如果您不想自己动手,pydoc
模块中有一个功能可以做到这一点:
from pydoc import locate
my_class = locate('my_package.my_module.MyClass')
与此处列出的其他方法相比,这种方法的优点是可以在提供的虚线路径上locate
找到任何python 对象,而不仅仅是模块中的直接对象。例如my_package.my_module.MyClass.attr
。
如果你好奇他们的食谱是什么,这里的功能是:
def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
else:
object = __builtin__
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
它依赖于pydoc.safeimport
功能。以下是相关文档:
"""Import a module; handle errors; return None if the module isn't found.
If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised. Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning. If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""