Code redundancy

Peter Otten __peter__ at web.de
Tue Apr 20 12:05:17 EDT 2010


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



More information about the Python-list mailing list