Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use __init__.py to modify sys path is a good idea?

I want to ask you something that came to my mind doing some stuff.

I have the following structure:

src
    - __init__.py
    - class1.py
    + folder2
        - __init__.py
        - class2.py

I class2.py I want to import class1 to use it. Obviously, I cannot use

from src.class1 import Class1

cause it will produce an error. A workaround that works to me is to define the following in the __init__.py inside folder2:

import sys
sys.path.append('src')

My question is if this option is valid and a good idea to use or maybe there are better solutions.

Another question. Imagine that the project structure is:

src
    - __init__.py
    - class1.py
    + folder2
        - __init__.py
        - class2.py
    + errorsFolder
        - __init__.py
        - errors.py

In class1:

from errorsFolder.errors import Errors

this works fine. But if I try to do in class2 which is at the same level than errorsFolder:

from src.errorsFolder.errors import Errors

It fails (ImportError: No module named src.errorsFolder.errors)

Thank you in advance!

like image 982
Solar Avatar asked Sep 26 '18 11:09

Solar


People also ask

What's the purpose of __ init __ py?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

What is the purpose of __ init __ py file at the time of creating Python packages?

If a file named __init__.py is present in a package directory, it is invoked when the package or a module in the package is imported. You can use this to execute package initialization code, for example for the initialization of package-level data.

Is SYS path append bad?

Most of the time, appending to sys. path is a poor solution. It is better to take care of what your PYTHONPATH is set to : check that it contains your root directory (which contains your top-level packages) and nothing else (except site-packages which i).

What should __ init __ py contain?

There is a range of options of what to put in an __init__.py file. The most minimal thing to do is to leave the __init__.py file totally empty. Moving slightly away from this, while still keeping things simple, you can use an __init__.py only for determining import order.


1 Answers

One correct way to solve this is to set the environment variable PYTHONPATH to the path which contains src. Then import src.class1 will always work, regardless of which directory you start in.

like image 104
John Zwinck Avatar answered Oct 19 '22 23:10

John Zwinck