Search code examples
python-3.xpython-importpython-module

Cyclic import in Python3


I have the following directory structure:

my-game/
  __init__.py
  logic/
    __init__.py
    game.py
    player.py

game.py and player.py have import dependency on each other (cyclic imports).

game.py has the following definition.

from logic.player import RandomPlayer, InteractivePlayer

T = 8

class Game:
  def __init__(self, p1, p2)
    ...

# some other things

if __name__ == '__main__':
  p1 = RandomPlayer()
  p2 = InteractivePlayer()
  g = Game(p1, p2)
  ...

player.py is as follows:

from logic.game import T

class Player:
  def __init__(self):
    ...

class RandomPlayer(Player):
  def __init__(self):
    ...

class InteractivePlayer(Player):
  def __init__(self):
    ...

I am trying to run the game from logic/ directory but I get the following error.

$ python3 game.py
Traceback (most recent call last):
  File "game.py", line 2, in <module>
    from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'

I then tried running game.py from the directory higher up (my-game/).

$ python3 logic/game.py
Traceback (most recent call last):
  File "logic/game.py", line 2, in <module>
    from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'

What am I doing wrong? How can I make these cyclic imports work?

I have also tried using this import in player.py

from .game import T

and using

from .player import RandomPlayer, InteractivePlayer

in game.py.

In this case, I get a different error. For example, when running from my-game/,

$ python3 logic/game.py
Traceback (most recent call last):
  File "logic/game.py", line 2, in <module>
    from .player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named '__main__.player'; '__main__' is not a package

I get a similar error when running from logic/ directory.

I looked at this post but didn't understand where I was going wrong.


Solution

  • You are made a circulair import in your code try to remove it from your import Vist this link you can find some other info about circular import :Remove python circular import