Null pattern in Python underused? Null pattern in Python underused? python python

Null pattern in Python underused?


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."


I'm sorry, but that code is pythonic. I think most would agree that "explicit is better than implicit" in Python. Python is a language that is easy to read compared to most, and people should not defeat that by writing cryptic code. Make the meaning very clear.

foo = Foo()...if foo.bar is not None and foo.bar.baz == 42:    shiny_happy(...)

In this code sample, it is clear that foo.bar is sometimes None on this code path, and that we only run shiny_happy() if it is not None, and .baz == 42. Very clear to anyone what is going on here and why. The same can not be said for the null pattern, or the try ... except code in one of the answers posted here. It's one thing if your language, like Objective-C or javascript enforces a null pattern, but in a language where it is not used at all, it will just create confusion and code that is difficult to read. When programming in python, do as the pythonistas do.


Couldn't you do a try except? The Pythonic way says It is Easier to Ask for Forgiveness than Permission.

So:

try:    if foo.bar.baz == 42:        shiny_happy(...)except AttributeError:    pass #or whatever

Or do it without possibly silencing more exceptions than desired:

try:    baz = foo.bar.bazexcept AttributeError:    pass # handle error as desiredelse:    if baz == 42:        shiny_happy(...)