extended setattr()
Diez B. Roggisch
deets at nospam.web.de
Tue Jul 8 13:25:55 EDT 2008
Andre Adrian wrote:
> Diez B. Roggisch <deets <at> nospam.web.de> writes:
>
>> > def ext_setattr(obj, attr, val):
>> > for subattr in attr.split("."):
>> > obj = getattr(obj, subattr)
>> > obj = val
>> >
>> >>>> import test
>> >>>> a = A()
>> > Traceback (most recent call last):
>> > File "<stdin>", line 1, in <module>
>> > NameError: name 'A' is not defined
>> >>>> a = test.A()
>> >>>> a.B.C.txt
>> > 'foo'
>> >>>> ext_setattr(a, 'B.C.txt', 'bar')
>> >>>> a.B.C.txt
>> > 'foo'
>> >
>> > What am i doing wrong?
>>
>> obj = val won't work.
>
> Why is this so? Shouldn't it be the same?
No, of course not!
obj = val
binds the object reffered to by val to the LOCAL name obj. That's python
101, make sure you get variables/names and scopes proper.
>> You need to use a setattr(obj, name, val)
>> on the last attribute-name.
>
> Ok, so this works:
>
> def ext_setattr(obj, attr, val):
> attributes = attr.split('.')
> for subattr in attributes[:-1]:
> obj = getattr(obj, subattr)
> setattr(obj, attributes[-1], val)
Yep.
Diez
More information about the Python-list
mailing list