nukul
nukul

Reputation: 123

python import error cannot import name

I am facing weird problem, although new to python. And this looks bit different from already stated on several forums.

Directory structure:

Project_Folder
 -- Folder A 
 -- SubFolder A1
 -- Subfolder A2 
 -- Subfolder A3 
      -- Folder A3-1 
         -- XYZ.py 
 -- Subfolder A4 ( this contains utility classes)
       -- A4-1.py
       -- A4-2.py

NOTE: All folders contain __init__.py, also PYTHON PATH contains all required directories in PATH.

Script XYZ.py ... is dependent on below 2 utilities classes. Scipts starts with appending on sys.path the sub-folder A4 so ideally there is not need to use A4.A4-1.py instead directly A4-1 should work on import. Like below from A4-1.py import sub-methods from A4-2.py import sub-methods

But this is giving an issue ... as stated in subject. However, same works if I use A4.A4-1.py

Weird part, is same script work on server where project was already setup.

Being new to Python, I need to understand how I am able to execute this script from local machine. (without changing or using Module name in import)

Also, I am using IDE INtelliJ where I have added A4 as dependency to my project. And compiler is able to resolve it but execution is throwing import error ...

Any help is appreciated.

Upvotes: 4

Views: 9994

Answers (2)

nukul
nukul

Reputation: 123

This is now resolved, problem was clash of similar folders on PYTHONPATH , there was a path where utilities existed but no files were there...After removing path itself, it searched on right path for util files...

Upvotes: 2

Mark
Mark

Reputation: 19969

Are the files really named A4-1.py etc? Because that gives me a SyntaxError rather than an ImportError; the - sign is (apparently) not allowed in module names. Which makes sense, because it means minus.

If you are importing within the same probject, I would personally say that in most cases, importing like this

from A4.A4_1 import submethods

is better than adding A4 to your path and then importing from A4_1 directly.

EDIT

Could you try if your path works if you resolve the ..?

import sys,os,time,datetime
testdir = os.path.dirname(os.path.abspath(__file__))
newdir = os.path.abspath(os.path.join(testdir, '../../utilities'))
sys.path.append(newdir)

If not, can you verify that the correct absolute path is included using

print sys.path

EDIT2

If you're checking sys.path, also make sure there's not another directory that matches the start of the import but does not contain the rest (e.g. submethods). If there's another directory A4, maybe Python is using the wrong one.

Also make sure the name is not an existing Python module. (E.g. the first part of the import still works if you rename your module).

Upvotes: 1

Related Questions