mypy

StrEnums and type narrowing (mypy)

StrEnums and type narrowing (mypy) Question: I am fighting with type narrowing of StrEnums To summarize my issue I have some abstract base class from abc import ABC, abstractmethod from enum import StrEnum class Animal(ABC): @staticmethod @abstractmethod def speak(animal_type: StrEnum): … and derivative classes each with their own StrEnums: class FrogType(StrEnum): frog = "frog" toad …

Total answers: 2

Mypy error: PEP 695 type aliases are not yet supported

Mypy error: PEP 695 type aliases are not yet supported Question: I encountered an error while trying to use type aliases in Python with MyPy. Here’s a simplified version of my code: type IntList = list[int] # This line causes the error type OtherType = int # This line causes the error class test: pass …

Total answers: 1

Using a pipe symbol in typing.Literal string

Using a pipe symbol in typing.Literal string Question: I have a function that accepts certain literals for a specific argument: from typing import Literal def fn(x: Literal["foo", "bar", "foo|bar"]) -> None: reveal_type(x) The third contains a pipe symbol (|), "foo|bar". This is interpreted by mypy as an error, as the name foo is not defined. …

Total answers: 1

MyPy linting conflicting typing with typing.Self

MyPy linting conflicting typing with typing.Self Question: During linting and rewriting of an immutable class, operations do not pass the mypy checker. The class implements operations such as__add__, however, every function that returns a new instance of the same class triggers a typing error Incompatible return value type (got "Point", expected "Self") [return-value]mypy(error) Methods I’ve …

Total answers: 1

mypy & typing singleton / factory classes

mypy & typing singleton / factory classes Question: I often use the following construct to generate singletons in my code: class Thing: pass class ThingSingletonFactory: _thing = None def __new__(cls) -> Thing: if cls._thing is None: cls._thing = Thing() return cls._thing def get_thing() -> Thing: return ThingSingletonFactory() thing = get_thing() same_thing = get_thing() assert thing …

Total answers: 3

How do I fix the return type of a Django model manager's method?

How do I fix the return type of a Django model manager's method? Question: I’m using Django 4.1.7 with django-stubs 1.16.0, and mypy 1.1.1. I have code that looks like this: class ProductQuerySet(QuerySet): … class ProductManager(Manager): def create_red_product(self, **kwargs) -> "Product": return self.model(color=Product.Color.RED, **kwargs) _product_manager = ProductManager.from_queryset(ProductQuerySet) class Product(Model): … objects = _product_manager() When mypy …

Total answers: 1

How can I type annotate a general nested TypedDict?

How can I type annotate a general nested TypedDict? Question: I’m trying to remove the Any type hint from code similar to the following: from typing import TypedDict, Any class NestedDict(TypedDict): foo: str class EventDict(TypedDict): nested: NestedDict class BaseEventDict(TypedDict): nested: Any # this should accept NestedDict but also other TypedDicts which may contain additional fields …

Total answers: 2

Subclassing in python: restricting the signature of child class functions

Subclassing in python: restricting the signature of child class functions Question: Let’s say I have a base class like class Foo: def __init__(self): return def foo(self, a: str | int) -> float: raise NotImplementedError() which gets inherited by class FooChild(Foo): def __init__(self): return def foo(self, a: str) -> float: return 0.5 Now, mypy is complaining …

Total answers: 1

pandas column-slices with mypy

pandas column-slices with mypy Question: Lately I’ve found myself in a strange situation I cannot solve for myself: Consider this MWE: import pandas import numpy as np data = pandas.DataFrame(np.random.rand(10, 5), columns=list("abcde")) observations = data.loc[:, :"c"] features = data.loc[:, "c":] print(data) print(observations) print(features) According to this Answer the slicing itself is done correct and it …

Total answers: 1

mypy: Incompatible types in assignment when overwriting a variable

mypy: Incompatible types in assignment when overwriting a variable Question: I’m getting an assignment error when running mypy version 0.942 on my script that I can’t make sense of. I have a variable price_point that takes the form of a string, and depending on if the string contains a "-", will determine if the variable …

Total answers: 1