Limiting scope of Python import
Question: 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 rewrite`pyparsing.` so
many times.


Answer: The usual ways to control namespace pollution are

  1. Delete the variables after use 
  2. Use the __all__ variable
  3. Use import-as to underscored variable names

These techniques are all used by the core developers in the standard library.
For example, the _decimal_ module:

  * starts out with [private name imports](http://hg.python.org/cpython/file/2.7/Lib/decimal.py#l139) such as `import math as _math` etc. 

  * Later it does work to setup a threading environment followed by [variable deletion](http://hg.python.org/cpython/file/2.7/Lib/decimal.py#l402) using `del sys, MockThreading`.

  * In addition, it [defines an __all__ variable](http://hg.python.org/cpython/file/2.7/Lib/decimal.py#l118) to make clear what the public API is. 

Taken together, these techniques keep the namespace as clean as a whistle.

