Code redundancy

A

Alan Harris-Reid

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
 
I

Iain King

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
 
P

Peter Otten

Alan said:
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
.... for k, v in kw.items():
.... setattr(obj, k, v)
....

and then use keyword arguments:

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top