Code redundancy

Alan Harris-Reid aharrisreid at googlemail.com
Tue Apr 20 17:37:52 EDT 2010


Peter Otten wrote:
> Alan Harris-Reid wrote:
>
>   
>> Hi,
>>
>> During my Python (3.1) programming I often find myself having to repeat
>> code such as...
>>
>> class1.attr1 = 1
>> class1.attr2 = 2
>> class1.attr3 = 3
>> class1.attr4 = 4
>> etc.
>>
>> Is there any way to achieve the same result without having to repeat the
>> class1 prefix?  Before Python my previous main language was Visual
>> Foxpro, which had the syntax...
>>
>> with class1
>>    .attr1 = 1
>>    .attr2 = 2
>>    .attr3 = 3
>>    .attr4 = 4
>>    etc.
>> endwith
>>
>> Is there any equivalent to this in Python?
>>     
>
> No. You could write a helper function
>
>   
>>>> def update(obj, **kw):
>>>>         
> ...     for k, v in kw.items():
> ...             setattr(obj, k, v)
> ...
>
> and then use keyword arguments:
>
>   
>>>> class A: pass
>>>>         
> ...
>   
>>>> a = A()
>>>> update(a, foo=42, bar="yadda")
>>>> a.foo, a.bar
>>>>         
> (42, 'yadda')
>   
>
> But if you are doing that a lot and if the attributes are as uniform as 
> their names suggest you should rather use a Python dict than a custom class.
>
>   
>>>> d = {}
>>>> d.update(foo=42, bar="whatever")
>>>> d
>>>>         
> {'foo': 42, 'bar': 'whatever'}
>   
>>>> d["bar"]
>>>>         
> 'whatever'
>
> Peter
Hi Peter, thanks for the reply,

Interesting solution, but it looks as though it may be easier to repeat 
the class prefix a few times.

Alan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100420/dcec8f6d/attachment.html>


More information about the Python-list mailing list