Python Forum

Full Version: Python 2.7 Import error. Directory and filename conflict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello

Suppose you have this folder and file structure
/ProjectDir
    /library1
        utils.py
        somemodule.py
    /utils
        helper.py
Where in helper.py you have a class called XYZ.

Now suppose you try the following in somemodule.py:
from utils.helper import XYZ
an error will be thrown. Not terribly surprisingly this is due to the fact that python seems to be looking in utils.py, rather the utils folder.
The following does work however:

import imp
helper = imp.load_source('helper', './utils/helper.py')
so I figure that the files and folders are named poorly. Is there any other way though other than using imp to import from helper.py?

Thanks

Peter
I's suggest upgrade of python.
Current version is 3.8.1 and 2.7 is no longer supported.
The import would be like this:
>>> from ProjectDir.utils.helper import XYZ

>>> obj = XYZ('Kent')
>>> obj.name
'Kent'
I do not like long import,so many/most of the time i lift sub-modules up.
This can be done with __init__.py in the top level folder also under ProjectDir.
__init__.py
from .utils.helper import XYZ
Now can import like this.
>>> from ProjectDir import XYZ
>>> 
>>> obj = XYZ('Kent')
>>> obj.name
'Kent'
As mention do not use Python 2.7 anymore Dodgy
Also for Python 2.7 so most have __init__.py blank,in all folder for it to be a package.