Question

Lets say that we want on Windows with Python 2.7 to either run a command from the GUI by typing it and hitting Enter or right-click on the Python file and choose Edit with IDLE and when IDLE pops up inside IDLE press F5.

Now assume that we have a simplistic file directory like C:\A\B\C\D and inside folder D we want to run the example.py. We want to do it by a certain way which is either:

  • By opening it with a right-click and choose edit with IDLE and pressing F5 or
  • By picking up every line of code and typing her on the Python GUI

Let us say that we type the command:

from C.D import example

Please bear in mind that C and D are folders and inside folder D we have example.py. We also set up the environment variable: C:\A\B\C; in PYTHONPATH so that Python can see folder D as a module and inside of it operate with the example.py submodule.

Is it necessary to have an __init__.py in every folder before the File D?

If file A or file B do NOT have an __init__.py can Python (remember we have typed in the environment variable) go to file C?

Is it a must that in every step of the way aka in every folder in the directory to have an __init__.py?

Was it helpful?

Solution

You only need to add __init__.py to directories that must be treated as packages. Any folder outside the PYTHONPATH search path is never a package and doesn't need to have an __init__.py.

You don't need __init__ in the top-level directory listed on PYTHONPATH either, because that's not a package. C is not a package here, it is a folder on module search path. You cannot import from C; only D is a package.

For your setup, if C:A\B\C is on the module search path, then only items in C can be imported. C:A\B\C\module.py is importable as module, and C:A\B\C\D\ is importable if there is an __init__.py file in that directory, as import D.

Python uses the search path to find top-level names you import; if you try to import foo, the search path is tried one by one, each a location on your harddisk. C:\A\B\C is one such location, it'll look inside that location, but the directory name of the location is never part of the search space.

See the Python tutorial on packages for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top