|
| 1 | +def __is_defined_in_submodule(submodule_name_prefix, x): |
| 2 | + """ |
| 3 | + Utility method to return True if x is not a module and its module name starts with submodule_name_prefix |
| 4 | + e.g. 'autoclass.autohash_'. |
| 5 | +
|
| 6 | + :param submodule_name_prefix: |
| 7 | + :param x: |
| 8 | + :return: |
| 9 | + """ |
| 10 | + # if _inspect.ismodule(x): |
| 11 | + # return False |
| 12 | + # else: |
| 13 | + from inspect import getmodule |
| 14 | + m = getmodule(x) |
| 15 | + if m is None: |
| 16 | + return True |
| 17 | + elif hasattr(m, '__name__') and m.__name__.startswith(submodule_name_prefix): |
| 18 | + return True |
| 19 | + else: |
| 20 | + return False |
| 21 | + |
| 22 | + |
| 23 | +def __get_all_submodules_symbols(pkg_name, submodules_to_export): |
| 24 | + """ |
| 25 | + Generates the list of symbol names that can be used in the `__all__` variable in init.py |
| 26 | + The list is created from a list of submodules. |
| 27 | +
|
| 28 | + All symbols in these submodules that are not private and that are actually defined in there, get in the list. |
| 29 | + The submodules themselves end up in the list. |
| 30 | +
|
| 31 | + Note that this function should only be used if you also actually import those symbols in the init.py, so that they |
| 32 | + are actually visible at package root level. |
| 33 | +
|
| 34 | + :param submodules_to_export: a list of submodule names to export |
| 35 | + :return: |
| 36 | + """ |
| 37 | + from inspect import getmembers |
| 38 | + from copy import copy |
| 39 | + from importlib import import_module |
| 40 | + |
| 41 | + # first create a copy of the submodules list |
| 42 | + all_ = copy(submodules_to_export) |
| 43 | + |
| 44 | + # then for each submodule add the symbols that are declared in this submodule |
| 45 | + for submodule in submodules_to_export: |
| 46 | + submodule_full_name = pkg_name + '.' + submodule |
| 47 | + imported_module = import_module(submodule_full_name) |
| 48 | + # print(imported_module.__name__) |
| 49 | + for x_name, symbol in getmembers(imported_module): |
| 50 | + if not x_name.startswith('_'): |
| 51 | + if __is_defined_in_submodule(submodule_full_name, symbol): |
| 52 | + # print('{} is exported'.format(x_name)) |
| 53 | + all_.append(x_name) |
| 54 | + return all_ |
| 55 | + |
| 56 | + |
| 57 | +def __remove_all_external_symbols(pkg_name, globs): |
| 58 | + for x_name in list(globs.keys()): |
| 59 | + if not __is_defined_in_submodule(pkg_name, globs[x_name]): |
| 60 | + del globs[x_name] |
0 commit comments