API design is an art activity. It often needs to be simple, easy to understand, neat, and not cumbersome.
Many times, we encapsulate a method at the bottom layer for high-level use, and other methods are just to assist this method.
That is to say, we only need to expose this method, and we don't need to care about how this method is implemented, or the existence of other auxiliary methods.
In Python, there are several strategies to keep namespaces clean.
1. Variable names starting with underscore _
Variables starting with underscore _ will not be imported when other modules from xxx import *.
If you look at the source code of decimal, you will find that the imported modules have been changed to aliases starting with underscore _ many times.
http://hg.python.org/cpython/file/2.7/Lib/decimal.pyFor example
import copy as _copy import math as _math import numbers as _numbers
This is not an egg It hurts, in order not to pollute the namespace
2. Define __all__
Python’s magic method is really flexible.
Suppose there are three methods a(), b(), c() in my module
I just want to expose a, not b and c.
At this time __all__=[a]
When other modules from xxxmodule import *, only a is imported.
And when the developer reads the source code, he sees __all__ and immediately knows which methods are to be exposed, instead of a bunch of code with no way to start.
3. After using this variable, delete
and delete it through del xxx.
This reduces the number of variables that fill the screen in dir (xxxmodule).
Similarly in the source code of decimal, you can see that after using the regular expression module re, it was deleted with del re.
Another way is to put the import statement inside the function and limit it to the local scope. I feel that this method is not pythonic, so I don’t recommend it.
For more articles related to the standard definition of namespaces in Python, please pay attention to the PHP Chinese website!