473,785 Members | 3,285 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, name):
if name == '__int__':
return lambda: self.value

class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, 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
16 1679
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__(sel f, 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(ob ject):
def __init__(self, name):
self.name = name
def __get__(self, instance, typ):
if instance is None:
return self
return instance.__geta ttr__(self.name )

def AddDynOper(decl cls, name):
if not hasattr(declcls , name):
setattr(declcls , name, DynOperDescr(na me))

class Z(object):
value = 42
def __getattr__(sel f, 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.c om> wrote:
class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, 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(ob ject):
def __init__(self, name):
self.name = name
def __get__(self, instance, typ):
if instance is None:
return self
return instance.__geta ttr__(self.name )

def AddDynOper(decl cls, name):
if not hasattr(declcls , name):
setattr(declcls , name, DynOperDescr(na me))

class Z(object):
value = 42
def __getattr__(sel f, 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 IndirectionMixi ns(object):
pass

def add_indirection _method(name):
def f(self, *args, **kwargs):
return self.__getattr_ _(name)(*args, **kwargs)
setattr(Indirec tionMixins, name, f)

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

class Y(IndirectionMi xins):
...
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.c om> wrote in message news:<Fz******* **********@nwrd ny02.gnilink.ne t>...
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.c om> wrote in message news:<6O******* **********@nwrd ny03.gnilink.ne t>...
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.c om> wrote in message news:<6O******* **********@nwrd ny03.gnilink.ne t>...
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.c om> 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('call ed __getattribute_ _ with %s' % str(args))
def __getattr__(*ar gs):
raise Exception('call ed __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**@pythoncra ft.com) <*> http://www.pythoncraft.com/

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

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

Similar topics

1
1337
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 for old style class' instance it returns <type 'instance'>. >>> import types >>> class A(object): pass
5
1395
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 help from Alex Martelli, Aahz, Tim Peters, David Goodger and c.l.p itself. After the pre-PEP roundups the features are almost established. There is not agreement yet on how to create a Decimal from a float, in both explicit and
3
4348
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!!! My code is above: it displays right on Firefox 1.0 but it doesn't on IE6. What should I change?! thanx --
3
1338
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 work OK as well, the problems appear in rather bulky code:( I'm trying to implement some signal processing algorithm using
4
3084
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 leads to a secondary problem involving php's __autoload feature. Since you cannot specify a namespace when calling a class that may not have been included, you are forced to store all of your classes in the same folder in your file system. This...
28
1954
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 for criticism, this time dead serious. I really need an effective Vector emulator for a project (as much effective as something not implemeted in language but emulated by means of the language itself is: a
5
3175
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 instance is created by "calling" a class object.
8
1711
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 new 2008 folder structure, recreated the app.config using the new 4.0 EntLib config tool, and referenced the 4.0 Microsoft.Practices.EnterpriseLibrary.Data.dll file. The problem is there is a Function that has errors in it and I'm not sure how to...
21
5202
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 actually the same thing: - both are instances of a metaclass, and the same metaclass ('type') can instantiate both classes and types. - both can be instantiated and yield an "ordinary" object - I can even inherit from a type and get a class
0
9643
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10315
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10085
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9947
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5379
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4045
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.