descriptor object for an attribute?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Apr 11 16:07:19 EDT 2007


Eric Mahurin a écrit :
> Is there a standard way to get a descriptor object for an arbitrary
> object attribute - independent of whether it uses the descriptor/
> property protocol or not.  I want some kind of handle/reference/
> pointer to an attribute.  

I'm not sure to understand what you want exactly. A concrete example 
would probably help. But from what I understood, you could just use a 
thin wrapper like:

_marker = object()
class Accessor(object):
   def __init__(self, obj, name):
     self._obj = obj
     self._name = name
   def __call__(self, new_val=_marker):
     if new_val is _marker:
       return getattr(self._obj, self._name)
     else:
       setattr(self._obj, self._name, new_val)


class Foo(object):
   def __init__(self, bar, baak=42):
     self.bar = bar
     self.baak = baak

foo = Foo('allo')
bar = Accessor(foo, 'bar')

assert bar() == foo.bar == 'allo'
bar(42)
assert bar() == foo.bar == 42

If that doesn't answer your question, please pardon my stupidity and 
provide some more concrete example.



More information about the Python-list mailing list