Why does it say that it can not find my class? Why should I create another class with the same name in order to make make it not complain?
from typing import Dict
class WeekDay:
def __init__(self, day_number, day_name):
self.day_name = day_name
self.day_number = day_number
@staticmethod
def get_week_days() -> Dict[str, WeekDay]: # WeekDay unresolved reference error
weekdays = {
"monday": WeekDay(1, "Monday"),
"tuesday": WeekDay(2, "Tuesday"),
"wednesday": WeekDay(3, "Wednesday"),
"thursday": WeekDay(4, "Thursday"),
"friday": WeekDay(5, "Friday"),
"saturday": WeekDay(6, "Saturday"),
"sunday": WeekDay(7, "Sunday")
}
return weekdays
From docs (Section Forward references)
When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.
A situation where this occurs commonly is the definition of a container class, where the class being defined occurs in the signature of some of the methods.
so in order to solve that just wrap the type with quotes, like this:
from typing import Dict
class WeekDay:
def __init__(self, day_number, day_name):
self.day_name = day_name
self.day_number = day_number
@staticmethod
def get_week_days() -> Dict[str, 'WeekDay']: # quote WeekDay
weekdays = {
"monday": WeekDay(1, "Monday"),
"tuesday": WeekDay(2, "Tuesday"),
"wednesday": WeekDay(3, "Wednesday"),
"thursday": WeekDay(4, "Thursday"),
"friday": WeekDay(5, "Friday"),
"saturday": WeekDay(6, "Saturday"),
"sunday": WeekDay(7, "Sunday")
}
return weekdays
From Python3.7, you can use:
from __future__ import annotations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With