Python descriptors are not transparent when they're first used
Seth Gordon
sethg-Dp9fwfP21SfQT0dZR+AlfA at public.gmane.org
Mon Jul 30 15:46:09 EDT 2007
For reasons too boring to describe here, I wanted objects in a certain
Python class to have attributes that could be written to once and only
once. After reading up on descriptors, I came up with this:
> class WriteOnly(object):
> """A descriptor that can be written to once and only once;
> If the descriptor has not yet been written to, then its
> value is None."""
>
> def __init__(self, name):
> self.__name = name
> self.__value = None
> self.__writable = True
>
> def __get__(self, obj, objtype):
> return self.__value
>
> def __set__(self, obj, value):
> if self.__writable:
> self.__value = value
> self.__writable = False
> else:
> msg = "Can't reset %s from %s to %s" % (self.__name,
> repr(self.__value),
> repr(value))
> raise AttributeError, msg
Then I set up a client class like this:
> class Foo(object):
> def __init__(self):
> for attr in ('bar', 'baz', 'quux'):
> self.__dict__[attr] = WriteOnly(attr)
>
> foo = Foo()
> foo.bar = 4
> foo.baz = None
> print `foo.bar`
> print `foo.baz`
> print `foo.quux`
Running that program (with Python 2.4.4) gives me this output:
> 4
> None
> <WriteOnly.WriteOnly object at 0xf7daa28c>
Why don't I get "None" on the third line? What subtle (or
not-so-subtle) detail of Python descriptors am I missing?
--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.
More information about the Discuss
mailing list