1

This is the structure of my project at the moment.

classes/
├─ __init__.py
├─ card.py
├─ find.py
├─ player.py
├─ table.py
.gitignore
main.py

My __init__.py:

from .card import *
from .player import *
from .table import *

The problem is when I want to import from example player to table.py, like this:

from classes import Player
from classes import Card, CardType, CardValue, HandValue

I get the following error message:

Traceback (most recent call last):
  File "/home/adrian/Desktop/Programozas/Poker/classes/table.py", line 1, in <module>
    from classes import Player
ModuleNotFoundError: No module named 'classes'

Do you have any idea?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
AdriaNn01
  • 86
  • 6
  • How are you running `player.py`? Is it imported in some script or are you running it directly? Nothing has tried to `import classes` up to this point or you would have failed earlier. – tdelaney Dec 28 '22 at 23:43

1 Answers1

2

Notice that this error is occurring in ".../classes/table.py", line 1, as you are trying to import classes.Player when both table.py and player.py are contained in classes. To do this in table.py, you would use from .player import Player just like you did in __init__.py (instead of from classes import Player).

Anything at the same level or above classes can be done using this method, but anything defined inside classes cannot call up to classes, as anything therein does not even know classes exists.

Edit: if you need to be able to run both main.py and table.py, you could do something like:

# in table.py
try:
    from player import Player # this should work when running table.py directly
except:
    from .player import Player # this should work when running main.py (it's a relative import)
Nicholas Barrow
  • 422
  • 3
  • 10
  • More on sibling imports: https://stackoverflow.com/questions/6323860/sibling-package-imports – Nicholas Barrow Dec 29 '22 at 04:33
  • Once I change for example the player's import from " from classes import Player" to "from .player .... " I get this error message: " from .player import Player ImportError: attempted relative import with no known parent package " – AdriaNn01 Dec 29 '22 at 11:48
  • If you need to run `table.py`, you could structure your import block to use a try/except format (`try: from .player import Player except: from player import Player`)... I added this to the original answer with some more details – Nicholas Barrow Dec 30 '22 at 14:13