1

I've got a folder that looks something like this. I'm trying to import a class from card.py from test_cards.py

└── 32-PROJECT-Texas-Hold-Em-Poker/
├── poker/
│   ├── card.py
│   └── __init__.py
└── tests/
    └── test_cards.py
    └── __init__.py

In test.py I've tried:

from poker import card

from .poker import card

from ..poker import card
from 32-PROJECT-Texas-Hold-Em-Poker.poker import card


import sys
sys.path.insert(1, '/path/to/Test_folder_1/Test_folder_2')
from Test_folder_2 import add_numbers

but it keeps coming up with either No module named poker or ImportError: attempted relative import with no known parent package. I've tried different variations along with varying where the init.py file is, and honestly I've tried a lot more than what I posted above. I've read up on relative and absolute imports. Short of adding this directory right into my path, I'm completely lost at what seems to be a simple task. I've spend a couple of days on this now and I just can't seem to get it to work. Also, what should I be studying to understand this stuff better rather than finding stuff online? I've just recently learnt about system paths and venvs.

I'm actually following along with The complete Python bootcamp for 2022 on Udemy from test_cards.py, he is able to get a Card class from card.py just from typing

from poker.card import Card

Thank you

Brian
  • 15
  • 2

1 Answers1

0

There are a few ways to do this. Here's one that's quite simple, suitable for test code but not recommended in a production app:

import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'poker'))
import card
sys.path = sys.path[:-1]

That should work no matter where you run your Python script from.

Here's some more information: https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python

DraftyHat
  • 428
  • 1
  • 2
  • 6
  • Hi @DraftyHat I tried that, copied it line for line and it still said no module named poker – Brian Aug 16 '22 at 09:27
  • You're right. I missed that the file you're running is in `tests/`. Replace the sys.path.append line with: `sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'poker'))` – DraftyHat Aug 16 '22 at 10:13
  • @DraftyHate still coming up with no module named poker unfortunately – Brian Aug 16 '22 at 23:11
  • "no module named poker" -- are you still trying to "from poker import card" on another line? – DraftyHat Aug 17 '22 at 10:12
  • no I commented that out – Brian Aug 19 '22 at 21:46
  • Ok. There are no references to a poker module in these lines, so I'm guessing that's coming from somewhere else. I recommend that you take a closer look at the exception you're getting, hopefully that'll show you exactly where it's coming from. – DraftyHat Aug 20 '22 at 13:22