4

enter image description here I saw some code of this format:

from b.c import *

However there is no __init__.py in b and I do not undersand how it succeeds.


The directory structure looks like this:

a.py
b
    c.py

Is it possible to from b.c import * in a.py even if there is no __init__.py in folder b?

user3822769
  • 151
  • 6

1 Answers1

1

This is not possible in Python 2.7 due to how the PYTHONPATH is constructed. See this question for an excellent explanation.


However nothing is impossible in python...

Thanks to PEP 420: Implicit Namespace Packages: this is indeed possible in Python 3.3 and up.

__init__.py files are now optional for namespace packages:

Using Python 3.5 on Windows


a.py
b/
    c.py

b/c.py

def hello_world():

    print("Hello World!")

a.py

from b.c import *

hello_world

Then:

>>> import a
Hello World!

More information about the caveats of namespace packages versus regular packages can be found in the PEP and in David Beazley's excellent talk Modules and Packages: Live and Let Die!

Community
  • 1
  • 1
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
  • Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> from peak.util.decorators import * >>> sys.modules['peak.util.decorators'] >>> (games)ubuntu@i:$ ll /home/ubuntu/games/local/lib/python2.7/site-packages/peak total 12 drwxrwxr-x 3 ubuntu ubuntu 4096 Jul 18 2013 ./ drwxrwxr-x 75 ubuntu ubuntu 4096 Sep 25 06:15 ../ drwxrwxr-x 2 ubuntu ubuntu 4096 Oct 30 13:51 util/ – user3822769 Oct 30 '15 at 16:01
  • Ah now I see what you mean. Can you check peak/__init__.py? Maybe it defines the module directly – Sebastian Wozny Oct 30 '15 at 16:26