Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting scope of Python import

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.

like image 661
math4tots Avatar asked Apr 28 '12 04:04

math4tots


People also ask

Should all imports be at the top Python?

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)

Why is the use of import all statements not recommended in Python?

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.

What are the scopes in Python?

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.

Does Python import order matter?

Import order does not matter. If a module relies on other modules, it needs to import them itself. Python treats each .


2 Answers

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 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.

like image 101
Raymond Hettinger Avatar answered Nov 02 '22 08:11

Raymond Hettinger


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()
like image 40
Amber Avatar answered Nov 02 '22 09:11

Amber