Python dynamic attribute creation

Neil Hodgson nyamatongwe+thunder at gmail.com
Sat Jun 26 06:40:05 EDT 2010


WANG Cong:

> From what you are saying, Smalltalk picks a way similar to setattr() in
> Python?

   addInstVarName is a method on ClassDescription objects.

> Because you mentioned 'addInstVarName' which seems to be a
> method or a builtin function. If so, that is my point, as I mentioned
> earlier, switching to setattr() by default, instead of using assignments
> by default. :)

   No, that was only part of the problems you enumerated. You want to
easily distinguish adding instance variables (possibly also other
things) since these are 'metaprogramming'. Now, once setattr is
available it is possible to call setattr any place where a function can
be called so you are not going to be able to determine whether any
particular statement, including o.f=1 adds a new instance variable. You
would have to change Python a lot more to be able to determine easily
from inspection whether a given statement is 'metaprogramming'.

   The main problem I had was that you were saying that adding an
instance variable is a special form of programming when its just an
ordinary part of programming in most languages.

> Hmm, although this is off-topic, I am interested in this too. C++ does
> have metaprogramming, but that is actually static metaprogramming (using
> templates), not dynamic metaprogramming here.

   C++ is still extremely limited. Can you show a C++ example where a
metaprogram modifies an existing class to add an instance variable?

   Neil



More information about the Python-list mailing list