我有以下情况:一个模块包含一个类 Foo 以及一些用于组装 Foo 对象的附加便利函数。 Foo 对象包含以在线和离线方式与数据交互的方法。根据用户的不同,他们可能不想使用在线功能,如果他们不尝试在线执行任何操作,我希望避免询问他们的凭据。如果可能的话,我希望将 credential_obj 保留为导入,因为 Python 实例在导入一次后不需要重新加载导入。
# my_utils.py
def perform_query(metadata):
from auth import credential_obj # This import asks for a password
# perform the query and save to file
# my_foo.py
class Foo:
def __init__(self, x):
# Do something with x to find search for local files
# and populate metadata
def bar(self, metadata): # Online functionality
from my_utils import perform_query
perform_query(metadata)
def spam(self): # Offline functionality
pass
def find_foos(xs):
list_of_foos = [Foo(x) for x in xs]
return list_of_foos
# my_script.py
from my_foo import find_foos # this causes "credential_obj" to be imported and asks for the password
foos = find_foos()
for foo in foos:
foo.spam()
我希望通过在类方法中包含 import 语句,导入只会在执行“bar”时运行 - 但情况似乎并非如此。 “my_script”仅使用离线功能,但仍要求提供凭据。无论如何,有办法阻止导入 find_foos 时发生导入吗?
快速修复以避免一次又一次导入
class Foo:
def __init__(self, x):
# Do something with x to find search for local files
# and populate metadata
self.query_call = None
def bar(self, metadata): # Online functionality
if not self.query_call:
from my_utils import perform_query
self.query_call = perform_query
self.query_call(metadata)
def spam(self): # Offline functionality
pass
感谢 Ben Voigt,我很快找到了解决方案:
# my_utils.py
from importlib import import_module
def perform_query(metadata):
auth = import_module('auth')
# perform the query and save to file using auth.credential_obj