Python dynamic attribute creation

WANG Cong xiyou.wangcong at gmail.com
Fri Jun 25 23:58:38 EDT 2010


On 06/25/10 19:38, Ethan Furman <ethan at stoneleaf.us> wrote:

> WANG Cong wrote:
>> On 06/25/10 15:34, Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote:
>>
>>> WANG Cong a écrit :
>>>> Hi, list!
>>>>
>>>> I have a doubt about the design of dynamic attribute creation by
>>>> assignments in Python.
>>>>
>>>> As we know, in Python, we are able to create a new attribute of
>>>> a class dynamically by an assignment:
>>>>
>>>>>>> class test: pass
>>>> ... 
>>>>>>> test.a = "hello"
>>>>>>> test.a
>>>> 'hello'
>>>>
>>>> However, I still don't get the points why Python designs it like this.
>>>>
>>>> My points are:
>>>>
>>> (snip)
>>>
>>> Python's classes are plain objects, and like any other object are
>>> created at runtime. Having to special-case them would break the
>>> simplicity and uniformity of Python for no good reason. Just like
>>> there's no good reason to make setattr() working differently for class
>>> and non-class objects.
>>>
>>
>> For implementaiton, perhaps, but not for the language design, how could
>> a language design be perfect if we can use setattr() like assignments
>> while use other things, e.g. delattr(), not? Is there any way to express
>> delattr() as simple as expressing setattr() with assignments? I doubt...
>
>>>> del test.a
>>>> test.a
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: class test has no attribute 'a'
>
> Looks pretty simple to me...
>

Ah, thanks for teaching this! I should think out it.

So, this is much related with the fact that Python treats class
attributes as dictionary keys and their values as dictionary values,
thus unifies with the operations of dictionary.

But this is still questionable. Dictionary keys can be constants and
variable values, I mean:

>>> foo['constant'] = 'blah'
>>> foo[foo['constant']] = 'blah'

however, class attributes not, they are constants only _at least_ in
simple assignments.

I searched in google and found that Python already had a proposal for
dynamic attribute names [1], but it is rejected (surprisingly!). Thus,
for people who want to really dynamic attribute names, he/she has to
switch to setattr(). Isn't this what I insist? :)

1. http://www.python.org/dev/peps/pep-0363/

-- 
Live like a child, think like the god.
 



More information about the Python-list mailing list