Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fail python import from another folder

Tags:

python

import

I am experimenting with python, mostly troubleshooting other people's code. I am trying to get a program to run, "path\folderA\program.py".

I am running the program from path\folderA

I am getting an error:

ImportError: No module named fff.ggg.ppp

program.py contains an import:

from fff.ggg.ppp import mmm

In the folder "path\folderB" there are: "path\folderB\fff\__init__.py" "path\folderB\fff\ggg"

folder ggg also contains __init__.py, as well as program ppp.py

From reading other posts, like Python error "ImportError: No module named" I understand that having the __init__.py makes a folder a "package" which makes imports from it possible - but it doesn't work, since I am getting an error.

This has been working for other people that worked with these projects, so there is something wrong with my setup.

I read something about the directories having to be in the sys.path. Does that mean I have to add them to the environment variable path ? That would mean adding a lot of directories to the PATH though, so it can't be.

So I also found the following:

import sys
sys.path.append( <path to FolderB> )

But that means changing the code (which has not been necessary for other people) and hard-coding a path to what it is on my local machine - which I shouldn't have to, right ?

I can't visualize it - apparently I am not supposed to change the code and hard-code the physical path to the import module - so how can a program from folderA even know to look in folderB for an import ?

How does the magic of __init__.py work ?

like image 960
Thalia Avatar asked Nov 13 '22 02:11

Thalia


1 Answers

I can't visualize it - apparently I am not supposed to change the code and hard-code the physical path to the import module - so how can a program from folderA even know to look in folderB for an import ?

You are correct. Somehow you have to tell python to look for imported modules in folderB. There is no __init__.py magic that lets you import from other folders on your hard drive.

Usually, if you've got various different python packages like that, they work by being installed into python's library. That way they can imported from anywhere. This is usually accomplished by a setup.py script. Check if folderB has one. Run it with python setup.py install.

If that doesn't work, we'll need more information about how this code is structured.

like image 191
Winston Ewert Avatar answered Dec 22 '22 11:12

Winston Ewert