Code redundancy

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Apr 21 11:38:35 CEST 2010


Alan Harris-Reid wrote:
> Jean-Michel Pichavant 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?
>>>
>>> Any help would be appreciated.
>>>
>>> Alan Harris-Reid
>> Hello,
>>
>> Use an effective text editor, repeating stuff should not be a 
>> problem. In a more general manner, avoid trying to speed your writing 
>> while you should care speeding the reading.
>> Most of the tricks you could use will confuse the reader (unless the 
>> reader is familiar with Visual foxpro).
>>
>> Anyway,
>>
>> for attrName, value in [
>>    ('attr1', 1),
>>    ('attr2', 2),
>>    ('attr3', 3),
>>    ]:
>>    setattr(class1, attrName, value)
>>
>> or
>>
>> class Foo:
>>    def __init__(self):
>>       self.attr1=None
>>       self.attr2=None
>>       self.attr3=None
>>
>>    def set(self, *args, **kwargs):
>>       for k in kwargs:
>>          if hasattr(self, k):
>>              setattr(self, k, kwargs[k])
>>          else:
>>            raise AttributeError('%s instance has no attribute "%s"' % 
>> (self.__class__.__name__, k))
>>
>> f = Foo()
>> f.set(attr1=25)
>> print f.__dict__
>> f.set(attr3=4, attr2=89)
>> print f.__dict__
>> f.set(bar= 8)
>>
>> output:
>> {'attr2': None, 'attr3': None, 'attr1': 25}
>> {'attr2': 89, 'attr3': 4, 'attr1': 25}
>> AttributeError: Foo instance has no attribute "bar"
>>
>>
>> JM
>>
> Hi Jean-Michel,
>
> Interesting solutions, but I think for the effort involved (and 
> readability) I'll stick to repeating the class.
>
> Regards,
> Alan
that's the way to go :)

JM



More information about the Python-list mailing list