Reputation: 747
So I am having trouble importing classes in the same directory and getting them to work properly.
I currently have the following hiearchy
My problem is between the 2 files in the bbsource
directory. I have figured out how to get access from the bbsource
directory down to the classes in the objects
directory and vice versa but when I try to from BouncyBallEnv import BouncyBallEnv
in the Console
class I get the following error:
File "E:\PycharmProjects\BouncyBallPythonV0\bbsource\Console.py", line 5, in
from BouncyBallENV import BouncyBallEnv
ImportError: cannot import name 'BouncyBallEnv'
I have tried several things like:
from bbsource import BouncyBallEnv
from bbsource.BouncyBallEnv import BouncyBallEnv
But I can't get it to work.
The only time I could get it to work is when I did the following:
import bbsource.BouncyBallEnv
#Extra
print(bbsource.BouncyBallEnv.BouncyBallEnv.WIDTH)
But there must be a better way to do it than that so that I wouldn't have to type that lengthy statement that is in the print
statement every time that I want to use a static variable in BouncyBallEnv
.
I am still quite confused on how the Python importing works so I'm not sure how to go about doing this. Thank you.
NOTE: Running Python 3.5.1
Upvotes: 2
Views: 1401
Reputation: 195
It is abosolue_import rule.
try
from .BouncyBallENV import BouncyBallEnv
to access module in relative position.
besides, there should be an __init__.py
file under bbsource
directory
Upvotes: 1
Reputation: 596
the thing you need is aliases :
import bbsource.BouncyBallEnv as bbe
#Extra
print(bbe.WIDTH)
and you can't import a module with the from ... import ...
syntax. Only attributes. It work like this :
import <module> [as <alias>]
or
from <module> import <attribute> [, <attribute2>...] # import some attributes
from <module> import * # import everything
with the second one, you could have done :
from bbsource.BouncyBallEnv import WIDTH
# the variable WIDTH is directly loaded : watch out for collision !
print(WIDTH)
Upvotes: 2