Sobes.tech
Junior — Middle

Применяешь ли ты Generic из модуля typing для объявления обобщенных типов в Python?

sobes.tech AI

Answer from AI

Yes, in Python, the class Generic from the typing module is often used to declare generic types. This allows creating custom generic classes and functions with type parameters, which improves code readability and maintainability, especially with static typing.

Example of using Generic:

from typing import TypeVar, Generic, List

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self):
        self._items: List[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

stack_int = Stack[int]()
stack_int.push(1)
value = stack_int.pop()  # value will be of type int

Thus, Generic helps create type-safe data structures and functions parameterized by types.

Применяешь ли ты Generic из модуля typing для… - sobes.tech