Python Forum
Python 2.7 Import error. Directory and filename conflict - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python 2.7 Import error. Directory and filename conflict (/thread-24165.html)



Python 2.7 Import error. Directory and filename conflict - petcoo00 - Feb-02-2020

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


RE: Python 2.7 Import error. Directory and filename conflict - Larz60+ - Feb-02-2020

I's suggest upgrade of python.
Current version is 3.8.1 and 2.7 is no longer supported.


RE: Python 2.7 Import error. Directory and filename conflict - snippsat - Feb-02-2020

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.