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.
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?
Or even better—would it be a bad idea to let None.whatever return None instead of raising an exception?
Couldn't you do a try except? The Pythonic way says It is Easier to Ask for Forgiveness than Permission.
So:
Or do it without possibly silencing more exceptions than desired:
PEP 336 - Make None Callable proposed a similar feature:
The reason for why it was rejected was simply "It is considered a feature that None raises an error when called."
I don't think it's a good idea. Here's why. suppose you have
Suppose
getValue()
returns a number, orNone
if not found. Now supposefoo
was none by accident or a bug. As a result, it would returnNone
, and continue, even if there's a bug.In other words, you are no longer able to distinguish if there's no value (returns
None
) or if there's an error (foo
wasNone
to begin with). You are altering the return contract of a routine with a fact that is not under control of the routine itself, eventually overwriting its semantics.Here's why I don't think that's a good idea:
How would you handle this case?
As others have said, PEP 336 describes why this is the behavior.
Adding something like Groovy's "safe navigation operator" (
?.
) could perhaps make things more elegant in some cases: