Python import limit

I have a 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 to be able to call from <package> import <etc>, but I want it to be used only in a very small code segment. I am afraid that I am contributing to the pollution of the namespace because I have some small fragments like this in the same file.

What is the pythonic way to handle this situation? I still just play with it, so I would rather not write and rewrite pyparsing.so many times.

+5
source share
2 answers

One simple way is to use a functional area to control the visibility of imports in a file:

def prepare_parser():
    from pyparsing import Word, alphas, Optional, ...
    # do stuff, and get the final thing to return
    return ...

parser = prepare_parser()
+7
source

  • __all__
  • import-as

. , :

  • , import math as _math ..

  • , , del sys, MockThreading.

  • , __all__, , API.

, , .

+11

All Articles