Limiting scope of Python import

后端 未结 2 1836
半阙折子戏
半阙折子戏 2021-01-02 22:21

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.         


        
相关标签:
2条回答
  • 2021-01-02 22:59

    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()
    
    0 讨论(0)
  • 2021-01-02 23:04

    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.

    0 讨论(0)
提交回复
热议问题