Issue
I have some issues importing some modules in my latest project. I'm really new to Pycharm and Python and I could really use the help/insight.
The problem is I have a folder of utils i wanna use but I cant seem to import modules correctly. Here is what my directories look like roughly:
myproject
utils
utilities
myclass.py
__init__.py
anothermodule
__init__.py
src
helper_func.py
__init__.py
venv
...
main.py
...
I wanna be able to use my classes and functions in the following way:
object = utilities.myclass.myclass( . . . )
thing = utilities.anothermodule.src.helper_func.helper_func ( . . .)
I thought the way to go would be just to :
from utils import utilities
But trying to create ''object'' as previously stated gives me this error (myclass.py contains a class called ''myclass''):
AttributeError: module 'utils.utilities' has no attribute 'myclass'
I have already marker utils, utilities , anothermodule, src as Source roots in Pycharm. What am I doing wrong? I also already added the path of the folder ''utils'' to the sys paths.
Solution
in your utilities/__init__.py file add the following.
from . import myclass
from . import anothermodule
and anothermodule should import src and src should import helper_func and so on.
when you import utilities, python imports the __init__ file under the name of utilities, this is because folders are imported as packages.
another alternative is just doing the following, but you'll have to modify the syntax.
from utils.utilities import myclass
myclass.myclass()
# or
import utils.utilities.my_class
utils.utilities.myclass.myclass()
you can find more information about this in python package documentation
Answered By - Ahmed AEK Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.