开发者

Catching a value of None with "or" in an expression

开发者 https://www.devze.com 2023-03-01 12:46 出处:网络
I came开发者_如何学运维 across this in a code review: def some_method(self, path): path = os.path.abspath(os.path.expanduser(path or \"\"))

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()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号