473,387 Members | 1,789 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Type emulation issues with new style classes

Is there any way to make the class Z behave the same way as class Y?

Chris

class Y:
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __getattr__(self, name):
if name == '__int__':
return lambda: self.value

class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __getattr__(self, name):
if name == '__int__':
return lambda: self.value
y, z = Y(), Z()
print int(y) 42 print int(z)

TypeError: int() argument must be a string or a number
Jul 18 '05 #1
16 1655
class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __int__(self):
return self.value

Umm, maybe I haven't understood what you need.

--
Don't you know why your Python application has crashed?
Take a look to http://www.pycrash.org
--
Posted via Mailgate.ORG Server - http://www.Mailgate.ORG
Jul 18 '05 #2
I need to have Python call the the emulation methods for numbers, lists,
etc, when those methods are provided though __getattr__ rather than defined
in the instance or class __dict__. I've been up and down PEP 252 trying to
determine how Python determines the presence or absence of emulation methods
for new style classes, but I'm not having any luck.

"Carmine Noviello" wrote:
class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __int__(self):
return self.value
Umm, maybe I haven't understood what you need.


I need to know how I can do what I previously demonstrated with an old style
class, that is hook into Python's introspection mechanism to dynamically
provide an __int__ method (or optionally __str__, __lt__, __le__, __eq__
,__ne__, __gt__, __ge__, __len__, __getitem__, __add__, __sub__, __mul__,
__floordiv__, __mod__, __divmod__, __pow__, __lshift__, ... ad nausuem).
Old style classes will let me do this, but I cannot determine how to do this
with new style classes.

Chris
Jul 18 '05 #3
In article <C0****************@nwrdny03.gnilink.net>,
Chris <fe*************@spamgourmet.com> wrote:

class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __getattr__(self, name):
if name == '__int__':
return lambda: self.value


IIRC, __getattribute__ may do what you want, but I don't have time to
check.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"Do not taunt happy fun for loops. Do not change lists you are looping over."
--Remco Gerlich, comp.lang.python
Jul 18 '05 #4
Tried it earlier, same result.

Chris

"Aahz" wrote:
IIRC, __getattribute__ may do what you want, but I don't have time to
check.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/
"Do not taunt happy fun for loops. Do not change lists you are looping over." --Remco Gerlich, comp.lang.python

Jul 18 '05 #5
"Chris" <fe*************@spamgourmet.com> writes:
Is there any way to make the class Z behave the same way as class Y?


You need a custom metaclass for Z, and implement __getattr__ there.

HTH.

Cheers,
mwh

--
Lisp does badly because we refuse to lie. When people ask us if
we can solve insoluble problems we say that we can't, and because
they expect us to lie to them, they find some other language
where the truth is less respected. -- Tim Bradshaw, comp.lang.lisp
Jul 18 '05 #6
I tried a couple variation of that, and __getattr__, when defined in a
metaclass is never called when accessing an attribute on an instance of a
class derived from that metaclass.

Here is some testing I did:

class Zmeta(type):
def __getattribute__(*args):
raise Exception('called __getattribute__ with %s' % str(args))
def __getattr__(*args):
raise Exception('called __getattr__ with %s' % str(args))

Z = Zmeta('Z', (), {'value': 42})
z = Z()
int(z) TypeError: int() argument must be a string or a number z.__int__ AttributeError: 'Z' object has no attribute '__int__' Z.__int__
Exception: called __getattribute__ with (<class '__main__.Z'>, '__int__')

It appears (and is confirmed in: Metaclass Programming in Python Pt. 2
http://www-106.ibm.com/developerwork...a2/?ca=dnt-434) that
metaclass attributes are available to instances (classes) but not instances
of instances.

Chris

"Michael Hudson" wrote:
Is there any way to make the class Z behave the same way as class Y?


You need a custom metaclass for Z, and implement __getattr__ there.

HTH.

Cheers,
mwh

--
Lisp does badly because we refuse to lie. When people ask us if
we can solve insoluble problems we say that we can't, and because
they expect us to lie to them, they find some other language
where the truth is less respected. -- Tim Bradshaw, comp.lang.lisp

Jul 18 '05 #7
Chris wrote:
class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __getattr__(self, name):
if name == '__int__':
return lambda: self.value

def __int__(self):
return self.__getattr__('__int__')()
--
Rainer Deyke - ra*****@eldwood.com - http://eldwood.com
Jul 18 '05 #8
On Sat, 28 Feb 2004 11:33:54 GMT, "Chris" <fe*************@spamgourmet.com>
wrote:
class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __getattr__(self, name):
if name == '__int__':
return lambda: self.value


The following allows your test case to work, but it may have various subtle
problems. AddDynOper emulates __getattr__ semantics: the descriptor is not
installed if the type already has an attribute of the given name:

class DynOperDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, instance, typ):
if instance is None:
return self
return instance.__getattr__(self.name)

def AddDynOper(declcls, name):
if not hasattr(declcls, name):
setattr(declcls, name, DynOperDescr(name))

class Z(object):
value = 42
def __getattr__(self, name):
if name == "__int__":
return lambda : self.value
raise AttributeError(name)
AddDynOper(Z, "__int__")

---
Greg Chapman

Jul 18 '05 #9
I'm looking for a way to do this without explicity definining every
emulation method, i.e. (__str__, __lt__, __le__, __eq__, __ne__, __gt__,
__ge__, __len__, __getitem__, __add__, __sub__, __mul__, __floordiv__,
__mod__, __divmod__, __pow__, __lshift__, ... ad nausuem). Plus, there's a
few this isn't going to work for several of the the arithmetic operators,
such as when I want to have __add__ undefined so Python will attpemt
__radd__. For example:

class Y:
value = 42
def __getattr__(self, name):
if name == '__coerce__':
raise AttributeError
if name == '__add__':
raise AttributeError
if name == '__radd__':
return lambda other: self.value + other.value
y1, y2 = Y(), Y()
print int(y1) #This works 42 print y1 + y2 #This works too 84

class Z(object):
value = 42
def __getattr__(self, name):
if name == '__add__':
raise AttributeError
if name == '__radd__':
return lambda other: Z.value + Z.value
if name == '__int__':
return lambda: self.value
def __int__(self):
return self.__getattr__('__int__')()
def __add__(self, other):
return self.__getattr__('__add__')()
def __radd__(self, other):
return self.__getattr__('__radd__')()

z1, z2 = Z(), Z()
# This following will work now, after explicitly
# adding __int__ to the namespace of Z, which I'm
# trying to avoid.
print int(z1) 42 print y1 + y2 # This bombs
TypeError: 'NoneType' object is not callable

"Rainer Deyke" wrote: Chris wrote:
class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __getattr__(self, name):
if name == '__int__':
return lambda: self.value

def __int__(self):
return self.__getattr__('__int__')()
--
Rainer Deyke - ra*****@eldwood.com - http://eldwood.com

Jul 18 '05 #10
I tried your suggestion, but it breaks down when in the case where I want a
emulation method to be undefined. See example below.

Okay, it looks lke I'm going to have to come to the realization that there
is no way to hook into Python's test for the existance of emulation methods,
so I'm going to have to explicitly define every single possible emulation
method, from __add__ to __xor__. But still, how do I have __add__ return a
special value or throw a special exception so that the interpreter will then
move on to try __radd__?

### Works with old style classes ###
class Y:
value = 42
def __getattr__(self, name):
if name == '__coerce__':
raise AttributeError
if name == '__add__':
raise AttributeError
if name == '__int__':
return lambda: self.value
if name == '__radd__':
return lambda other: self.value + other.value
y1, y2 = Y(), Y()
print int(y1) 42 print y1 + y2 84
### With new style classes, __radd__ is never called ###
class DynOperDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, instance, typ):
if instance is None:
return self
return instance.__getattr__(self.name)

def AddDynOper(declcls, name):
if not hasattr(declcls, name):
setattr(declcls, name, DynOperDescr(name))

class Z(object):
value = 42
def __getattr__(self, name):
if name == '__radd__':
return lambda other: Z.value + Z.value
if name == '__int__':
return lambda: self.value
raise AttributeError(name)

AddDynOper(Z, "__int__")
AddDynOper(Z, "__add__")
AddDynOper(Z, "__radd__")
z1, z2 = Z(), Z()
print int(z1) 42 print z1 + z2
AttributeError: __add__
"Greg Chapman" wrote: On Sat, 28 Feb 2004 11:33:54 GMT, "Chris" <fe*************@spamgourmet.com> wrote:
class Z(object):
value = 42
def __hasattr__(self, name):
if name == '__int__':
return True
def __getattr__(self, name):
if name == '__int__':
return lambda: self.value
The following allows your test case to work, but it may have various

subtle problems. AddDynOper emulates __getattr__ semantics: the descriptor is not installed if the type already has an attribute of the given name:

class DynOperDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, instance, typ):
if instance is None:
return self
return instance.__getattr__(self.name)

def AddDynOper(declcls, name):
if not hasattr(declcls, name):
setattr(declcls, name, DynOperDescr(name))

class Z(object):
value = 42
def __getattr__(self, name):
if name == "__int__":
return lambda : self.value
raise AttributeError(name)
AddDynOper(Z, "__int__")

---
Greg Chapman

Jul 18 '05 #11
Chris wrote:
I'm looking for a way to do this without explicity definining every
emulation method, i.e. (__str__, __lt__, __le__, __eq__, __ne__,
__gt__, __ge__, __len__, __getitem__, __add__, __sub__, __mul__,
__floordiv__, __mod__, __divmod__, __pow__, __lshift__, ... ad
nausuem).
You can get away with mentioning all of those names only once in your code.

class IndirectionMixins(object):
pass

def add_indirection_method(name):
def f(self, *args, **kwargs):
return self.__getattr__(name)(*args, **kwargs)
setattr(IndirectionMixins, name, f)

for name in ['__str__', '__lt__', ...]:
add_indirection_method(name)

class Y(IndirectionMixins):
...
Plus, there's a few this isn't going to work for several
of the the arithmetic operators, such as when I want to have __add__
undefined so Python will attpemt __radd__.


That's harder. It might be possible with metaclasses.
--
Rainer Deyke - ra*****@eldwood.com - http://eldwood.com
Jul 18 '05 #12
"Chris" <fe*************@spamgourmet.com> wrote in message news:<Fz*****************@nwrdny02.gnilink.net>...
I need to know how I can do what I previously demonstrated with an old style
class, that is hook into Python's introspection mechanism to dynamically
provide an __int__ method (or optionally __str__, __lt__, __le__, __eq__
,__ne__, __gt__, __ge__, __len__, __getitem__, __add__, __sub__, __mul__,
__floordiv__, __mod__, __divmod__, __pow__, __lshift__, ... ad nausuem).
Old style classes will let me do this, but I cannot determine how to do this
with new style classes.

Chris


You may want to look at this thread:

http://groups.google.it/groups?hl=it....lang.python.*

It does not solve your problem, but it may be of some interest.

Michele Simionato
Jul 18 '05 #13
"Chris" <fe*************@spamgourmet.com> wrote in message news:<6O*****************@nwrdny03.gnilink.net>...
I tried a couple variation of that, and __getattr__, when defined in a
metaclass is never called when accessing an attribute on an instance of a
class derived from that metaclass.


You may also look at this bug report:

http://sourceforge.net/tracker/?grou...ail&aid=789262

The special lookup of special attributes has bitten at least three or four
person on this mailing list in the last year or so: I maintain that
it is a documentation bug.

Michele Simionato
Jul 18 '05 #14
That's my bug! That's exactly the problem I'm having. Thanks for the info,
it looks like I'll have to create a mixin class that manually defines all
emulation methods, but will be broken for __radd__, __rsub__, __rmul__,
etc... but as long as I make a note of it in the documentation, it should
be okay.

Thanks showing me the bug report.

Chris

"Michele Simionato" wrote:
"Chris" <fe*************@spamgourmet.com> wrote in message news:<6O*****************@nwrdny03.gnilink.net>...
I tried a couple variation of that, and __getattr__, when defined in a
metaclass is never called when accessing an attribute on an instance of a class derived from that metaclass.


You may also look at this bug report:

http://sourceforge.net/tracker/?grou...ail&aid=789262
The special lookup of special attributes has bitten at least three or four
person on this mailing list in the last year or so: I maintain that
it is a documentation bug.

Michele Simionato

Jul 18 '05 #15
"Chris" <fe*************@spamgourmet.com> writes:
I tried a couple variation of that, and __getattr__, when defined in a
metaclass is never called when accessing an attribute on an instance of a
class derived from that metaclass.

Here is some testing I did:

class Zmeta(type):
def __getattribute__(*args):
raise Exception('called __getattribute__ with %s' % str(args))
def __getattr__(*args):
raise Exception('called __getattr__ with %s' % str(args))

Z = Zmeta('Z', (), {'value': 42})
z = Z()
int(z) TypeError: int() argument must be a string or a number z.__int__ AttributeError: 'Z' object has no attribute '__int__' Z.__int__

Exception: called __getattribute__ with (<class '__main__.Z'>, '__int__')

It appears (and is confirmed in: Metaclass Programming in Python Pt. 2
http://www-106.ibm.com/developerwork...a2/?ca=dnt-434) that
metaclass attributes are available to instances (classes) but not instances
of instances.


Argh. Yes, now I think about the implementation, this isn't that
surprising. OTOH, one shouldn't have to know Objects/typeobject.c as
well as I do to avoid being surprised by Python...

I've added some more detailed comments to the bug report Michele
mentioned, if you're curious.

Cheers,
mwh

--
SCSI is not magic. There are fundamental technical reasons why it
is necessary to sacrifice a young goat to your SCSI chain now and
then. -- John Woods
Jul 18 '05 #16
In article <95**************************@posting.google.com >,
Michele Simionato <mi***************@poste.it> wrote:

You may also look at this bug report:

http://sourceforge.net/tracker/?grou...ail&aid=789262

The special lookup of special attributes has bitten at least three or four
person on this mailing list in the last year or so: I maintain that
it is a documentation bug.


Just as a reminder, here's a nifty way of reporting SF URLs that makes
life easier:
http://www.python.org/sf/789262
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"Do not taunt happy fun for loops. Do not change lists you are looping over."
--Remco Gerlich, comp.lang.python
Jul 18 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Michal Vitecek | last post by:
hello, does the type() command work correctly for new style classes? i guess it does not, unfortunately. for example, for a new style class' instance it returns <class '__main__.ClassName'>, but...
5
by: Batista, Facundo | last post by:
I'm proud to announce that the PEP for Decimal Data Type is now published under the python.org structure: http://www.python.org/peps/pep-0327.html This wouldn't has been possible without the...
3
by: ShadowMan | last post by:
Hi all I've seen a lot of posts about frames emulation. I would like to emulate a: header, left-side menu, content, footer layout. I need to be cross browser compatible...but I'm get crazy!!!...
3
by: Serge Skorokhodov (216716244) | last post by:
Hi, I just seeking advice. Some background information first because I've run into issues that seems pretty obscure to me:( Quick search through KB yields next to nothing. Simplified samples...
4
by: Kevin Newman | last post by:
The primary problem I've had with php is the lack of namespaces, which makes OOP very difficult to organize, since you end up with large number of classes cluttering up the same namespace - which...
28
by: VK | last post by:
A while ago I wrote a "Vector data type" script using DOM interface to select.options. That was a (beautiful) mind game :-) rather than a practical thing to use. Here is another attempt open...
5
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a...
8
by: =?Utf-8?B?ZG1idXNv?= | last post by:
I'm migrating a VB.NET 2003 application to VB.NET 2008. The 2003 app used the June 2005 Enterprise Library while I'm going to use the latest EntLib, 4.0 - May 2008. I copied the 2003 app to a...
21
by: Nikolaus Rath | last post by:
Hello, Can someone explain to me the difference between a type and a class? After reading http://www.cafepy.com/article/python_types_and_objects/ it seems to me that classes and types are...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.