For my terminal Uno game, I want to have a very simple Card
class that has two attributes: colour and value.
In this class, I also want to have a method that takes another card as an argument, and checks whether putting the initial card on this topCard
would be a legal move.
The code as written down below works perfectly fine with my other files, but I feel like it could benefit from some better type annotation.
import typing
class Card:
def __init__(self, colour: str, value: typing.Union[str, int]):
self.colour = colour
self.value = value # can be string or int (e.g., 'Reverse' or 6)
def __str__(self) -> str:
return f'[{self.colour} | {self.value}]'
def is_valid_move(self, topCard) -> bool:
if self.colour == 'Black': # always legal
return True
elif self.colour == topCard.colour or self.value == topCard.value:
return True
return False
Because I want to be as strict as possible (as far as Python allows any strictness of course), I want is_valid_move
to look like this:
def is_valid_move(self, topCard: Card) -> bool:
...
By default my IDE shows the yellow squiggly line under Card
, and when running the code I get NameError: name 'Card' is not defined
.
When I try to from card import Card
— the file is called card — I get ImportError: cannot import name 'Card' from partially initialized module 'card' (most likely due to a circular import)
.
This does seem to fix the squiggly line issue and according to my IDE nothing is wrong, but if it doesn't run I assume that this can not be the way to handle things.
So my question is: Is there any way to use Card
as a type hint for one of it's own methods?