1

I have the following file structure in a package:

test/
test/__init__.py
test/testmodule.py
caller.py

On testmodule.py:

def myfunc():
    print('wew')

On __init__.py:

from . import testmodule
from .testmodule import *
__all__ = ['testmodule']

And on caller.py:

from test import *
if __name__ == '__main__':
    myfunc()

But I get a "NameError: 'myfunc' is not defined". If I do instead test.myfunc(), it works. How can I do from <module> import * so that it works without needing to add the module name to the call?

wewlie
  • 11
  • 1
  • 4
    You wrote `__all__ = ['testmodule']`. Since you defined an `__all__` and it doesn't include `myfunc`, `from test import *` doesn't import `myfunc`. Was that just a typo you missed, or do you need an explanation? – abarnert Mar 26 '18 at 20:14
  • So let me see if I understand it. If I have 20 functions in a file, I have to list all of them in the `__all__`? Is there a easier way to go about this? Is what I'm doing not pythonic? What would be the point of listing a module in all? Is it so that if I have a subfolder module2, and more .py and `__init__.py` files inside this subfolder module2? – wewlie Mar 26 '18 at 20:17
  • 1
    You can just not specify `__all__`. Or don't `import *`, it's considered bad practice to do so in long term scripts. – Alex Hall Mar 26 '18 at 20:19
  • The point of listing a module in `__all__` is the same as listing _any_ name: so that `from me import *` will include that module as one of the names that gets imported. Modules aren't really anything that special; `import testmodule` works pretty similar to `testmodule = __import__('testmodule')`, creating a module object and binding it to a global name. – abarnert Mar 26 '18 at 20:28
  • Also, what is the difference between `from . import ` and `from . import *` inside the `__init__`? Both seem to let me access my objects. – wewlie Mar 26 '18 at 20:29
  • Anyway, if you leave out the `__all__`, you get the default behavior, which is (slightly oversimplying) everything that starts with an underscore is "private" so it doesn't get included, everything else is "public" so it does. You only need `__all__` if you want to override that default. – abarnert Mar 26 '18 at 20:29

0 Answers0