Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Blog | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python descriptors are not transparent when they're first used



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.







BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org