Category : python-typing

I am looking for the correct type to annotate this code def process_item(item: MyItemType) -> str: return f"Hello {item[‘name’]} {item[‘age’]} old" i.e item is any object with __getitem__() and must have name and age keys. import typing class MyItemType(typing.Protocol): name: str age: int def __getitem__(self, key: ???)->???: … In practice it would mean valid inputs ..

Read more

I’ve created BaseRepository class from which I inherit in my specific repositories. When invoking an update method of the RecipeRepository I get some strange warning. Warning: Expected type ‘Recipe’ (matched generic type ‘T’), got ‘Recipe’ instead What am I doing wrong? Setup: BaseRepository: from typing import TypeVar, Generic, Type from tortoise import Model T = ..

Read more

There is a typical pattern for data conversion in our code: when the value is None, we let it pass through. E.g., def capitalize(value): if value is None: return None return value.capitalize() # usage example: assert capitalize(None) is None assert capitalize("hello world") == "Hello world" I can annotate it like this: from typing import Optional ..

Read more

The ORM I’m using is TortoiseORM. Let’s assume following scenario I’ve created an entity that inherits from tortoise.Model like so: from tortoise import Model class MyModel(Model): … Then I’ve created BaseRepository that I will use as a base class for all repositories: class BaseRepository: def __init__(self, model: Model): self._model = Model async def get(self, *args, ..

Read more

I’m trying to refactor some classes using SOLID principles in python, and I have a question about how to mix SOLID with python typing. Suppose I have these classes: from asyncpg import Pool class PGQuery: async def execute(self, connection: Pool): raise NotImplementedError class PGQueryExecutor: def __init__(self, connection: Pool): self._connection = connection async def execute(self, query: ..

Read more

I’m trying to match type annotations like int | str, and use regex substitution to replace them with a string Union[int, str]. Desired substitutions (before and after): str|int|bool -> Union[str,int,bool] Optional[int|str] -> Optional[Union[int,str]] dict[str | int, list[B | C | Optional[D]]] -> dict[Union[str,int], list[Union[B,C,Optional[D]]]] I’ve put together a Regex below on what i’ve attempted so ..

Read more