From: John Nagle on
I've been looking at existing code, using Google Code search,
to see what use cases for "setattr" are actually used in production
code. High-performance implementations like Shed Skin try to
avoid dynamic creation of attributes, so it's worth seeing where
this feature is used in production.

1. Copying

"setattr" is used by "copy" and "pickle" to construct new
objects without calling their constructors. This is seen only in
code which also uses the CPython feature that the class of an object
can be changed by storing into the "__class__" attribute.

2. Proxying

A local object is being created as a proxy for some remote object.
This shows up in the Python shim for Remember the Milk, in the
wrapper for a restricted execution shell ""

3. Representation of some other data structure.

This is typically seen where some XML or JSON structure has been
translated into a tree of Python objects, and attribute access is being
used to access the data from the original object. This can result
in name clashes with existing attributes and keywords. Used by

4. Ordered dictionaries

"" uses "setattr", but with the comment "FIXME", noting
that unrestricted "setattr" can break the built-in attributes.

5. Enums

The Google Wave API uses "setattr" in StringEnum, which creates
an enumeration-like object.

6. Test platforms

"setattr" is used in "Mocker" to insert shim objects for test
purposes. This is a special case of proxying.

Note that in all the above cases, "setattr" is being used during
(or even prior to) object construction. It's rarely used on "live"

For the above cases, a mechanism for constructing general objects
would do the job. Something like

attrdict = { 'a' : 1, 'b' : 2 }
obj = make_object('classname', attrdict)

There are clearly use cases for dynamic object construction, but
modifying the structure of an object after creation is quite rare.

John Nagle