Home > Backend Development > Python Tutorial > Standard definition of namespace in Python

Standard definition of namespace in Python

高洛峰
Release: 2017-03-03 15:15:45
Original
1198 people have browsed it

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template