独自のロールを作成したくない場合は、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)."""