Vai al contenuto principale
๐Ÿ”’ Modalitร  anteprima. Le prime quindici lezioni di Foundations sono gratuite; questa รจ Pro. Avvia un trial di 7 giorni per sbloccare l'editor, i suggerimenti AI e il resto del programma. Carta richiesta, disdici in qualsiasi momento dalla Dashboard.Avvia trial di 7 giorni โ†’
โšก
โ† Corsiโ€บSenior Deep-DivesModulo 1 ยท Concorrenza e aspetti interni asincroniโ€บDigitazione: TypeVar, Generico, Protocollopredict4 / 161
+100 XP
Compito๐ŸŒ shown in EN
๐Ÿ“ **Task:** Predict the 4-line verdict from the typing checker: a TypeVar narrowing pass, a Protocol structural match, a Protocol mismatch, and an Any-shortcut. ๐Ÿ“‹ Implement the function above. Tests run automatically. ๐Ÿ’ก **Hint:** Re-read the theory if you get stuck.
Predici output

Leggi il codice attentamente

# 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.

Cosa stamperร  il programma? Scrivi qui: