Catching a value of None with "or" in an expression
I came开发者_如何学运维 across this in a code review:
def some_method(self, path):
path = os.path.abspath(os.path.expanduser(path or ""))
My first reaction was "ahhhh bad!" but on second thought... is it?
This is a common pattern for implementing some kind of a default value or fallback value if the first part of the expression evaluates to False. Consider it as best-practice - like it or not. It can also be used to turning None into an empty string.
It's a bit pointless in this example though, because calling it like this:
instance.some_method()
Will yield an error.
You would have to call it like this:
instance.some_method(None)
It would be better with:
def some_method(self, path=None):
path = os.path.abspath(os.path.expanduser(path or ""))
Or arguably:
def some_method(self, path=""):
path = os.path.abspath(os.path.expanduser(path))
...which wouldn't guard against a None value. One can debate whether it's better to whine or "default" in that case.
Anyhow the path can be altogether omitted now:
instance.some_method()
精彩评论