ballet.util.mod module¶
-
ballet.util.mod.
import_module_at_path
(modname, modpath)[source]¶ Import module from path that may not be on system path
- Parameters
modname (
str
) – module name from package root, e.g. foo.barmodpath (
Union
[str
,PathLike
]) – absolute path to module itself, e.g. /home/user/foo/bar.py. In the case of a module that is a package, then the path should be specified as ‘/home/user/foo’ and a file ‘/home/user/foo/__init__.py’ must be present or the import will fail.
Examples
>>> modname = 'foo.bar.baz' >>> modpath = '/home/user/foo/bar/baz.py' >>> import_module_at_path(modname, modpath) <module 'foo.bar.baz' from '/home/user/foo/bar/baz.py'>
>>> modname = 'foo.bar' >>> modpath = '/home/user/foo/bar' >>> import_module_at_path(modname, modpath) <module 'foo.bar' from '/home/user/foo/bar/__init__.py'>
- Return type
module
-
ballet.util.mod.
import_module_from_relpath
(path)[source]¶ Import module at relative path to project root
- Return type
module
-
ballet.util.mod.
modname_to_relpath
(modname, project_root=None, add_init=True)[source]¶ Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in which case the relevant file is the __init__.py within the subdirectory.
Example
>>> modname_to_relpath('foo.features') 'foo/features.py' >>> modname_to_relpath('foo.features', project_root='/path/to/project') 'foo/features/__init__.py'
- Parameters
modname (
str
) – Module name, e.g. os.pathproject_root (
Union
[str
,PathLike
,None
]) – Path to project rootadd_init (
bool
) – Whether to add __init__.py to the path of modules that are packages. Defaults to True
- Return type
str
-
ballet.util.mod.
relpath_to_modname
(relpath)[source]¶ Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a module name. Relative paths of the form ‘foo/bar’ are not converted to module names ‘foo.bar’, because (1) they identify directories, not regular files, and (2) already ‘foo/bar/__init__.py’ would claim that conversion.
- Parameters
relpath (
Union
[str
,PathLike
]) – Relative path from some location on sys.path
Example
>>> relpath_to_modname('ballet/util/_util.py') 'ballet.util._util'
- Return type
str