Code redundancy

Iain King iainking at gmail.com
Tue Apr 20 16:54:29 CEST 2010


On Apr 20, 2:43 pm, Alan Harris-Reid <aharrisr... at googlemail.com>
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?
>
> Any help would be appreciated.
>
> Alan Harris-Reid

The pythonic equivalent of VB 'with' is to assign to a short variable
name, for example '_':

_ = class1
_.attr1 = 1
_.attr2 = 2
_.attr3 = 3
_.attr4 = 4

alternatively, you could use the __setattr__ method:

for attr, value in (
    ('attr1', 1),
    ('attr2', 2),
    ('attr3', 3),
    ('attr4', 4)):
    class1.__setattr__(attr, value)

and to get a bit crunchy, with this your specific example can be
written:

for i in xrange(1, 5):
    class1.__setattr__('attr%d' % i, i)

Iain



More information about the Python-list mailing list