Python dynamic attribute creation

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Jun 28 06:33:05 EDT 2010


Alexander Kapps a écrit :
(snip)
> 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,

Chicken and egg problem, really :  f.__dict__['somearg'] doesn't exists 
until "self.somearg = 0" is executed.

The "problem" is that Python's methods are only thin wrapper around 
functions (cf http://wiki.python.org/moin/FromFunctionToMethod) so 
there's no difference between "self.somearg = 0" in Foo.__init__ and 
"f.somearg = 42".

IOW, there's no way to implement this proposal without completely 
changing Python's object model.



More information about the Python-list mailing list