[Python-Dev] Python-Dev Digest, Vol 85, Issue 71 (original) (raw)

John Nagle nagle at animats.com
Tue Aug 24 21:37:42 CEST 2010


On 8/24/2010 12:40 AM, python-dev-request at python.org wrote:

Message: 4 Date: Mon, 23 Aug 2010 17:21:50 -0700 From: Brett Cannon <brett at python.org> It is also non-obvious to any beginner. Are we really going to want to propagate the knowledge of this trick as a fundamental idiom? I would rather leave hasattr in that instance. But I'm +1 on only swallowing AttributeError.

I'd argue that since the ability to inherit a class from "dict"

was added, dynamically adding attributes is somewhat obsolete. An object instance is not a dictionary. Especially since its namespace interacts with the namespace of its class.

I've been using Google Code Search to look at the actual use

cases for "setattr". The main uses are:

1.  Copying.  Object copying is done with "setattr".
    All the "setattr" objects occur during object
    construction, or shortly after.

2.  Creating proxy objects for remote access.  This is
    much like copying,

3.  Representing HTML objects as
    Python object.  This usually requies gyrations to
    avoid clashes with Python built-in names and
    functions; "class" is a common attribute in
    HTML, and a reserved word in Python, and some hack
    is necessary to make that work.  BeautifulSoup
    does this.

It's rare that attributes are added long after object construction. Perhaps a mechanism should be provided for dynamically constructing an object. Something like

class foo(object) :
    pass

attrdict = { a : 1, b : 2}
make_object(foo, attrdict)

This covers most of the use cases for "setattr".

                John Nagle


More information about the Python-Dev mailing list