我喜欢@maxschlepzig 的回答。
该方法存在一个错误,即如果您直接导入一个函数,它将不起作用。例如,
global_imports("tqdm", "tqdm, True)
不起作用,因为未导入该模块。还有这个
global_imports("tqdm")
global_imports("tqdm", "tqdm, True)
作品。
我稍微改变了@maxschlepzig 的答案。使用 fromlist 以便您可以使用“From”语句以统一的方式加载函数或模块。
def global_imports(object_name: str,
short_name: str = None,
context_module_name: str = None):
"""import from local function as global import
Use this statement to import inside a function,
but effective as import at the top of the module.
Args:
object_name: the object name want to import,
could be module or function
short_name: the short name for the import
context_module_name: the context module name in the import
example usage:
import os -> global_imports("os")
import numpy as np -> global_imports("numpy", "np")
from collections import Counter ->
global_imports("Counter", None, "collections")
from google.cloud import storage ->
global_imports("storage", None, "google.cloud")
"""
if not short_name:
short_name = object_name
if not context_module_name:
globals()[short_name] = __import__(object_name)
else:
context_module = __import__(context_module_name,
fromlist=[object_name])
globals()[short_name] = getattr(context_module, object_name)