What is type annotation for "any callable but a class" in Python using Mypy?

Advertisements I’m trying to perfectly type annotate the following Python function: from typing import Callable, Any import inspect def foo(func: Callable[…, Any]) -> None: if inspect.isclass(func): raise ValueError # Do something… class Bad: pass def good() -> Bad: return Bad() foo(good) # OK foo(Bad) # NOK I would like to narrow down the Callable[…, Any]… Read More What is type annotation for "any callable but a class" in Python using Mypy?

Python – decorating a instance method with mypy (static type checker)

Advertisements I’m new using mypy as a static type checker for my python projects and I’m having troubles trying to define a decorator for a instance method, where I want to access the instance properties. What I want to do is to decorate some class methods that require a method specific call before calling to… Read More Python – decorating a instance method with mypy (static type checker)

Mypy – Incompatible types in assignment

Advertisements I am wondering why I am getting Incompatible types in assignment here? from typing import cast import pyvisa from pyvisa.constants import InterfaceType from pyvisa.resources import GPIBInstrument, TCPIPInstrument class Instrument: resource_manager = pyvisa.ResourceManager() def __init__(self, resource: str): self.resource = self.resource_manager.open_resource(resource_name=resource) if self.resource.interface_type == InterfaceType.tcpip: self.instance: TCPIPInstrument = cast(TCPIPInstrument, resource) elif self.resource.interface_type == InterfaceType.gpib: self.instance: GPIBInstrument… Read More Mypy – Incompatible types in assignment

How to avoid mypy complaints when inheriting from a built-in collection type?

Advertisements Running mypy on code like this class MySpecialList(list): # funky extra functionality gives me my_file.py:42: error: Missing type parameters for generic type "list" [type-arg] I can avoid this by not inheriting from list at all or ignoring this error. But how should I deal with this? Isn’t this a bug in mypy? >Solution :… Read More How to avoid mypy complaints when inheriting from a built-in collection type?

Subclassing in python: restricting the signature of child class functions

Advertisements 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 about the Liskov substitution principle (which I might have studied… Read More Subclassing in python: restricting the signature of child class functions

pandas column-slices with mypy

Advertisements 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 works in the sense… Read More pandas column-slices with mypy

mypy complains about classmethod

Advertisements 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… Read More mypy complains about classmethod

Why does mypy complain about my dictionary comprehension?

Advertisements 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… Read More Why does mypy complain about my dictionary comprehension?