PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 25, 2022

[FIXED] How to properly import modules in a Pycharm project?

 November 25, 2022     import, module, pycharm, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing