【发布时间】:2020-12-12 18:58:08
【问题描述】:
Python 代码:
class Importer:
from importlib import __import__, reload
from sys import modules
libname = ""
import_count = 0
module = None
def __init__(self, name):
self.libname = name
self.import_count = 0
def importm(self):
if self.libname not in self.modules:
self.module = __import__(self.libname)
else:
print("must reload")
self.module = self.reload(self.module)
self.import_count += 1
# test out Importer
importer = Importer("module")
importer.importm() # prints Hello
importer.importm() # prints Hello
importer.importm() # prints Hello (again)
print(importer.import_count)
上面的Python(3.8.1)代码在OnlineGDB,如果运行会报错:
TypeError: reload() takes 1 positional argument but 2 were given
当我在 Python 中打开 importlib 库时,我看到了这个:
# ... (previous code; unnecessary)
_RELOADING = {}
def reload(module): ## this is where reload is defined (one argument)
"""Reload the module and return it.
The module must have been successfully imported before.
"""
if not module or not isinstance(module, types.ModuleType): ## check for type of module
raise TypeError("reload() argument must be a module")
try:
name = module.__spec__.name
except AttributeError:
name = module.__name__
if sys.modules.get(name) is not module: ## other code you (probably) don't have to care about
msg = "module {} not in sys.modules"
raise ImportError(msg.format(name), name=name)
if name in _RELOADING:
return _RELOADING[name]
_RELOADING[name] = module
try:
parent_name = name.rpartition('.')[0]
if parent_name:
try:
parent = sys.modules[parent_name]
except KeyError:
msg = "parent {!r} not in sys.modules"
raise ImportError(msg.format(parent_name),
name=parent_name) from None
else:
pkgpath = parent.__path__
else:
pkgpath = None
target = module
spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
if spec is None:
raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
_bootstrap._exec(spec, module)
# The module may have replaced itself in sys.modules!
return sys.modules[name]
finally:
try:
del _RELOADING[name]
except KeyError:
pass
# ... (After code; unnecessary)
所有双井号 (##) cmets 都是我的
很明显reload 有 1 个参数,它会检查该参数是否是一个模块。在the OGDB (OnineGDB) code 中,我只传递了一个参数(很确定),它是模块类型(很可能)。如果我删除该参数(您可以编辑 OGDB),它会给出:
TypeError: reload() argument must be module
因此,出于某种原因,Python 一直认为我的论点比实际的要多。我让它工作的唯一方法是编辑importlib 文件,让reload 有两个参数(不是一个好主意)。
我尝试运行 PDB,但没有帮助。
谁能发现任何明显错误的地方,比如实际上有两个参数?
【问题讨论】:
-
请在问题中包含minimal reproducible example。
-
当您像
self.reload一样调用它时,它会隐式添加self作为第一个参数。 -
将
self.reload替换为reload。它首先起作用的原因是因为您在“类范围”内导入,我认为这是不好的做法。 -
是的,我看到了。但是您应该在问题中添加代码。问题应该是独立的。
-
@LakshyaRaj 在课堂外进行导入。
标签: python python-3.x illegalargumentexception