"_func" not being imported even when declared in __all__

50 Views Asked by At

I am using Python 2.

I was able to find that __all__ by default does not pass _functions (underscored "internal" functions) when __all__ is not declared (i.e. just using from module import * but without __all__ explicitly defined). However, I'm also seeing that _functions are not passed even if they are added to __all__.

What words am I missing in my question to find the answer to this? Is this a continued "issue" (or expected behavior?) in Python 3?

My example is:

I have a mix of internal and external functions I am creating. Currently my bypass for this issue was to put the _functions (underscored functions, aka "internal functions", renamed without the underscore) into a ._internal_module_folder and then import the ._internal_module_folder into a external_module and add the external functions to the __all__ of external_module but leave out the internal functions.

So my original tree (with the issue) would look something like this:

/
    modules_folder/
        _internal_module_folder/
            __init__.py
            _internal_module.py
        __init__.py
        external_module.py

where:

modules_folder/_internal_module_folder/__init__.py:

from ._internal_module import *

modules_folder/_internal_module_folder/internal_module.py:

__all__ = [
    # functions:
    'ext_func1',
    'ext_func2',

    # _functions:
    '_intl_func1', 
    '_intl_func2']

def ext_func1(*args, **kwargs):
    pass
def _int_func1(*args, **kwargs):
    pass
# etc.

modules_folder/__init__.py:

from external_module import * # Should import _functions from __all__??

modules_folder/external_module.py:

from ._internal_module_folder import *
__all__ = ['ext_func1', 'ext_func2'] + list_of_external_functions_from_this_module
<define external_functions_from_this_module some of which use _int_func1>

When run I get an error that _int_func1 does not exist even though it's in __all__ explicitly?

My solution:

I renamed _int_func to int_func, changed the import in modules_folder/__init__.py to from . import _internal_module as im and then aliased the internal functions on call (for ease of Find Definition in VS Code and change the function to NOT be called with the default __all__) with _int_func1 = im.int_func1.

Is this PEP 8 approved?

Summary: Put _function into __all__ but it wasn't passed on from module import *.

0

There are 0 best solutions below