Python dynamic attribute creation

Chris Rebert clp2 at rebertia.com
Tue Jun 29 12:57:45 EDT 2010


On Tue, Jun 29, 2010 at 9:48 AM, WANG Cong <xiyou.wangcong at gmail.com> wrote:
> On 06/27/10 12:01, Carl Banks <pavlovevidence at gmail.com> wrote:
>> On Jun 25, 8:24 pm, WANG Cong <xiyou.wangc... at gmail.com> wrote:
>>> Understand, but please consider my proposal again, if we switched to:
>>>
>>> setattr(foo, 'new_attr', "blah")
>>>
>>> by default, isn't Python still dynamic as it is? (Please teach me if I
>>> am wrong here.)
>>>
>>> This why I said the questionable thing is not so much related with dynamic
>>> programming or not.
>>
>> Because it makes dynamicism harder to do.
>>
>> Like I said, Python's goal isn't simply to make dynamicism possible,
>> it's to make it easy.
>>
>> "foo.new_attr = 'blah'" is easier than using setattr.
>
> I do agree it's easier, but why do we need this to be easy? This is
> really my question.

Conversely: Why do we need to make it harder than necessary?

> Also, since it is easier, why not drop the harder one, setattr()?

Because there's no way to write the following without using setattr()
or similar, aside from adding new syntax:

attr_name = raw_input("Enter an identifier: ")
setattr(x, attr_name, 42)

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list