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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With