Default if none

A

Astley Le Jasper

I realise I could roll my own here, but I wondered if there was an
inbuilt version of this?
def default_if_none(*args):
for arg in args:
if arg:
return arg
return None

x = None
y = 5
z = 6

print default_if_none(x,y,z)
 
C

Chris Rebert

I realise I could roll my own here, but I wondered if there was an
inbuilt version of this?

def default_if_none(*args):
   for arg in args:
       if arg:
           return arg
   return None

x = None
y = 5
z = 6

print default_if_none(x,y,z)

If none of the potential values are considered boolean false:

print x or y or z

Cheers,
Chris
 
S

Steven D'Aprano

... oh ... that simple. Now I feel dumb.

It's really difficult to tell what you're talking about, but I assume
that you're talking about Chris' solution:

x or y or z

Be careful, as Chris' solution is rather risky (read his disclaimer
again). And the code you give does NOT solve the question you ask. Have
you tested it with something like this?
True

Your code destroys perfectly legitimate values and replaces them with
None. That's almost certainly not what you actually want. Chris' solution
isn't much better, but he warned you about it. Read his post carefully.
True


What are you trying to accomplish? Return the first arg that is not None,
otherwise return None? You need to code your test more carefully, by
testing for None and nothing but None:

def default_if_none(*args):
for arg in args:
if arg is not None:
return arg

You don't need the "return None" at the end, because all Python functions
do that automatically.

Here is a one-liner to do it:

(filter(lambda x: x is not None, args) or [None])[0]

but frankly the one-liner is ugly and I wouldn't use it. Just use the
function.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top