The code that could not be...

Jun 21, 2006 20:08

Though Python is the language I use the most, there are several things that I still hate, mostly about the implementation (CPython)...

The good thing is that some of these warts are now resolved, like the exec dict issue.

Here is another one:
The object's __dict__ can only be a dict derivative and at that none of the Python's mapping API will be used.


Here is simple example example that this problem makes impossible...

---cut---
class AttrDict(dict):
'''This implements JavaScript-like object attribute/mapping interface.'''
def __new__(cls, *p, **n):
o = dict.__new__(cls, *p, **n)
o.__dict__ = o
return o

# this works fine in current CPython...
o = AttrDict()
o.attr = 'val'
o['other'] = 123

print o.other # -> 123
print o # -> {'attr': 'val', 'other': 123}

# now if you modify this to add some logging...
def _getitem(self, name):
print 'getting "%s".' % name
return super(AttrDict, self).__getitem__(name)

AttrDict.__getitem__ = _getitem

# this will work as expected...
o['attr'] # -> getting "attr".

# and the following will not!
o.attr # will print nothing...

--uncut--

Thus, no user defined dict-like will work correctly as the objects namespace...

To mention several tasks that can be made trivial using this technique are, for instance zope-like acquisitions, various ACLs, interfaces and other namespace manipulation patterns.

I wrote a patch some time back, it appears rather stable and is being production tested.

So, to the purpose of this post... is there any interest for a patch like this and if so, anyone who would be willing to test it and/or add feedback to the topic would be very welcome! :)

P.S. I'm not proposing this patch to the python-dev until it is extensively tested (and not just on my usecases :) )

python, programming, questions, patches

Previous post Next post
Up