342

In C#, I can say x ?? "", which will give me x if x is not null, and the empty string if x is null. I've found it useful for working with databases.

Is there a way to return a default value if Python finds None in a variable?

nfw
  • 3,853
  • 2
  • 19
  • 16
  • I'm used to Ruby's `||=` operator which is great for caching variables. In my case the variable was not defined so `a or b` did not work for me. I found the following works though if you need variable caching which comes in handy with Jupyter Notebooks: `a = a if 'a' in locals() else do_work()`. This is great if you want to create a backup variable and make sure you don't overwrite it as you're running different cells if you accidentally run the same cell again. – CTS_AE May 11 '20 at 08:14

4 Answers4

544

You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).

Tenzin Chemi
  • 5,101
  • 2
  • 27
  • 33
starhusker
  • 6,658
  • 3
  • 19
  • 12
  • 71
    This will return "default" if x is any falsy value, e.g. `None`, `[]`, `""`, etc. but is often good enough and cleaner looking. – FogleBird Dec 04 '12 at 19:45
  • I get `NameError: name 'x' is not defined` – Stephen Jan 30 '14 at 03:31
  • 29
    Would return "default" if x is 0 (zero) as well – thameera Feb 08 '14 at 17:28
  • 34
    I consider this to be a bad practice - this uses some conversion to bool of 'x' and this will fail if no such conversion found (for instance, pandas DataFrames and numpy arrays) – Alleo Apr 07 '14 at 16:47
  • 70
    ``x or default`` is an **antipattern**! It is a frequent source of errors that are hard to debug, because for many subtle reasons x could evaluate to false even if it is the desired value. – Quant Metropolis Jun 23 '16 at 11:31
  • 5
    I agree with QuantMetropolis and Alleo. Very bad practice. If there's a need for a default value, then it's because you know that x can appear with some irregular value (or type) which you want to replace. So your code should detect that specific circumstance. Not only does this avoid surprise side effects (like providing the default when x has legitimate value zero), but it also documents for maintenance programmers (possibly your later self) what you intended to happen here. – gwideman Jul 11 '16 at 10:57
  • 100
    **WARNING: AntiPattern** : use `return "default" if x is None else x` – brent.payne Aug 29 '16 at 20:40
  • 1
    ^ I was receiving a lot of up votes on my unselected answer below, so assumed people were discovering this anti-pattern the hard way. Hopefully the above comment will grab people's attention and save some heartache. – brent.payne Aug 29 '16 at 20:42
  • Because of duck-typing, many use-cases actually require a comparison to any false-y value; which polymorphic functions are treating/returning as a None == NULL == '' == 0 value. Stop trying to shoehorn Javascript or .NET principles onto python. Take the default value, and use EAFP later on. – cowbert Sep 25 '17 at 17:01
  • 3
    So `time.now() == False` once a day. That's just great. – Tom Russell Nov 09 '17 at 10:19
  • 7
    It's perfectly valid and not an antipattern. Just as with everything else, you need to know what it does: it doesn't just ignore None, but all "falsy" values, including 0, "", [] and {} (and some more special cases, like instances which override their evaluation). If that's what you want (and in lots of cases it is), it's perfect. – Hejazzman Oct 10 '18 at 12:56
  • 1
    @Hejazzman "It is a frequent source of errors that are hard to debug, because for many subtle reasons x could evaluate to false even if it is the desired value." – MrR Mar 27 '19 at 12:57
  • 1
    @Hejazzman It may be frequently what people want, but the question explicitly asked for a null test, not a falsy test. 0 may be a desirable value in a lot of cases also, can't assume that the asker doesn't care about other falsy values being ignored, and MrR is correct, things like this get hard to debug, particularly if they come up rarely. I had something in a production server for months before someone hit the edge case that broke everything. – Andrew Jan 18 '21 at 19:10
  • Also, this would fail to return a valid value, if you're returning a function call and it raises an exception. – Kusal Hettiarachchi Feb 06 '21 at 12:49
  • 1
    This will return a default value for many cases other than just `None`, it's not even close to being a correct answer, yet is so upvoted. – Mark K Cowan Feb 17 '22 at 18:30
  • @Hejazzman its working just fine for me too. I used it to test if a cell in a spreadsheet was empty. I'm only expecting a string so im happy to get the default if whatever is in the cell evaluated to False. Definitely valid for some specific cases of course you run into issues if you use anything carelessly – West Aug 04 '22 at 03:04
233
return "default" if x is None else x

try the above.

brent.payne
  • 5,189
  • 3
  • 22
  • 17
  • 1
    Use this when you only want the default value when x is None and not other false values. Which matches the C# x??"default" – brent.payne Apr 30 '13 at 17:00
  • 5
    Otherwise, just drop the `is None`, and let `x` evaluate as a Boolean value on its own. – chepner Apr 30 '13 at 17:07
  • Or use @starhusker's x or "default". Often I used to use the ternary sytax b/c I what to do x.value if X might be None. So x.value if x else "default", but this is more readable getattr(obj, "value", "default"). The trade off is that the later is not caught by many auto-refactor tools. – brent.payne Apr 30 '13 at 23:49
  • 2
    Its Pythonic #PEP20 The Zen of Python Explicit is better than implicit. Better to handle only for None Cases if thats what it takes. – Doogle Jan 19 '18 at 04:53
  • 3
    This is also how it is implemented in the convenience function `ifnone` from the `fastai` library. So if you are using that library, then that is your shorthand. – MartijnVanAttekum Sep 22 '19 at 14:20
  • 3
    meh... it's ok, but not as good as c#, because you need to create a variable for x. In c# for instance x can be a function call, such as `return foo() ?? "default"`. But in python you'll need `x = foo(); return x if x is not None else "default"`. Not as pretty. – John Henckel Jan 11 '22 at 17:39
67

You can use a conditional expression:

x if x is not None else some_value

Example:

In [22]: x = None

In [23]: print x if x is not None else "foo"
foo

In [24]: x = "bar"

In [25]: print x if x is not None else "foo"
bar
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

You've got the ternary syntax x if x else '' - is that what you're after?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280