Question on overriding implicit lookups

  • Thread starter Bruno Desthuilliers
  • Start date
B

Bruno Desthuilliers

David Ells a écrit :
In Python we have a wonderful facility for customizing attribute
access by defining __getattr__ or __getattribute__ in our classes.
Unfortunately (or perhaps fortunately, for reasons I don't know), this
facility only works for explicit attribute access, i.e. accessing
foo.bar. What I am in need of, for reasons I'll keep out of the
discussion for now, is a similar facility for implicit attribute
access, such as the call to foo.__len__ when something like len(foo)
is executed. I would like some way to customize access during these
implicit lookups without having to define each one in the class
myself. Essentially what I am looking for is a mechanism like
__getattribute__, only one that will work for these implicit lookups
to functions like __len__, __str__, __getitem__, and so on. Hopefully
my question makes sense.

An obvious solution would be to define "each one" of these magic methods
in a mixin class. Else, here's a Q&D but working solution :

class Test(object):
def _get_magic_attribute(self, name):
return "YADDA YADDA"

for _name in ('__len__', '__str__', '__repr__'):
exec "%s = lambda self, _name='%s' : " \
"self._get_magic_attribute(_name)" % (_name, _name)
del _name

For a cleaner version, you may want to use a custom metaclass, but that
seems a bit overkill to me.
 
D

David Ells

In Python we have a wonderful facility for customizing attribute
access by defining __getattr__ or __getattribute__ in our classes.
Unfortunately (or perhaps fortunately, for reasons I don't know), this
facility only works for explicit attribute access, i.e. accessing
foo.bar. What I am in need of, for reasons I'll keep out of the
discussion for now, is a similar facility for implicit attribute
access, such as the call to foo.__len__ when something like len(foo)
is executed. I would like some way to customize access during these
implicit lookups without having to define each one in the class
myself. Essentially what I am looking for is a mechanism like
__getattribute__, only one that will work for these implicit lookups
to functions like __len__, __str__, __getitem__, and so on. Hopefully
my question makes sense.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top