Slaknation
Slaknation

Reputation: 1926

having trouble importing python module from root directory in PyCharm

Here is my folder structure:

lib\
    pt_hil\
        utilities\
            PT_HILdSPACE_Utils\
                exception\
                    __init__.py  --> has "class SimulatorException(Exception):"
                pythonScript.py

I opened the project from the "lib" folder in PyCharm. In the "pythonScript.py" script, when I try to import SimulatorException by doing:

from pt_hil.utilities.PT_HIL_dSPACE_Utils.exception import SimulatorException

It doesn't work. However if I do:

from exception import SimulatorException

It works. Shouldn't the root directory be from the lib folder? When I look in settings the content root is set to the lib folder.

Upvotes: 1

Views: 801

Answers (1)

Avihoo Mamka
Avihoo Mamka

Reputation: 4786

One of the purposes of a __init__.py file, is to mark the directory as a valid Python package that you can import.

You only declared the exception folder to be a valid Python package and therefore that's the root package you can start importing from.

It's either you create top level packages by adding empty __init__.py files to each top level folder you have and then can import as you originally wanted, or keep the current structure and import directly from exception package.

Upvotes: 1

Related Questions