Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parameter annotations unresolved reference

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
like image 454
Laimonas Sutkus Avatar asked Mar 20 '18 19:03

Laimonas Sutkus


2 Answers

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
like image 53
leandro Avatar answered Oct 24 '22 06:10

leandro


From Python3.7, you can use: from __future__ import annotations

like image 36
Jboulery Avatar answered Oct 24 '22 07:10

Jboulery