NRagot
NRagot

Reputation: 294

python import class in module throws ImportError

Sorry if this question seems very simple, i am quite experienced in java but absolutely not in python, and the way importations works in python is still quite a mistery to me.
The problem being that from what i have collected from the internet, i feel like I have done everything that is necessary for my script to import a module inside a folder.

my project looks like this

/omme
    start.py
    /foo
        __init__.py   #is empty
        bar.py        #has a class named BarClass

start.py only has this

from foo.bar import BarClass

b = BarClass()

when i run this script in the spyder IDE i get this

runfile('/home/nathan/Documents/workspace/omme/start.py', wdir='/home/nathan/Documents/workspace/omme')
Reloaded modules: foo.bar
Traceback (most recent call last):

  File "<ipython-input-38-c3b9ba6593fb>", line 1, in <module>
    runfile('/home/nathan/Documents/workspace/omme/start.py', wdir='/home/nathan/Documents/workspace/omme')

  File "/home/nathan/.anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "/home/nathan/.anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/nathan/Documents/workspace/omme/start.py", line 1, in <module>
    from foo.bar import BarClass

ImportError: cannot import name 'BarClass'

and then even weirder, if I replace foo.bar by test.bar it throws a ModuleNotFoundException (I suspect some ide shenanigans).

What am I doing wrong ?

Thank you for your time, sincerly nathan.

Upvotes: 1

Views: 287

Answers (1)

NRagot
NRagot

Reputation: 294

thanks for @zvone, I now know my mistake : i just mispelled the name of the class... sorry for your time.

As I can't remove the question, I'll tell you the simple trick @vzone told me to solve the two problems i had:

import lib
print (lib)

let you check from where the lib is located, as you may be loading a similarly named lib from somewhere else. which happened to me with my test.bar
furthermore using

import lib
print (dir( lib))

gives you a pretty neat look on what is in your classes which makes it easier to debug.

Thank the lad, he did it all in the comments.

Upvotes: 1

Related Questions