I have some code that looks like this:
from pyparsing import Word, alphas, Optional, ...
# Do stuff ...
# And at the end, save a result to the outside world.
parser = ...
# Now use parser but don't use anything else from pyparsing again.
I like having the convenience of calling from <package> import <etc>
, but I only want it to be used in a very small segment of code. I am afraid I am contributing to namespace pollution because I have a number of small snippets like this in the same file.
What is the Pythonic way of handling this situation? I am still just kind of playing around with it, so I would rather not write and rewritepyparsing.
so many times.
Imports should always be written at the top of the file, after any module comments and docstrings. Imports should be divided according to what is being imported. There are generally three groups: standard library imports (Python's built-in modules)
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.
You will learn about the four different scopes with the help of examples: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.
Import order does not matter. If a module relies on other modules, it needs to import them itself. Python treats each .
The usual ways to control namespace pollution are
These techniques are all used by the core developers in the standard library. For example, the decimal module:
starts out with private name imports such as import math as _math
etc.
Later it does work to setup a threading environment followed by variable deletion using del sys, MockThreading
.
In addition, it defines an __all__ variable to make clear what the public API is.
Taken together, these techniques keep the namespace as clean as a whistle.
One easy way is to use function scope to control import visibility within a file:
def prepare_parser():
from pyparsing import Word, alphas, Optional, ...
# do stuff, and get the final thing to return
return ...
parser = prepare_parser()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With