Przejdź do treści głównej
🔒 Tryb podglądu. Pierwszych piętnaście lekcji Foundations jest darmowych; ta jest Pro. Rozpocznij 7-dniowy trial, aby odblokować edytor, podpowiedzi AI i resztę kursu. Wymagana karta, anulujesz w dowolnym momencie w Dashboard.Rozpocznij 7-dniowy trial →
← KursySenior Deep-DivesModuł 1 · Współbieżność i asynchroniczne elementy wewnętrzneWpisywanie: TypeVar, Generic, Protocolpredict4 / 161
+100 XP
Zadanie
📝 **Zadanie:** Wytypuj 4-wierszowy werdykt na podstawie modułu sprawdzania pisania: przejście zawężające TypeVar, dopasowanie strukturalne protokołu, niezgodność protokołu i skrót Any. 📋 Zaimplementuj powyższą funkcję. Testy uruchamiają się automatycznie. 💡 **Wskazówka:** Jeśli utkniesz, przeczytaj ponownie teorię.
Przewiduj wynik

Przeczytaj kod uważnie

# A miniature mypy-style checker that only knows the rules from
# the theory above. Calls return "ok" or "error: <reason>".

class TypeChecker:
    def check_generic(self, stack_type, value_type):
        # Stack[int] doesn't accept str → mypy error.
        if stack_type == value_type:
            return "ok"
        return f"error: Stack[{stack_type}] cannot accept {value_type}"

    def check_protocol(self, obj_methods, required_methods):
        # Protocol passes when obj has every required method —
        # NO inheritance required (structural subtyping).
        missing = required_methods - obj_methods
        if not missing:
            return "ok"
        return f"error: missing {sorted(missing)}"

    def check_any(self, _value_type):
        # Any disables checking — always accepts. Mypy stays quiet
        # but you lose the safety net.
        return "ok"

chk = TypeChecker()

# 1) Stack[int] accepting an int — fine.
print(chk.check_generic("int", "int"))

# 2) SupportsLen Protocol — list has __len__, so it passes.
print(chk.check_protocol({"__len__", "__iter__"}, {"__len__"}))

# 3) Same protocol against an int (no __len__).
print(chk.check_protocol({"__add__"}, {"__len__"}))

# 4) Cache annotated with Any — checker stays quiet even on
# a clearly wrong assignment. Mypy bug-magnet.
print(chk.check_any("Stack[int] = 'two'"))

# What does this print? Type your prediction.

Co wypisze program? Napisz tutaj:

💬 Dyskusja

Zadaj pierwsze pytanie lub podziel się wskazówką.
Zaloguj się aby dołączyć do dyskusji. Czytanie jest darmowe.
Ładowanie dyskusji…