I want to import a class from a .py to another .py but it says : no module named "example"

Question:

My folders looks like this:

Code_Sources (folder)
    main.py
    Class (folder)
        game_class.py
        player_class.py

I made in game_class.py:

from player_class import *

And when I run the game_class.py I have no problem.
But when I run main.py which contains:

import pygame

from Class.game_class import Game

if __name__ == "__main__" :
    pygame.init()
    game = Game()
    game.run()

It says that an error comes from game_class.py and No module named 'player_class'.
I don’t understand why.

I tried the method of init.py but it doesn’t work.

Asked By: Hikuyo Diesolow

||

Answers:

Check out python documentation on packages.

Also it’s good practise to follow style guide for python code PEP8, especially the package and module names section.

Let’s rebuild your code structure a bit.

code_sources
  | __init__.py
  | main.py
  | classes
      | __init__.py
      | game_class.py
      | player_class.py

The names of directories are still vague imo, think about giving them name that reflect what they are grouping inside.

All your internal imports should look like this now:

from code_sources.classes import player_class

Even when you are importing something between game_class and player_class

Also try to avoid asking questions that already has been answered or are well documented by the software creators. Python is perfect example of great documentation.

Here is one example of your question in StackOverflow: Import a module from a relative path

Answered By: w8eight
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.