Python Forum
Python 2.7 Import error. Directory and filename conflict
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 2.7 Import error. Directory and filename conflict
#1
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
Reply
#2
I's suggest upgrade of python.
Current version is 3.8.1 and 2.7 is no longer supported.
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 7 6,166 Aug-03-2023, 06:00 PM
Last Post: Gribouillis
  Coding error. Can't open directory EddieG 6 1,063 Jul-13-2023, 06:47 PM
Last Post: deanhystad
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 3,076 Jun-27-2023, 01:17 PM
Last Post: diver999
  import module error tantony 5 3,360 Dec-15-2022, 01:55 PM
Last Post: Lauraburmrs
  python get filename mg24 2 775 Nov-11-2022, 10:57 PM
Last Post: Larz60+
  How to import another Python in different directory? dee 3 852 Sep-28-2022, 06:41 PM
Last Post: dee
  Folium: Conflict with Font Awesome Kit jgomes_eu 0 1,182 Apr-23-2022, 03:18 PM
Last Post: jgomes_eu
  Cryptic Error with import statement Led_Zeppelin 2 2,478 Jan-11-2022, 01:13 PM
Last Post: Led_Zeppelin
  Install any library via pip get an error cannot import name 'SCHEME_KEYS' from 'pip. Anldra12 2 10,490 Jan-04-2022, 01:05 PM
Last Post: Anldra12
  Error about missing directory Led_Zeppelin 3 2,649 Aug-31-2021, 01:37 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020