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 superclass

Superclass of subclasses to look for

required
module ModuleType

Imported module where to look for 'superclass' subclasses.

required

Returns:

Type Description

List of plug-ins, or empty list if none is found.

Source code in client/ayon_core/lib/python_module_tools.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def classes_from_module(superclass, module):
    """Return plug-ins from module

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

    Returns:
        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

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

Import python file as python module.

Parameters:

Name Type Description Default
filepath str

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 None so module is not added to sys.modules.

None

Todo (antirotor): We should add the module to the sys.modules always but we need to be careful about it and test it properly.

Source code in client/ayon_core/lib/python_module_tools.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def import_filepath(
        filepath: str,
        module_name: Optional[str] = None,
        sys_module_name: Optional[str] = None) -> types.ModuleType:
    """Import python file as python module.

    Args:
        filepath (str): 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 None so module is not added to
            `sys.modules`.

    Todo (antirotor): We should add the module to the sys.modules always but
        we need to be careful about it and test it properly.

    """
    if module_name is None:
        module_name = os.path.splitext(os.path.basename(filepath))[0]

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

    # Use loader so module has full specs
    module_loader = importlib.machinery.SourceFileLoader(
        module_name, filepath
    )
    # only add to sys.modules if requested
    if sys_module_name:
        sys.modules[sys_module_name] = module
    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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def 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.

    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 = "{}.{}".format(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
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
253
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(folder_path)

Get python scripts as modules from a path.

Parameters:

Name Type Description Default
path str

Path to folder containing python scripts.

required

Returns:

Type Description

tuple: First list contains successfully imported modules and second list contains tuples of path and exception.

Source code in client/ayon_core/lib/python_module_tools.py
 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
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def modules_from_path(folder_path):
    """Get python scripts as modules from a path.

    Arguments:
        path (str): Path to folder containing python scripts.

    Returns:
        tuple<list, list>: First list contains successfully imported modules
            and second list contains tuples of path and exception.
    """
    crashed = []
    modules = []
    output = (modules, crashed)
    # Just skip and return empty list if path is not set
    if not folder_path:
        return output

    # Do not allow relative imports
    if folder_path.startswith("."):
        log.warning((
            "BUG: Relative paths are not allowed for security reasons. {}"
        ).format(folder_path))
        return output

    folder_path = os.path.normpath(folder_path)

    if not os.path.isdir(folder_path):
        log.warning("Not a directory path: {}".format(folder_path))
        return output

    for filename in os.listdir(folder_path):
        # Ignore files which start with underscore
        if filename.startswith("_"):
            continue

        mod_name, mod_ext = os.path.splitext(filename)
        if not mod_ext == ".py":
            continue

        full_path = os.path.join(folder_path, filename)
        if not os.path.isfile(full_path):
            continue

        try:
            module = import_filepath(full_path, mod_name)
            modules.append((full_path, module))

        except Exception:
            crashed.append((full_path, sys.exc_info()))
            log.warning(
                "Failed to load path: \"{0}\"".format(full_path),
                exc_info=True
            )
            continue

    return output

recursive_bases_from_class(klass)

Extract all bases from entered class.

Source code in client/ayon_core/lib/python_module_tools.py
107
108
109
110
111
112
113
114
def recursive_bases_from_class(klass):
    """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