Util Python¶
Python specific helper functions
- dffml.util.python.modules(root: Union[str, Path], package_name: str, *, skip: Optional[Callable[[str, Path], bool]] = None) Iterator[Tuple[str, module]] [source]¶
Import all modules (Python files) starting at the directory given by
root
of the packagepackage_name
.- Parameters:
root (str, pathlib.Path) – The path to the directory containing the top level
__init__.py
of the package.package_name (str) – Top level package name of the package your importing. There are no
.
characters in this. For example,dffml
, ordffml_config_yaml
.skip (callable, optional) – Function that will be called with
(import_name, path)
and should return a boolean, True if the module should not be imported and yielded to the caller. If it returns False, the Python file atpath
withinpackage_name
will be imported by passingimport_name
to :py:func`importlib.import_module`.
- Yields:
import_name (str) – The
package_name.subdir.file_stem
used to import the module.module (types.ModuleType) – The imported module.
Examples
You can get all the Python files imported individually in a package as follows.
>>> import dffml >>> import pathlib >>> import importlib >>> >>> package_name = "xml" >>> top_level_module = importlib.import_module(package_name) >>> >>> root = pathlib.Path(top_level_module.__path__[0]) >>> >>> # Skip any files in dom/ subdirectory and __main__.py and __init__.py >>> def skip(_import_name, path) -> bool: ... return (root / "dom") in path.parents or path.name.startswith("__") ... >>> # Print the first module >>> for import_name, module in dffml.modules(root, package_name, skip=skip): ... print(import_name) ... break ... xml.etree.ElementInclude
- dffml.util.python.within_method(obj: object, method_name: str, max_depth: int = - 1) bool [source]¶
Return True if a caller is being called from a given method of a given object.
- Parameters:
- Returns:
within – True if the calling function is being called from within the method given bound to the object given.
- Return type:
boolean
Examples
>>> from dffml import within_method >>> >>> class FirstClass: ... def feedface(self): ... print(within_method(self, "__init__", max_depth=3)) ... >>> first = FirstClass() >>> first .feedface() False >>> >>> class SecondClass(FirstClass): ... def __init__(self): ... self.feedface() ... >>> second = SecondClass() True >>> >>> class ThirdClass(SecondClass): ... def __init__(self): ... self.deadbeef() ... ... def deadbeef(self): ... self.feedface() ... >>> third = ThirdClass() False