2

I have a function like this:

def func(foo, bar, nin=None, nout=None):
    if not nin:
        nin = bar
    if not nout:
        nout = bar
    return foo * nin / nout

It takes in two optional parameters and I need to map them into another compulsory parameter if they are not passed in. But is this the pythonic way to do it? Are there other ways to get the check and set the nin and nout?

3
  • 2
    Yes, that's the Pythonic way to do it, except that you should check if nin is not None: instead of if not nin: to avoid issues with false-y objects other than None. Commented Aug 2, 2015 at 18:27
  • Looks good, though I would use if nin is None: ... etc. Commented Aug 2, 2015 at 18:27
  • 1
    You could also use **kwargs and use .get, nin, nout = kwargs.get("nin", bar),kwargs.get("nout", foo) Commented Aug 2, 2015 at 18:39

3 Answers 3

3

If you really want to shorten it, you could do e.g.:

nin = bar if nin is None else nin

Note that here I'm testing for None by identity, using is, not truthiness; otherwise, what happens if e.g. nin = 0? This isn't None, but still evaluates false-y (see truth value testing), hence the style guide's suggestion:

Comparisons to singletons like None should always be done with is or is not ... beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

Sign up to request clarification or add additional context in comments.

2 Comments

Different case, you could test with == here as well.. is just feels like the way here (and is probably slightly faster)
@lolopop you could, but, again, the style guide is clear on this!
2

I would do the following:

def func(foo, bar, nin=None, nout=None):
    nin = bar if nin is None else nin
    nout = bar if nout is None else nout
    return foo * nin / nout

Comments

1

None is the way for inputs where you also accept zero and the like.

I think that you should use nin is None rather the nin == None, and many would argue that nin = bar if nin is None else nin is more pythonic, but personally I think both are ok.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.