Python type-hints where only the first item is None

I am implementing a priority queue class in Python using a binary heap, which has a attribute that stores the binary tree. In my implementation, I’m using 1-indexing because it has the nice property that I can use lists (say, the list is called heap) and the children of heap[i] are exactly heap[2*i] and heap[2*i+1],… Read More Python type-hints where only the first item is None

mypy complains about classmethod

I have a trivial dataclass (from pydantic) from pydantic.dataclasses import dataclass from abc import ABCMeta from abc import abstractmethod from pydantic.dataclasses import dataclass @dataclass class BaseEntity(metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, other: dict): … @abstractmethod def dict(self): … @dataclass class UserEntity(BaseEntity): id: Optional[str] name: str email: str avatar: str @classmethod def from_dict(cls, other: dict): return cls(… Read More mypy complains about classmethod

Why does mypy complain about my dictionary comprehension?

I’m trying to do an update of a dictionary with a dictionary comprehension. My code works fine, but mypy raises an error while parsing the types. Here’s the code: load_result = {"load_code": "something"} load_result.update({ quality_result.quality_code: [quality_result.quantity] for quality_result in random_quality_results() }) In that code the quality_result objects have those two attributes quality_code and quantity which… Read More Why does mypy complain about my dictionary comprehension?

Ignoring mypy attr-defined with triple quotes

The following code: # type: ignore[attr-defined] timeit.template = """ # type: ignore[attr-defined] def inner(_it, _timer{init}): {setup} _t0 = _timer() for _i in _it: retval = {stmt} _t1 = _timer() return _t1 – _t0, retval """ # type: ignore[attr-defined] # type: ignore[attr-defined] Yields error: src/snncompare/Experiment_runner.py:45: error: Module has no attribute "template" [attr-defined] Found 1 error in… Read More Ignoring mypy attr-defined with triple quotes

Mypy – how to fix incompatible type inside list comprehensions?

It’s a pyspark. I’m looking for a way to fix an error from mypy about the wrong type for an element inside a list comprehension – data_frame[x]. The error: List item 0 has incompatible type "List[Column]"; expected "str"  [list-item] It refers to this line of a code: columns = list(set(columns + [*[data_frame[x] for x in… Read More Mypy – how to fix incompatible type inside list comprehensions?

How to declare additional attributes when subclassing str?

Consider the following class: class StrWithInt(str): def __new__(cls, content, value: int): ret = super().__new__(cls, content) ret.value = value return ret This class just works fine, but when using mypy, the following error occurs: "StrWithInt" has no attribute "value" [attr-defined] Is there some way to explicitly state the attribute in this case? What is the proper… Read More How to declare additional attributes when subclassing str?

Why does mypy raise truthy-function error for assertion?

I inherited a project from a dev who is no longer at the company. He wrote this test: from contextlib import nullcontext as does_not_raise def test_validation_raised_no_error_when_validation_succeeds(): # given given_df = DataFrame(data={"foo": [1, 2], "bar": ["a", "b"]}) given_schema = Schema( [ Column("foo", [InListValidation([1, 2])]), Column("bar", [InListValidation(["a", "b"])]), ] ) # when _validate_schema(given_df, given_schema) # then assert… Read More Why does mypy raise truthy-function error for assertion?

Mypy errors in Generic class

I slightly modified the documented mypy generic example but got an error: from typing import Generic, TypeVar, Union T = TypeVar("T", bound=Union[int, float]) class Person(Generic[T]): def __init__(self, salary: T) -> None: self.salary: T = salary def get_yearly_bonus(self, amount: T) -> None: self.salary += amount def __str__(self) -> str: return f"Person(salary={self.salary})" p = Person[int](9) p.get_yearly_bonus(6) print(p)… Read More Mypy errors in Generic class