2

i got a directory structure, this is a simplified example:

project_root/
    __init__.py
    test.py
    mypack/
        __init__.py
        mymodule.py

test.py contains this:

from . import mypack

mypack.mymodule.some_function()

and mypack's __init__.py contains this:

from . import *
__all__ = ['mypack']

When doing this, Python tells me that 'mypack' doesn't have 'mymodule'.
I can only do from mypack import mymodule.
This happens both in Python 2.7 and Python 3.5.

How can I get this to work? It seems it can only be done when I install my packages, and not with project directories.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • What's in the `__init__.py` file of the package? – Moses Koledoye Mar 06 '17 at 17:09
  • I'm confused as to why `import mypack` doesn't throw an ImportError. That should be `from . import mypack`, should it not? Are you sure you're importing the correct `mypack` module? – Aran-Fey Mar 06 '17 at 17:09
  • @Rawing My bad, it is `from . import mypack`. I edited the post. Thanks. –  Mar 06 '17 at 17:17
  • @MosesKoledoye I added the `__init__.py` content in the post. –  Mar 06 '17 at 17:18

2 Answers2

1

For the option you want to work, you have to actually import the function in the mypack.__init__.py file:

#In mypack/__init__.py
import mymodule

Though it can work, it is not the most pythonic way to do it, I'd recommend (and I am still sure it can be bettered):

# In your test.py file
import mypack.mymodule

mypack.mymodule.some_function() # Should work now

This way you know where your file comes from and don't have to modify your __init__.py file for it to work

LoicM
  • 1,786
  • 16
  • 37
1

If you want your module to be accessible from the package import, you need to include it in your __all__:

# from . import *  This is prolly not needed when using __all__
__all__ = ['mymodule']

It appears you misunderstand how __all__ works. You might want to see Can someone explain __all__ in Python?

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139