Skip to content

python_module_tools

Tools for working with python modules and classes.

classes_from_module(superclass, module)

Return plug-ins from module

Parameters:

Name Type Description Default
superclass type

Superclass of subclasses to look for

required
module ModuleType

Imported module where to look for 'superclass' subclasses.

required

Returns:

Type Description
list[type]

list[type]: List of plug-ins, or empty list if none is found.

Source code in client/ayon_core/lib/python_module_tools.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def classes_from_module(
    superclass: type, module: types.ModuleType
) -> list[type]:
    """Return plug-ins from module

    Arguments:
        superclass (type): Superclass of subclasses to look for
        module (types.ModuleType): Imported module where to look for
            'superclass' subclasses.

    Returns:
        list[type]: List of plug-ins, or empty list if none is found.

    """
    classes = list()
    for name in dir(module):
        # It could be anything at this point
        obj = getattr(module, name)
        if not inspect.isclass(obj) or obj is superclass:
            continue

        if issubclass(obj, superclass):
            classes.append(obj)

    return classes

get_dynamic_import_module_name(dirpath, filename=None)

Get hash of directory path.

Parameters:

Name Type Description Default
dirpath Path | str

Directory path to hash.

required

Returns:

Name Type Description
str str

Hash of directory path.

Source code in client/ayon_core/lib/python_module_tools.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def get_dynamic_import_module_name(
    dirpath: Path | str,
    filename: str | None = None,
) -> str:
    """Get hash of directory path.

    Args:
        dirpath (Path | str): Directory path to hash.

    Returns:
        str: Hash of directory path.

    """
    if isinstance(dirpath, str):
        dirpath = Path(dirpath)
    unified_path = dirpath.absolute().as_posix()
    if IS_WINDOWS:
        unified_path = unified_path.lower()
    dirhash = hashlib.md5(unified_path.encode("utf-8")).hexdigest()
    if not filename:
        return dirhash
    return f"{dirhash}.{os.path.splitext(filename)[0]}"

import_filepath(filepath, module_name=None, sys_module_name=None)

Import python file as python module.

It is recommended to pass in only 'filepath' and let function generate module names automatically.

Parameters:

Name Type Description Default
filepath str | Path

Path to python file.

required
module_name str

Name of loaded module. Only for Python 3. By default is filled with filename of filepath.

None
sys_module_name str

Name of module in sys.modules where to store loaded module. By default is used directory hash and module name.

None
Source code in client/ayon_core/lib/python_module_tools.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def import_filepath(
    filepath: str | Path,
    module_name: str | None = None,
    sys_module_name: str | None = None,
) -> types.ModuleType:
    """Import python file as python module.

    It is recommended to pass in only 'filepath' and let function generate
        module names automatically.

    Args:
        filepath (str | Path): Path to python file.
        module_name (str): Name of loaded module. Only for Python 3.
            By default is filled with filename of filepath.
        sys_module_name (str): Name of module in `sys.modules` where to store
            loaded module. By default is used directory hash and module name.

    """
    if isinstance(filepath, str):
        filepath = Path(filepath).resolve()

    if module_name is None:
        module_name = filepath.stem

    if not sys_module_name:
        dirpath_hash = get_dynamic_import_module_name(filepath.parent)
        sys_module_name = f"{dirpath_hash}.{module_name}"

    # Prepare module object where content of file will be parsed
    module = types.ModuleType(sys_module_name)
    module.__file__ = filepath.as_posix()

    sys.modules[sys_module_name] = module

    # Use loader so module has full specs
    module_loader = importlib.machinery.SourceFileLoader(
        sys_module_name, filepath.as_posix()
    )

    module_loader.exec_module(module)
    return module

import_module_from_dirpath(dirpath, folder_name, dst_module_name=None)

Import passed directory as a python module.

Imported module can be assigned as a child attribute of already loaded module from sys.modules if has support of setattr. That is not default behavior of python modules so parent module must be a custom module with that ability.

It is not possible to reimport already cached module. If you need to reimport module you have to remove it from caches manually.

Parameters:

Name Type Description Default
dirpath str

Parent directory path of loaded folder.

required
folder_name str

Folder name which should be imported inside passed directory.

required
dst_module_name str

Parent module name under which can be loaded module added.

None
Source code in client/ayon_core/lib/python_module_tools.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def import_module_from_dirpath(
    dirpath: str,
    folder_name: str,
    dst_module_name: str | None = None,
) -> types.ModuleType:
    """Import passed directory as a python module.

    Imported module can be assigned as a child attribute of already loaded
    module from `sys.modules` if has support of `setattr`. That is not default
    behavior of python modules so parent module must be a custom module with
    that ability.

    It is not possible to reimport already cached module. If you need to
    reimport module you have to remove it from caches manually.

    Args:
        dirpath (str): Parent directory path of loaded folder.
        folder_name (str): Folder name which should be imported inside passed
            directory.
        dst_module_name (str): Parent module name under which can be loaded
            module added.

    """
    # Import passed dirpath as python module
    if dst_module_name:
        full_module_name = f"{dst_module_name}.{folder_name}"
        dst_module = sys.modules[dst_module_name]
    else:
        full_module_name = folder_name
        dst_module = None

    # Skip import if is already imported
    if full_module_name in sys.modules:
        return sys.modules[full_module_name]

    import importlib.util
    from importlib._bootstrap_external import PathFinder

    # Find loader for passed path and name
    loader = PathFinder.find_module(full_module_name, [dirpath])

    # Load specs of module
    spec = importlib.util.spec_from_loader(
        full_module_name, loader, origin=dirpath
    )

    # Create module based on specs
    module = importlib.util.module_from_spec(spec)

    # Store module to destination module and `sys.modules`
    # WARNING this mus be done before module execution
    if dst_module is not None:
        setattr(dst_module, folder_name, module)

    sys.modules[full_module_name] = module

    # Execute module import
    loader.exec_module(module)

    return module

is_func_signature_supported(func, *args, **kwargs)

Check if a function signature supports passed args and kwargs.

This check does not actually call the function, just look if function can be called with the arguments.

Notes

This does NOT check if the function would work with passed arguments only if they can be passed in. If function have *args, **kwargs in parameters, this will always return 'True'.

Example

def my_function(my_number): ... return my_number + 1 ... is_func_signature_supported(my_function, 1) True is_func_signature_supported(my_function, 1, 2) False is_func_signature_supported(my_function, my_number=1) True is_func_signature_supported(my_function, number=1) False is_func_signature_supported(my_function, "string") True def my_other_function(*args, **kwargs): ... my_function(*args, **kwargs) ... is_func_signature_supported( ... my_other_function, ... "string", ... 1, ... other=None ... ) True

Parameters:

Name Type Description Default
func Callable

A function where the signature should be tested.

required
*args Any

Positional arguments for function signature.

()
**kwargs Any

Keyword arguments for function signature.

{}

Returns:

Name Type Description
bool

Function can pass in arguments.

Source code in client/ayon_core/lib/python_module_tools.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def is_func_signature_supported(func, *args, **kwargs):
    """Check if a function signature supports passed args and kwargs.

    This check does not actually call the function, just look if function can
    be called with the arguments.

    Notes:
        This does NOT check if the function would work with passed arguments
            only if they can be passed in. If function have *args, **kwargs
            in parameters, this will always return 'True'.

    Example:
        >>> def my_function(my_number):
        ...     return my_number + 1
        ...
        >>> is_func_signature_supported(my_function, 1)
        True
        >>> is_func_signature_supported(my_function, 1, 2)
        False
        >>> is_func_signature_supported(my_function, my_number=1)
        True
        >>> is_func_signature_supported(my_function, number=1)
        False
        >>> is_func_signature_supported(my_function, "string")
        True
        >>> def my_other_function(*args, **kwargs):
        ...     my_function(*args, **kwargs)
        ...
        >>> is_func_signature_supported(
        ...     my_other_function,
        ...     "string",
        ...     1,
        ...     other=None
        ... )
        True

    Args:
        func (Callable): A function where the signature should be tested.
        *args (Any): Positional arguments for function signature.
        **kwargs (Any): Keyword arguments for function signature.

    Returns:
        bool: Function can pass in arguments.

    """
    sig = inspect.signature(func)
    try:
        sig.bind(*args, **kwargs)
        return True
    except TypeError:
        pass
    return False

modules_from_path(path)

Get python scripts as modules from a path.

Parameters:

Name Type Description Default
path str | Path

Path to folder containing python scripts or path to a python script.

required

Returns:

Name Type Description
ModulesResult ModulesResult

Contains successfully imported modules and information about paths that failed to import.

Source code in client/ayon_core/lib/python_module_tools.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def modules_from_path(path: str | Path) -> ModulesResult:
    """Get python scripts as modules from a path.

    Arguments:
        path (str | Path): Path to folder containing python scripts or path
            to a python script.

    Returns:
        ModulesResult: Contains successfully imported modules and
            information about paths that failed to import.

    """
    result = ModulesResult()

    # Just skip and return empty result if path is not set
    if isinstance(path, str):
        path = Path(path)

    # Do not allow relative imports
    if not path.is_absolute():
        log.warning(
            f"Relative paths are not allowed for security reasons '{path}'."
        )
        return result

    path = path.resolve()

    filepaths = []
    if path.is_file():
        filepaths.append(path)

    elif path.is_dir():
        for file in path.iterdir():
            if not file.is_file():
                continue

            # Ignore files which start with underscore
            if file.name.startswith("_"):
                continue

            filepaths.append(file)

    for filepath in filepaths:
        _, mod_ext = os.path.splitext(filepath.name)
        if mod_ext.lower() != ".py":
            continue

        try:
            module = import_filepath(filepath)
            result.add_module(filepath.as_posix(), module)

        except Exception:
            result.add_crashed_module(filepath.as_posix(), sys.exc_info())
            log.warning(
                f"Failed to load path: \"{filepath}\"",
                exc_info=True
            )
            continue

    return result

recursive_bases_from_class(klass)

Extract all bases from entered class.

Source code in client/ayon_core/lib/python_module_tools.py
255
256
257
258
259
260
261
262
def recursive_bases_from_class(klass: type) -> list[type]:
    """Extract all bases from entered class."""
    result = []
    bases = klass.__bases__
    result.extend(bases)
    for base in bases:
        result.extend(recursive_bases_from_class(base))
    return result