What is the function form of star import in Python 3

前端 未结 1 996
有刺的猬
有刺的猬 2020-12-10 01:31

What is the equivalent of import * in Python using functions (presumably from importlib)?

I know that you can import a module with mo

相关标签:
1条回答
  • There's no function for from whatever import *. In fact, there's no function for import whatever, either! When you do

    mod = __import__(...)
    

    the __import__ function is only responsible for part of the job. It provides you with a module object, but you have to assign that module object to a variable separately. There's no function that will import a module and assign it to a variable the way import whatever does.


    In from whatever import *, there are two parts:

    • prepare the module object for whatever
    • assign variables

    The "prepare the module object" part is almost identical to in import whatever, and it can be handled by the same function, __import__. There's a minor difference in that import * will load any not-yet-loaded submodules in a package's __all__ list; __import__ will handle this for you if you provide fromlist=['*']:

    module = __import__('whatever', fromlist=['*'])
    

    The part about assigning names is where the big differences occur, and again, you have to handle that yourself. It's fairly straightforward, as long as you're at global scope:

    if hasattr(module, '__all__'):
        all_names = module.__all__
    else:
        all_names = [name for name in dir(module) if not name.startswith('_')]
    
    globals().update({name: getattr(module, name) for name in all_names})
    

    Function scopes don't support assigning variables determined at runtime.

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