suggestions for improving code fragment please

Dave Angel davea at davea.name
Thu Feb 28 16:28:18 EST 2013


On 02/28/2013 03:37 PM, Tim Chase wrote:
> On 2013-02-28 19:47, The Night Tripper wrote:
>> Hi there
>>      I'm being very dumb ... how can I simplify this fragment?
>>
>>
>>          if arglist:
>>              arglist.pop(0)
>>              if arglist:
>>                  self.myparm1 = arglist.pop(0)
>>                  if arglist:
>>                      self.myparm2 = arglist.pop(0)
>>                      if arglist:
>>                          self.myparm3 = arglist.pop(0)
>>                          if arglist:
>>                              self.parm4 = arglist.pop(0)
>
> If they're arbitrarily named attributes of the "self", you could do
> something like
>
>    for attr in ("myparm1", "myparm2", "myparm3", ...):
>      if arglist:
>        setattr(self, attr, arglist.pop(0))
>      else:
>        break
>
> -tkc
>
>
>
Or something like (untested):

     for name, value in zip(["myparm1", "myparm2", "myparm3"], arglist):
          setattr(self, name, value)
     arglist = []     #if you care how it ends up


-- 
DaveA



More information about the Python-list mailing list