When the symbol `__all__` is defined in a module, `mp_import_all()` should import all listed symbols into the global environment, rather than relying on the underscore-is-private default. This is the standard in CPython. Each item is loaded in the same way as if it would be an explicit import statement, and will invoke the module's `__getattr__` function if needed. This provides a straightforward solution for fixing star import of modules using a dynamic loader, such as `extmod/asyncio` (see issue #7266). This improvement has been enabled at BASIC_FEATURES level, to avoid impacting devices with limited ressources, for which star import is of little use anyway. Additionally, detailled reporting of errors during `__all__` import has been implemented to match CPython, but this is only enabled when ERROR_REPORTING is set to MICROPY_ERROR_REPORTING_DETAILED. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
50 lines
1.0 KiB
Python
50 lines
1.0 KiB
Python
__all__ = ['publicFun', 'PublicClass', 'dynamicFun']
|
|
|
|
|
|
# Definitions below should always be imported by a star import
|
|
def publicFun():
|
|
return 1
|
|
|
|
|
|
class PublicClass:
|
|
def __init__(self):
|
|
self._val = 1
|
|
|
|
|
|
# If __all__ support is enabled, definitions below
|
|
# should not be imported by a star import
|
|
def unlistedFun():
|
|
return 0
|
|
|
|
|
|
class UnlistedClass:
|
|
def __init__(self):
|
|
self._val = 0
|
|
|
|
|
|
# Definitions below should be not be imported by a star import
|
|
# (they start with an underscore, and are not listed in __all__)
|
|
def _privateFun():
|
|
return -1
|
|
|
|
|
|
class _PrivateClass:
|
|
def __init__(self):
|
|
self._val = -1
|
|
|
|
|
|
# Test lazy loaded function, as used by extmod/asyncio:
|
|
# Works with a star import only if __all__ support is enabled
|
|
_attrs = {
|
|
"dynamicFun": "funcs",
|
|
}
|
|
|
|
|
|
def __getattr__(attr):
|
|
mod = _attrs.get(attr, None)
|
|
if mod is None:
|
|
raise AttributeError(attr)
|
|
value = getattr(__import__(mod, globals(), locals(), True, 1), attr)
|
|
globals()[attr] = value
|
|
return value
|