mypy

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

Typing to mark return values of current class type or any of its subclasses

Typing to mark return values of current class type or any of its subclasses Question: I want to make sure that the from_dict in the following method works well in its subclasses as well. Currently, its typing does not work (mypy error "Incompatible return value type"). I think because the subclass is returning an instance …

Total answers: 1

how to type python API responses similar to TS `as`?

how to type python API responses similar to TS `as`? Question: I’m using a lib that types its response as -> (Unknown | Response | Any) If i know/expect the response to be a Response and that is has an id field, how can I cast that in my code? Typescript provides an as <type> …

Total answers: 1

Type hints support for subclass of dict

Type hints support for subclass of dict Question: How can I implement a subclass of dict so it supports type hints like vanilla dict? I want to create a custom dict that does some extra work when modifying item, I implement it by subclassing the built-in dict class. After doing some googling I learned that …

Total answers: 1