On 02/28/2013 02:47 PM, 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)
> # ...
>
> Thanks
> J^n
>
>


I often use this convenience function:

def getitem(seq, index, default=None):
"""Get item from an `seq` at `index`, return default if index out of range."""
try : return seq[index]
except IndexError : return default


If you're ok with setting myparm values to default None, you can do:

self.myparm1, self.myparm2, self.myparm3, self.myparm4 = \
(getitem(arglist, n) for n in range(4))


If you only want to set them when they are in arglist:

for n in range(4):
val = getitem(arglist, n)
if val is not None:
setattr(self, "myparm%d" % (n+1), val)

-m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

“So many books, so little time.”
― Frank Zappa

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to