给定一个Python类的字符串,例如my_package.my_module。MyClass,最好的加载方式是什么?
换句话说,我正在寻找一个等效的Class.forName()在Java,函数在Python。它需要工作在谷歌应用程序引擎。
最好是这样一个函数,它接受类的FQN作为字符串,并返回类的引用:
my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
给定一个Python类的字符串,例如my_package.my_module。MyClass,最好的加载方式是什么?
换句话说,我正在寻找一个等效的Class.forName()在Java,函数在Python。它需要工作在谷歌应用程序引擎。
最好是这样一个函数,它接受类的FQN作为字符串,并返回类的引用:
my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
当前回答
def import_class(cl):
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
其他回答
PyPI模块自动加载和导入
# PyPI imports
import pkg_resources, subprocess, sys
modules = {'lxml.etree', 'pandas', 'screeninfo'}
required = {m.split('.')[0] for m in modules}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip'])
subprocess.check_call([sys.executable, '-m', 'pip', 'install', *missing])
for module in set.union(required, modules):
globals()[module] = __import__(module)
测试:
print(pandas.__version__)
print(lxml.etree.LXML_VERSION)
如果你不想滚动你自己的,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)."""
在谷歌应用引擎中有一个名为import_string的webapp2函数。更多信息请参见:https://webapp-improved.appspot.com/api/webapp2.html
So,
import webapp2
my_class = webapp2.import_string('my_package.my_module.MyClass')
例如,这在webapp2中使用。可以使用处理程序或字符串的路由。
def import_class(cl):
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
好的,对我来说,这就是它工作的方式(我使用Python 2.7):
a = __import__('file_to_import', globals(), locals(), ['*'], -1)
b = a.MyClass()
b是MyClass类的一个实例