Python中的空模式不足吗? [英] Null pattern in Python underused?
问题描述
每次我都会遇到这样的代码:
Every now and then I come across code like this:
foo = Foo()
...
if foo.bar is not None and foo.bar.baz == 42:
shiny_happy(...)
对于我来说,这似乎是一个愚蠢的事情。
Which seems, well, unpythonic, to me.
在Objective-C中,您可以发送消息到nil,答案。我一直认为这是非常方便的。当然,可以从Google给出的结果判断 Python中的空格式我,似乎这不是很广泛的使用。为什么是这样?
In Objective-C, you can send messages to nil and get nil as the answer. I've always thought that's quite handy. Of course it is possible to implement a Null pattern in Python, however judging from the results Google's given me, it seems this is not very widely used. Why's that?
或者甚至更好 - 这是一个坏主意,让None.whatever返回None而不是提出异常?
Or even better—would it be a bad idea to let None.whatever return None instead of raising an exception?
推荐答案
PEP 336 - Make None Callable 提出了一个类似的功能:
PEP 336 - Make None Callable proposed a similar feature:
没有应该是一个可调用对象,当用任何参数调用
没有副作用并返回无。
None should be a callable object that when called with any arguments has no side effect and returns None.
为什么被拒绝的原因只是被认为是无提出调用时发生错误。
The reason for why it was rejected was simply "It is considered a feature that None raises an error when called."
这篇关于Python中的空模式不足吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!