Q: attribute access and comparisons of two different objects

Aloysio Figueiredo afigueiredo at elnetcorp.com.br
Tue Jun 15 10:16:06 EDT 2004


* Chris... <chris.schaller at web.de> [15-06-2004 10:52]:
> Two simple questions regarding future of Python:
> 
> 1) Is there already a "fix" to avoid writing to an attribute that
> isn't defined yet?  I remember this being an often discussed problem,
> but didn't see any changes.  The only way I can think of is overriding
> __setattr__, but this is huge overhead.  While I like the idea of
> being able to add new attributes on the fly, in great projects I'd
> like to restrict some classes not to do so.
> 

I have a "fix" in mind, but I would like the community to comment
because I don't know if it's good practice. What about using the __slots__
attribute to prevent creation of new attributes on the fly? 

>>> class foo(object):
...   __slots__ = ['attr1', 'attr2']
... 
>>> a = foo()
>>> a.attr1 = 2
>>> a.attr2 = 3
>>> a.attr3 = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  AttributeError: 'foo' object has no attribute 'attr3'
>>> 
  
__slots__ is documented in
http://www.python.org/doc/current/ref/slots.html

Aloysio
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040615/0af22bea/attachment.sig>


More information about the Python-list mailing list