Namespaces are the shamash candle of the Zen of Python

This is part of a special series about the Zen of Python focusing on one bonus principle: namespaces.
77 readers like this.
Why and how to handle exceptions in Python Flask

Image from Unsplash.com, Creative Commons Zero 

Hanukkah famously has eight nights of celebration. The Hanukkah menorah, however, has nine candles: eight regular candles and a ninth that is always offset. It is called the shamash or shamos, which loosely translates to meaning "servant" or "janitor."

The shamos is the candle that lights all the others: it is the only candle whose fire can be used, not just watched. As we wrap up our series on the Zen of Python, I see how namespaces provide a similar service.

Namespaces in Python

Python uses namespaces for everything. Though simple, they are sparse data structures—which is often the best way to achieve a goal.

namespace is a mapping from names to objects.

— Python.org

Modules are namespaces. This means that correctly predicting module semantics often just requires familiarity with how Python namespaces work. Classes are namespaces. Objects are namespaces. Functions have access to their local namespace, their parent namespace, and the global namespace.

The simple model, where the . operator accesses an object, which in turn will usually, but not always, do some sort of dictionary lookup, makes Python hard to optimize, but easy to explain.

Indeed, some third-party modules take this guideline and run with it. For example, the variants package turns functions into namespaces of "related functionality." It is a good example of how the Zen of Python can inspire new abstractions.

In conclusion

Thank you for joining me on this Hanukkah-inspired exploration of my favorite language. Go forth and meditate on the Zen until you reach enlightenment.

What to read next
Tags
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
Moshe has been involved in the Linux community since 1998, helping in Linux "installation parties". He has been programming Python since 1999, and has contributed to the core Python interpreter. Moshe has been a DevOps/SRE since before those terms existed, caring deeply about software reliability, build reproducibility and other such things.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.