typing

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

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

bounds with typyvar

bounds with typyvar Question: I want to make sure that the input is the same as output, I tried to use TypeVar to bound the typing but I can’t get it to work… from typing import TypeVar, Union, Any import pandas as pd class my_Class(): def __init__(self): self.days = [] self.count = 0 def __call__(self, …

Total answers: 2

Annotation with custom types derived from numerical types in Python

Annotation with custom types derived from numerical types in Python Question: I am trying to create a custom type/class in Python that plays well with annotations and also can be checked in runtime. The only way I was able to achieve this is by using TypeAlias. from __future__ import annotations import typing FloatAlias: typing.TypeAlias = …

Total answers: 1

Generic vs Specific MyPy types of functions

Generic vs Specific MyPy types of functions Question: I remember reading, or hearing somewhere that for a function, input types should be as generic as possible (Iterable over list), but return types should be as specific as possible. Is this written down somewhere official that I can reference when this comes up in team discussions? …

Total answers: 1

mypy seems to think that (*args, **kwargs) could match to any funtion signature?

mypy seems to think that (*args, **kwargs) could match to any funtion signature? Question: How does mypy apply the Liskov substitution principle to *args, **kwargs parameters? I thought the following code should fail a mypy check since some calls to f allowed by the Base class are not allowed by C, but it actually passed. …

Total answers: 2

Dynamically Setting the Output Type of Python Function

Dynamically Setting the Output Type of Python Function Question: Okay, I have a set of dictionaries that contain a key/ID and a function. Said dictionaries are used as identifiers that point to a specific cache key and function to update said cache key’s associated data. from typing import TypedDict, List class CacheIdentifier(TypedDict): key: str func: …

Total answers: 1

Python define return type based on property type

Python define return type based on property type Question: I have three classes, one base class and two child classes with the following structure: class BaseLayout: def add_element(self: "BaseLayout", element: str) -> None: … class LayoutA(BaseLayout): def add_element(self: "BaseLayout", element: str, name: str) -> None: … class LayoutB(BaseLayout): def add_element(self: "BaseLayout", element: str, number: int) …

Total answers: 1

what kind of type hint for status code and message

what kind of type hint for status code and message Question: Which return value type to use in def create_or_update_gp(data: UpdateSchema) -> HERE: try: ….logic… return 200, {‘message’: ‘successfully updated’} except Exception as ex: return 400, {‘message’: ‘Update error’} I can write something like Tuple[str, dict] looks pretty general. Perhaps there is a special format …

Total answers: 1

How to correctly use typing for a sort key function

How to correctly use typing for a sort key function Question: For this sort key method: def srt(self,r:Optional[Colour])->Optional[int]: if not isinstance(r,Colour): return None return r.index used in a later method in the same class (NOT Colour): items=sorted(self.__dict__.values(),key=self.srt) results in this error from mypy: error: Argument "key" to "sorted" has incompatible type "Callable[[Optional[Colour]], Optional[int]]"; expected "Callable[[Any], …

Total answers: 1