473,775 Members | 2,610 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Modifying an instances dict to change attribute lookup

Hmm, I know this is something fundamental about how Python implements
predicate dispatch, but for some reason I believed that this would
work:

class delegate_dict(d ict):
def __init__(self, orig, deleg):
dict.__init__(s elf, orig)
self.deleg = deleg

def __getitem__(sel f, name):
print 'here:', name
try:
v = dict.__getitem_ _(self, name)
except KeyError:
return self.deleg.__ge titem__(name)
return v

def delegate(target , source):
target.__dict__ = delegate_dict(t arget.__dict__, source.__dict__ )

As a simple usage, give:
class A(object):
pass

class B(object):
def __init__(self, o):
delegate(self, o)

a = A()
a.test = 1
b = B(a)
print b.__dict__.__ge titem__('test')

# This goes down in flames
print b.test
And then a dumb example showing the concept I assumed was a given:

class C(object):
pass

c = C()
c.x = 1
assert c.__dict__.__ge titem__('x') == c.x

Could someone please tell me why the first example using a customized
dict does not perform as advertised?

Feb 20 '06 #1
1 1310
js******@gmail. com <js******@gmail .com> wrote:
...
c = C()
c.x = 1
assert c.__dict__.__ge titem__('x') == c.x

Could someone please tell me why the first example using a customized
dict does not perform as advertised?


Because Python's __getattribute_ _ is currently not EXACTLY as you
imagine it to be, but slightly different, say something like:
dict.__getitem_ _(c, 'x')
at the crucial step rather than c.__getitem__. More generally, when (on
any type or newstyle class -- oldstyle legacy classes are different) a
special method gets implicitly invoked, it's invoked on the type, not on
the instance (no per-instance overriding in this case); and, for speed,
many internal dict lookups do "dict.__getitem __(obj,name)" rather than
"type(obj).__ge titem__(obj, name)".

The documented way to do what you want in Python is by overriding
__getattr__ (which gets called when other normal lookup procedures fail
and would, absent __getattr__, raise AttributeError) , not by trying to
install as the __dict__ something whose type isn't exactly __dict__.
Other approaches may work, but they depend on implementation accidents
which are liable to change with every passing breeze.
Alex
Feb 20 '06 #2

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

Similar topics

15
2500
by: Paul Paterson | last post by:
I am trying to find a way to mimic by-reference argument passing for immutables in Python. I need to do this because I am writing an automated VB to Python converter. Here's an example of the VB code: Sub Change(ByVal x, ByRef y) x = x+1 y = y+1 End Sub
22
35489
by: christof hoeke | last post by:
hello, this must have come up before, so i am already sorry for asking but a quick googling did not give me any answer. i have a list from which i want a simpler list without the duplicates an easy but somehow contrived solution would be >>> a = >>> d = {}.fromkeys(a) >>> b = d.keys()
12
2015
by: Christopher J. Bottaro | last post by:
If I have the following class: class MyClass: def __init__(self): m_dict = {} m_dict = 1 m_dict = 2 m_dict = 3 Is there anyway to generate automatic accessors to the elements of the dict?
21
1765
by: André | last post by:
Short version of what I am looking for: Given a class "public_class" which is instantiated a few times e.g. a = public_class() b = public_class() c = public_class() I would like to find out the name of the instances so that I could create a list of them e.g.
2
1765
by: Krzysztof Stachlewski | last post by:
I tried to run the following piece of code: Python 2.3.4 (#53, May 25 2004, 21:17:02) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> o = object() >>> o.a = 5 Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'object' object has no attribute 'a'
6
3451
by: David Rasmussen | last post by:
If I have a collection of dicts like: john = {'id': 1, 'name': "John Cleese", 'year': 1939} graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} I could store all of them in a list. But for easy lookup, I might store all these in a dict instead, like people = {'1': john, '2': graham}
90
4418
by: Ben Finney | last post by:
Howdy all, How can a (user-defined) class ensure that its instances are immutable, like an int or a tuple, without inheriting from those types? What caveats should be observed in making immutable instances? -- \ "Love is the triumph of imagination over intelligence." -- |
4
3324
by: Pedro Werneck | last post by:
Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a custom metaclass with a __getattribute__ method, the method is used when acessing some attribute directly with the class object, but not when you do it from the instance.
5
1476
by: Joseph Barillari | last post by:
Hi python-list, I've just started using new-style classes and am a bit confused as to why I can't seem to alter methods with special names (__call__, etc.) of new-style class instances. In other words, I can do this: .... pass .... 33
0
9622
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
10268
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
10048
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
9916
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
6718
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5360
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...
0
5486
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2853
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.