The code that could not be...

Alex A. Naanou alex.nanou at gmail.com
Wed Jun 21 20:40:44 EDT 2006


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 (the dict is accessed directly).


Here is a 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.

you can download it here:
http://pli.sourceforge.net/object_dict_interface_use_fix.patch


So, to the purpose of this post... if there is any interest for a patch
like this, 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 :) )




More information about the Python-list mailing list