Jeśli nie chcesz tworzyć własnych, w pydocmodule dostępna jest funkcja , która robi dokładnie to:
from pydoc import locate
my_class = locate('my_package.my_module.MyClass')
Zaletą tego podejścia w porównaniu z innymi wymienionymi tutaj jest to, że locateznajdzie dowolny obiekt Pythona w podanej kropkowanej ścieżce, a nie tylko obiekt bezpośrednio w module. np my_package.my_module.MyClass.attr.
Jeśli jesteś ciekawy, jaki jest ich przepis, oto funkcja:
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
Opiera się na pydoc.safeimportfunkcji. Oto dokumenty dotyczące tego:
"""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)."""