Re: suggestions for improving code fragment please

Discussion in 'Python' started by Steven D'Aprano, Mar 1, 2013.

  1. On Thu, 28 Feb 2013 19:47:12 +0000, The Night Tripper wrote:

    > Hi there
    > I'm being very dumb ... how can I simplify this fragment?


    I suggest that the best way to simplify that fragment is to change the
    design of your class so it isn't so horrible. As it stands now, your
    class defines an arbitrary number of params, which *may or may not exist*:

    > 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)
    > # ...


    So using your class is a horrible experience:

    if hasattr(instance, 'param1'):
    do_something_with(instance.param1)
    else:
    fall_back_when_param1_doesnt_exist()
    if hasattr(instance, 'param2'):
    do_something_with(instance.param2)
    else:
    fall_back_when_param2_doesnt_exist()
    if hasattr(instance, 'param3'):
    print "Do you hate this class yet?"



    We have a perfectly good programming idiom to deal with a variable number
    of values: the list, or tuple if you prefer. So here's an alternative:

    self.params = arglist[1:]

    If order is not important:

    self.params = set(arglist[1:])


    If you have to map names to values:

    self.params = dict(
    ('param%d' % i, value) for i, value in enumerate(arglist[1:])
    )


    If you absolutely must have named attributes, I recommend that you choose
    a default value that indicates "missing". Conventionally, that is None,
    but you can always create your own sentinel value if needed:

    SENTINEL = object()
    arglist = arglist + [SENTINEL]*20
    for i in range(1, 21):
    setattr(self, 'param%d' % i, arglist)



    --
    Steven
    Steven D'Aprano, Mar 1, 2013
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Rick Johnson
    Replies:
    0
    Views:
    90
    Rick Johnson
    Feb 28, 2013
  2. Joel Goldstick
    Replies:
    0
    Views:
    99
    Joel Goldstick
    Feb 28, 2013
  3. Ian Kelly
    Replies:
    0
    Views:
    89
    Ian Kelly
    Feb 28, 2013
  4. Tim Chase
    Replies:
    0
    Views:
    88
    Tim Chase
    Feb 28, 2013
  5. MRAB
    Replies:
    0
    Views:
    85
Loading...

Share This Page