Python: Import by string with pkgutil.resolve_name() - Adam Johnson (original) (raw)
2024-06-17
Django and other frameworks often allow you to configure classes, functions, or modules to import using strings. To do the same in your own code, use pkgutil.resolve_name() from the standard library (added in Python 3.9):
In [1]: import pkgutil
In [2]: Path = pkgutil.resolve_name("pathlib:Path")
In [3]: Path('/') Out[3]: PosixPath('/')
The recommended syntax is <package>:<object>
, where <package>
defines the path to the module to import, and <object>
defines the path within that module to look up. Dots are allowed in both, supporting things like:
In [12]: pkgutil.resolve_name("collections:deque") Out[12]: collections.deque
In [8]: pkgutil.resolve_name("pathlib:Path.home") Out[8]: <bound method Path.home of <class 'pathlib.Path'>>
In [11]: pkgutil.resolve_name("http.cookies") Out[11]: <module 'http.cookies' from '/.../http/cookies.py'>
Modules only with importlib.import_module()
If you only need to import modules by string reference, use importlib.import_module():
In [1]: import importlib
In [2]: importlib.import_module("pathlib") Out[2]: <module 'pathlib' from '/.../pathlib.py'>
Read my book Boost Your Django DX, freshly updated in November 2024.
One summary email a week, no spam, I pinky promise.
Related posts:
- Python: Mock an inner import
- Python: Show all subclasses of a class
- Python: Make line number paths with inspect
Tags: python