Python dynamic attribute creation

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Jul 2 04:54:14 EDT 2010


WANG Cong wrote:

> Yeah, my point is why setattr() for dynamic attributes while assignments
> for static attributes?

I think there may be a misunderstanding here. You seem to
be thinking of "dynamic attribute" vs. "static attribute"
as the distinction between creating a new attribute and
modifying an existing one.

But that's not what it means in this context -- "dynamic"
just means that the attribute name is being computed rather
than written into the program. In either case, the attribute
may or may not be pre-existing.

> Why not unify them?

If you mean using exactly the same syntax for both, that would
require making the static case more verbose, e.g. instead of

    foo.blarg

you would have to write something like

    foo.("blarg")

just to allow for the possibility of writing

    foo.(some_arbitrary_expression)

If you keep the existing static-attribute syntax, then you
haven't really unified anything, you've just added a new
syntax for dynamic attributes. And because dynamic attribute
access is extremely rare, it's not considered worth having
a special syntax for it. It's been suggested before, and
rejected on those grounds.

-- 
Greg



More information about the Python-list mailing list