flâneur — a map of the web's best reading

The Global Object Pattern

python-patterns.guide · 3,552 words · saved by 1 readers

Like several other scripting languages, Python parses the outer level of each module as normal code. Un-indented assignment statements, expressions, and even loops and conditionals will execute as the module is imported. This presents an excellent opportunity to supplement a module’s classes and functions with constants and data structures that callers will find useful — but also offers dangerous temptations: mutable global objects can wind up coupling distant code, and I/O operations impose import-time expense and side effects. Every Python module is a separate namespace. A module like json can offer a loads() function without conflicting with, replacing, or overwriting the completely different loads() function defined over in the pickle module. Separate namespaces are crucial to making a programming language tractable. If Python modules were not separate namespaces, you would be unable to read or write Python code by keeping your attention focused on the module in front of you — a li

The Global Object Pattern ¶ Verdict Like several other scripting languages, Python parses the outer level of each module as normal code. Un-indented assignment statements, expressions, and even loops and conditionals will execute as the module is imported. This presents an excellent opportunity to supplement a module’s classes and functions with constants and data structures that callers will find useful — but also offers dangerous temptations: mutable global objects can wind up coupling distant code, and I/O operations impose import-time expense and side effects. Every Python module is a sepa

Explore this link on the map →

related reading