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 about missing directory Led_Zeppelin 3 561 Aug-31-2021, 01:37 PM
Last Post: snippsat
  import module with syntax error Skaperen 7 976 Jun-22-2021, 10:38 AM
Last Post: Skaperen
  Import Error Christian 3 1,135 Apr-17-2021, 11:27 PM
Last Post: bowlofred
  List of error codes to find (and count) in all files in a directory tester_V 8 1,371 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Folium import error kashif_flavio 2 1,137 Dec-07-2020, 08:58 AM
Last Post: bowlofred
  Import error Beingcode 0 1,095 Nov-20-2020, 02:57 AM
Last Post: Beingcode
Smile Import error with local file colt 1 738 Nov-08-2020, 07:56 AM
Last Post: Gribouillis
  switch from version 3.5.3 to 3.8.6 get import error python001 9 1,481 Oct-31-2020, 03:02 PM
Last Post: python001
  How to order the Cronjobs to avoid overlap or conflict sadhaonnisa 1 768 Oct-10-2020, 10:26 AM
Last Post: DeaD_EyE
  Append root directory folder and subdirectory to filename glittergirl 9 1,413 Aug-05-2020, 06:12 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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