Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there shorthand for returning a default value if None in Python? [duplicate]

Tags:

python

People also ask

What does [: None mean in Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.

How do you return a default value in Python?

Implicit return Statements So, if you don't explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you. That default return value will always be None .

How do you return a null value in Python?

If you want to return a null function in Python then use the None keyword in the returns statement. Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing').


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


return "default" if x is None else x

try the above.


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

x or "default"

works best — i can even use a function call inline, without executing it twice or using extra variable:

self.lineEdit_path.setText( self.getDir(basepath) or basepath )

I use it when opening Qt's dialog.getExistingDirectory() and canceling, which returns empty string.