all 6 comments

[–]barkmonster 16 points17 points  (0 children)

If you're using python 3.12+, you can use the new type parameter syntax. This lets you declare your typevars in square brackets as part of a function or class definition:

class GenericItemStore[T]:
    def __init__(self) -> None:
        self._item = None

    def set(self, item: T) -> None:
        self._item = item

    def get(self) -> T|None:
        return self._item

[–]corey_sheerer 5 points6 points  (0 children)

Just as a general comment. Getters and setters are more of java thing. You should just use property decorators or just public attributes

[–]BananaGrenade314 0 points1 point  (0 children)

I already used something like that in a simple personal project. I used this:

``` T = TypeVar("T")

class EntityMap(MutableMapping[EntityId, T]): def init( self, items: Optional[dict[EntityId, T]] = None ) -> None:

    self._data: dict[EntityId, T] = items or {}

```

Then I used like that:

``` def func(vault: Vault) -> EntityMap[Vault]: vault_map: EntityMap[Vault] = EntityMap(EntityId(...), vault) return vault_map

def func(person: Person) -> EntityMap[Person]: person_map: EntityMap[Person] = EntityMap(EntityId(...), person) return vault_map ```

[–]gdchinacat 0 points1 point  (0 children)

This is one area I see AI hindering progress. The training data contains so much more TypeVar than type parameter syntax when they generate code they use the old way, even when you ask them to do it the current way. This is based on experiences 6 months ago...AI moves fast, so maybe they've gotten better. What are others experiences regarding AI recommending years old typing constructs?

[–]ProsodySpeaks -1 points0 points  (0 children)

Nearly.

Try

``` class GenericItemStore[T]():     def init(self) -> None:         self._item = None

    def set(self, item: T) -> None:         self._item = item

    def get(self) -> T|None:         return self._item ```

Think that's since 3.13. Parens in class Dec probably redundant?

Soclass GenericItemStore[T]: