Python dynamic attribute creation

Alexander Kapps alex.kapps at web.de
Sat Jun 26 12:01:59 EDT 2010


Ixokai wrote:

> In what possible way is:
> 
>     setattr(foo, 'new_attr', 'blah')
>     getattr(foo, 'new_attr')
>     delattr(foo, 'new_attr')
> 
> Better then:
> 
>     foo.new_attr = 'blah'
>     foo.new_attr
>     del foo.new_attr
> 
> I don't understand what your argument is or problem is with the regular 
> syntax, if you want to allow the former (all of which is currently 
> possible in Python if you prefer this style) but not the latter (all of 
> which also works, it just uses normal syntax as everyone would expect).
> 
> Do you think it should be somehow "tricky" or "more difficult" to 
> dynamically modify an instance at runtime? For that to hold, you have to 
> provide some pretty compelling reasoning why dynamically modifying an 
> instance at runtime is Not Good. Only then is there a good reason to 
> make it more difficult. (Since Python doesn't really restrict things, 
> just makes certain rare things that are undesirable a little harder to do)
> 
> --Stephen
> 

While I personally don't agree with this proposal (but I understand 
why some people might want it), I can see a reason.

When disallowing direct attribute creation, those typos that seem to 
catch newcommers won't happen anymore. What I mean is this:

class Foo(object):
     def __init__(self):
         self.somearg = 0

f = Foo()
f.soemarg = 42

---^ There, typo, but still working

It's something like a custom __setattr__ that errors out when trying 
to assign to an attribute that doesn't exists, just as default behavior.

Sure, unittest are the Right Way(tm) to handle this, but there is a 
learning curve for new programmers wrt unittest. And disallowing 
this, doesn't take away any dynamism since setattr and friends are 
still there.

Anyway, since I do a lot interactive programming I don't want it. It 
would hinder me a lot.



More information about the Python-list mailing list