python-typing

Type hinting decorator with bounded arguments

Type hinting decorator with bounded arguments Question: An example of what I’d like to do is as follows: @dataclass class Arg1: x = field() @dataclass class Arg2: x = field() @dataclass class Obj: y = field() T = TypeVar("T") R = TypeVar("R", bound=(Arg1 | Arg2)) C = TypeVar("C", bound=Callable[[Self, R], T]) @staticmethod def deco(f: C) …

Total answers: 2

Why does Mypy report a subset of JSON as invalid?

Why does Mypy report a subset of JSON as invalid? Question: I have a base class that returns a JSON type. I then have subclasses that return more specific types that should I think be valid JSON types, but Mypy reports an error: error: Return type "List[Dict[str, JSON]]" of "return_json" incompatible with return type "JSON" …

Total answers: 1

SQLAlchemy returns `list` instead of `Sequence[Row[_TP]]`

SQLAlchemy returns `list` instead of `Sequence[Row[_TP]]` Question: The type-hinting of the method sqlalchemy.engine.result.Result.fetchall() suggests the method is supposed to return a Sequence[Row[_TP]] but when I print print(type(result_1.fetchall())), I get a list. Is there anything I’m missing? My code is the following: if __name__ == "__main__": engine: sqlalchemy.engine.base.Engine = sqlalchemy.create_engine( "sqlite:///data_SQL/new_db.db", echo=False ) with engine.connect() as …

Total answers: 2

How to resolve attribute reference for inherited objects in Python?

How to resolve attribute reference for inherited objects in Python? Question: I would like to have a proper Python typing for the setup I have created. The issue I have is connected with class B, in which my IDE (pyCharm) reports unresolved attribute reference.However, this setup is working fine. class ConfigA: def __init__(self): self.param1: int …

Total answers: 1

Python equivalent to `as` type assertion in TypeScript

Python equivalent to `as` type assertion in TypeScript Question: In TypeScript you can override type inferences with the as keyword const canvas = document.querySelector(‘canvas’) as HTMLCanvasElement; Are there similar techniques in Python3.x typing without involving runtime casting? I want to do something like the following: class SpecificDict(TypedDict): foo: str bar: str res = request(url).json() as …

Total answers: 2

Python typing for a metaclass Singleton

Python typing for a metaclass Singleton Question: I have a Python (3.8) metaclass for a singleton as seen here I’ve tried to add typings like so: from typing import Dict, Any, TypeVar, Type _T = TypeVar("_T", bound="Singleton") class Singleton(type): _instances: Dict[Any, _T] = {} def __call__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: if cls …

Total answers: 1

Difference between collections.abc.Sequence and typing.Sequence

Difference between collections.abc.Sequence and typing.Sequence Question: I was reading an article and about collection.abc and typing class in the python standard library and discover both classes have the same features. I tried both options using the code below and got the same results from collections.abc import Sequence def average(sequence: Sequence): return sum(sequence) / len(sequence) print(average([1, …

Total answers: 2

How to annotate a decorator that returns a `property`

How to annotate a decorator that returns a `property` Question: I want to create a decorator that return a property of the decorated function, i.e: from typing import TYPE_CHECKING def make_prop(param): def wrapper(func) -> ‘property(func)’: return property(func) return wrapper class A: @make_prop(‘foo’) def a(self) -> str: return "hello" a = A() assert a.a == "hello" …

Total answers: 2

Why I can't type hint that method takes instance attribute as argument?

Why I can't type hint that method takes instance attribute as argument? Question: I have this class, doesn’t matter what it does, so here is minimal example: class DashboardMethods(BaseMethods): _time_templates = IntervalTemplates() async def get_kpi_for_interval(self, interval): pass I want to type hint interval parameter that it should be attribute of instance of class IntervalTemplates. I …

Total answers: 2

Python type hints for unpacking object

Python type hints for unpacking object Question: I’m trying to implement type hinting for object unpacking. Here is what I have currently from typing import Tuple class A: def __init__(self, x: int, y: str): self.x = x self.y = y def astuple(self) -> Tuple[int, str]: return self.x, self.y # Need to annotate the return type …

Total answers: 1