Type checking vs runtime

After writing this, I finally understood @Alexander point in first comment: whatever you write in annotations, it does not affect runtime, and your code is executed in the same way (sorry, I missed that you're looking just not from type checking perspective). This is core principle of python typing, as opposed to strongly typed languages (which makes it wonderful IMO): you can always say "I don't need types here - save my time and mental health". Type annotations are used to help some third-party tools, like mypy (type checker maintained by python core team) and IDEs. IDEs can suggest you something based on this information, and mypy checks whether your code can work if your types match the reality.

Generic version

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None:
        self.items: list[T] = []

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

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

    def empty(self) -> bool:
        return not self.items

You can treat type variables like regular variables, but intended for "meta" usage and ignored (well, there are some runtime traces, but they exist primary for introspection purpose) on runtime. They are substituted once for every binding context (more about it - below), and can be defined only once per module scope.

The code above declares normal generic class with one type argument. Now you can say Stack[int] to refer to a stack of integers, which is great. Current definition allows either explicit typing or using implicit Any parametrization:

# Explicit type
int_stack: Stack[int] = Stack()
reveal_type(int_stack)  # N: revealed type is "__main__.Stack[builtins.int]
int_stack.push(1)  # ok
int_stack.push('foo')  # E: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int"  [arg-type]
reveal_type(int_stack.pop())  # N: revealed type is "builtins.int"
# No type results in mypy error, similar to `x = []`
any_stack = Stack()  # E: need type annotation for any_stack
# But if you ignore it, the type becomes `Stack[Any]`
reveal_type(any_stack)  # N: revealed type is "__main__.Stack[Any]
any_stack.push(1)  # ok
any_stack.push('foo')  # ok too
reveal_type(any_stack.pop())  # N: revealed type is "Any"

To make the intended usage easier, you can allow initialization from iterable (I'm not covering the fact that you should be using collections.deque instead of list and maybe instead of this Stack class, assuming it is just a toy collection):

from collections.abc import Iterable

class Stack(Generic[T]):
    def __init__(self, items: Iterable[T] | None) -> None:
        # Create an empty list with items of type T
        self.items: list[T] = list(items or [])
    ...

deduced_int_stack = Stack([1])
reveal_type(deduced_int_stack)  # N: revealed type is "__main__.Stack[builtins.int]"

To sum up, generic classes have some type variable bound to the class body. When you create an instance of such class, it can be parametrized with some type - it may be another type variable or some fixed type, like int or tuple[str, Callable[[], MyClass[bool]]]. Then all occurrences of T in its body (except for nested classes, which are perhaps out of "quick glance" explanation context) are replaced with this type (or Any, if it is not given and cannot be deduced). This type can be deduced iff at least one of __init__ or __new__ arguments has type referring to T (just T or, say, list[T]), and otherwise you have to specify it. Note that if you have T used in __init__ of non-generic class, it is not very cool, although currently not disallowed.

Now, if you use T in some methods of generic class, it refers to that replaced value and results in typecheck errors, if passed types are not compatible with expected.

You can play with this example here.

Working outside of generic context

However, not all usages of type variables are related to generic classes. Fortunately, you cannot declare generic function with possibility to declare generic arg on calling side (like function<T> fun(x: number): T and fun<string>(0)), but there is enough more stuff. Let's begin with simpler examples - pure functions:

T = TypeVar('T')

def func1() -> T:
    return 1
def func2(x: T) -> int:
    return 1
def func3(x: T) -> T:
    return x
def func4(x: T, y: T) -> int:
    return 1

First function is declared to return some value of unbound type T. It obviously makes no sense, and recent mypy versions even learned to mark it as error. Your function return depends only on arguments and external state - and type variable must be present there, right? You cannot also declare global variable of type T in module scope, because T is still unbound - and thus neither func1 args nor module-scoped variables can depend on T.

Second function is more interesting. It does not cause mypy error, although still makes not very much sense: we can bind some type to T, but what is the difference between this and func2_1(x: Any) -> int: ...? We can speculate that now T can be used as annotation in function body, which can help in some corner case with type variable having upper bound parameterizing an invariant class used covariantly (imagine needing a list[Parent] with .count() method and __getitem__, but still allowing list[Child] to be passed in and ignoring both Sequence existence and custom protocol option). Similar example is even explicitly referenced in PEP as valid.

The third and fourth functions are typical examples of type variables in functions. The third declares function returning the same type as it's argument.

The fourth function takes two arguments of the same type (arbitrary one). It is more useful if you have T = TypeVar('T', bound=Something) or T = TypeVar('T', str, bytes): you can concatenate two arguments of type T, but cannot - of type str | bytes, like in the below example:

T = TypeVar('T', str, bytes)

def total_length(x: T, y: T) -> int:
    return len(x + y)

The most important fact about all examples above in this section: T doesnot have to be the same for different functions. You can call func3(1), then func3(['bar']) and then func4('foo', 'bar'). T is int, list[str] and str in these calls - no need to match.

With this in mind your second solution is clear:

T = TypeVar('T')

class Stack:
    def __init__(self) -> None:
        # Create an empty list with items of type T
        self.items: list[T] = []  # E: Type variable "__main__.T" is unbound  [valid-type]

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

    def pop(self) -> T:  # E: A function returning TypeVar should receive at least one argument containing the same TypeVar  [type-var]
        return self.items.pop()

Here is mypy issue, discussing similar case.

__init__ says that we set attribute x to value of type T, but this T is lost later (T is scoped only within __init__) - so mypy rejects the assignment.

push is ill-formed and T has no meaning here, but it does not result in invalid typing situation, so is not rejected (type of argument is erased to Any, so you still can call push with some argument).

pop is invalid, because typechecker needs to know what my_stack.pop() will return. It could say "I give up - just have your Any", and will be perfectly valid (PEP does not enforce this). but mypy is more smart and denies invalid-by-design usage.

Edge case: you can return SomeGeneric[T] with unbound T, for example, in factory functions:

def make_list() -> list[T]: ...

mylist: list[str] = make_list()

because otherwise type argument couldn't have been specified on calling site

For better understanding of type variables and generics in python, I suggest you to read PEP483 and PEP484 - usually PEPs are more like a boring standard, but these are really good as a starting point.

There are many edge cases omitted there, which still cause hot discussions in mypy team (and probably other typecheckers too) - say, type variables in staticmethods of generic classes, or binding in classmethods used as constructors - mind that they can be used on instances too. However, basically you can:

  • have a TypeVar bound to class (Generic or Protocol, or some Generic subclass - if you subclass Iterable[T], your class is already generic in T) - then all methods use the same T and can contain it in one or both sides
  • or have a method-scoped/function-scoped type variable - then it's useful if repeated in the signature more than once (not necessary "clean" - it may be parametrizing another generic)
  • or use type variables in generic aliases (like LongTuple = tuple[T, T, T, T] - then you can do x: LongTuple[int] = (1, 2, 3, 4)
  • or do something more exotic with type variables, which is probably out of scope
Answer from STerliakov on Stack Overflow
🌐
Python
typing.python.org › en › latest › reference › generics.html
Generics — typing documentation
You may have seen type hints like list[str] or dict[str, int] in Python code. These types are interesting in that they are parametrised by other types! A list[str] isn’t just a list, it’s a list of strings. Types with type parameters like this are called generic types.
🌐
Medium
medium.com › @steveYeah › using-generics-in-python-99010e5056eb
Using Generics in Python. If you are using type hints in Python… | by SteveYeah | Medium
July 21, 2021 - Here we have added a generic type named T. We did this by using the TypeVar factory, giving the name of the type we want to create and then capturing that in a variable named T. This is then used the same way as any other type is used in Python type hints. T and U are commonly used names in generics (T standing for Type and U standing for….
Discussions

how to define python generic classes - Stack Overflow
Type annotations are used to help some third-party tools, like mypy (type checker maintained by python core team) and IDEs. IDEs can suggest you something based on this information, and mypy checks whether your code can work if your types match the reality. T = TypeVar('T') class Stack(Generic[T]): ... More on stackoverflow.com
🌐 stackoverflow.com
When to make classes & functions generic in python?
I don't understand the, idunno, premise of the question, I guess? Firstly, narrowing the type of a function parameter (or more generally, anything that's contravariant) is not allowed. This is a violation of Liskov: class Parent: def func(self, x: int): ... class Child(Parent): def func(self, x: bool): ... And secondly, your 2nd example doesn't typecheck. The way you're using the TypeVar makes no sense - it's neither bound to a generic class, nor does it appear in the function signature more than once. It's really unclear to me what problem you're trying to solve. More on reddit.com
🌐 r/learnpython
7
1
August 29, 2023
PEP 646 (Variadic Generics) has been accepted for Python 3.11
https://www.python.org/dev/peps/pep-0646/ for the lazy More on reddit.com
🌐 r/Python
35
209
January 22, 2022
Let's talk about python 3.12's new Type Parameter Syntax.
There was probably much discussion on this placement, and there is not point discussing it now because it won't change. If you want to learn more about this, I recommend reading PEP 695 and additionally the following: https://jellezijlstra.github.io/pep695 https://github.com/python/peps/pull/3122 More on reddit.com
🌐 r/Python
43
0
January 26, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-generics
Python Generics - GeeksforGeeks
October 29, 2025 - Python generics are type hints in Python that allow you to write functions and classes that can work with any data type.
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
3 weeks ago - Their intended purpose is to be building blocks for creating generic types and type aliases. These objects can be created through special syntax (type parameter lists and the type statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.
🌐
Mypy
mypy.readthedocs.io › en › stable › generics.html
Generics - mypy 1.19.1 documentation
Here is the same example using the old syntax (required for Python 3.11 and earlier, but also supported on newer Python versions): from typing import TypeVar, Generic T = TypeVar('T') # Define type variable "T" class Stack(Generic[T]): def __init__(self) -> None: # Create an empty list with items of type T self.items: list[T] = [] def push(self, item: T) -> None: self.items.append(item) def pop(self) -> T: return self.items.pop() def empty(self) -> bool: return not self.items
Top answer
1 of 1
5

Type checking vs runtime

After writing this, I finally understood @Alexander point in first comment: whatever you write in annotations, it does not affect runtime, and your code is executed in the same way (sorry, I missed that you're looking just not from type checking perspective). This is core principle of python typing, as opposed to strongly typed languages (which makes it wonderful IMO): you can always say "I don't need types here - save my time and mental health". Type annotations are used to help some third-party tools, like mypy (type checker maintained by python core team) and IDEs. IDEs can suggest you something based on this information, and mypy checks whether your code can work if your types match the reality.

Generic version

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None:
        self.items: list[T] = []

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

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

    def empty(self) -> bool:
        return not self.items

You can treat type variables like regular variables, but intended for "meta" usage and ignored (well, there are some runtime traces, but they exist primary for introspection purpose) on runtime. They are substituted once for every binding context (more about it - below), and can be defined only once per module scope.

The code above declares normal generic class with one type argument. Now you can say Stack[int] to refer to a stack of integers, which is great. Current definition allows either explicit typing or using implicit Any parametrization:

# Explicit type
int_stack: Stack[int] = Stack()
reveal_type(int_stack)  # N: revealed type is "__main__.Stack[builtins.int]
int_stack.push(1)  # ok
int_stack.push('foo')  # E: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int"  [arg-type]
reveal_type(int_stack.pop())  # N: revealed type is "builtins.int"
# No type results in mypy error, similar to `x = []`
any_stack = Stack()  # E: need type annotation for any_stack
# But if you ignore it, the type becomes `Stack[Any]`
reveal_type(any_stack)  # N: revealed type is "__main__.Stack[Any]
any_stack.push(1)  # ok
any_stack.push('foo')  # ok too
reveal_type(any_stack.pop())  # N: revealed type is "Any"

To make the intended usage easier, you can allow initialization from iterable (I'm not covering the fact that you should be using collections.deque instead of list and maybe instead of this Stack class, assuming it is just a toy collection):

from collections.abc import Iterable

class Stack(Generic[T]):
    def __init__(self, items: Iterable[T] | None) -> None:
        # Create an empty list with items of type T
        self.items: list[T] = list(items or [])
    ...

deduced_int_stack = Stack([1])
reveal_type(deduced_int_stack)  # N: revealed type is "__main__.Stack[builtins.int]"

To sum up, generic classes have some type variable bound to the class body. When you create an instance of such class, it can be parametrized with some type - it may be another type variable or some fixed type, like int or tuple[str, Callable[[], MyClass[bool]]]. Then all occurrences of T in its body (except for nested classes, which are perhaps out of "quick glance" explanation context) are replaced with this type (or Any, if it is not given and cannot be deduced). This type can be deduced iff at least one of __init__ or __new__ arguments has type referring to T (just T or, say, list[T]), and otherwise you have to specify it. Note that if you have T used in __init__ of non-generic class, it is not very cool, although currently not disallowed.

Now, if you use T in some methods of generic class, it refers to that replaced value and results in typecheck errors, if passed types are not compatible with expected.

You can play with this example here.

Working outside of generic context

However, not all usages of type variables are related to generic classes. Fortunately, you cannot declare generic function with possibility to declare generic arg on calling side (like function<T> fun(x: number): T and fun<string>(0)), but there is enough more stuff. Let's begin with simpler examples - pure functions:

T = TypeVar('T')

def func1() -> T:
    return 1
def func2(x: T) -> int:
    return 1
def func3(x: T) -> T:
    return x
def func4(x: T, y: T) -> int:
    return 1

First function is declared to return some value of unbound type T. It obviously makes no sense, and recent mypy versions even learned to mark it as error. Your function return depends only on arguments and external state - and type variable must be present there, right? You cannot also declare global variable of type T in module scope, because T is still unbound - and thus neither func1 args nor module-scoped variables can depend on T.

Second function is more interesting. It does not cause mypy error, although still makes not very much sense: we can bind some type to T, but what is the difference between this and func2_1(x: Any) -> int: ...? We can speculate that now T can be used as annotation in function body, which can help in some corner case with type variable having upper bound parameterizing an invariant class used covariantly (imagine needing a list[Parent] with .count() method and __getitem__, but still allowing list[Child] to be passed in and ignoring both Sequence existence and custom protocol option). Similar example is even explicitly referenced in PEP as valid.

The third and fourth functions are typical examples of type variables in functions. The third declares function returning the same type as it's argument.

The fourth function takes two arguments of the same type (arbitrary one). It is more useful if you have T = TypeVar('T', bound=Something) or T = TypeVar('T', str, bytes): you can concatenate two arguments of type T, but cannot - of type str | bytes, like in the below example:

T = TypeVar('T', str, bytes)

def total_length(x: T, y: T) -> int:
    return len(x + y)

The most important fact about all examples above in this section: T doesnot have to be the same for different functions. You can call func3(1), then func3(['bar']) and then func4('foo', 'bar'). T is int, list[str] and str in these calls - no need to match.

With this in mind your second solution is clear:

T = TypeVar('T')

class Stack:
    def __init__(self) -> None:
        # Create an empty list with items of type T
        self.items: list[T] = []  # E: Type variable "__main__.T" is unbound  [valid-type]

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

    def pop(self) -> T:  # E: A function returning TypeVar should receive at least one argument containing the same TypeVar  [type-var]
        return self.items.pop()

Here is mypy issue, discussing similar case.

__init__ says that we set attribute x to value of type T, but this T is lost later (T is scoped only within __init__) - so mypy rejects the assignment.

push is ill-formed and T has no meaning here, but it does not result in invalid typing situation, so is not rejected (type of argument is erased to Any, so you still can call push with some argument).

pop is invalid, because typechecker needs to know what my_stack.pop() will return. It could say "I give up - just have your Any", and will be perfectly valid (PEP does not enforce this). but mypy is more smart and denies invalid-by-design usage.

Edge case: you can return SomeGeneric[T] with unbound T, for example, in factory functions:

def make_list() -> list[T]: ...

mylist: list[str] = make_list()

because otherwise type argument couldn't have been specified on calling site

For better understanding of type variables and generics in python, I suggest you to read PEP483 and PEP484 - usually PEPs are more like a boring standard, but these are really good as a starting point.

There are many edge cases omitted there, which still cause hot discussions in mypy team (and probably other typecheckers too) - say, type variables in staticmethods of generic classes, or binding in classmethods used as constructors - mind that they can be used on instances too. However, basically you can:

  • have a TypeVar bound to class (Generic or Protocol, or some Generic subclass - if you subclass Iterable[T], your class is already generic in T) - then all methods use the same T and can contain it in one or both sides
  • or have a method-scoped/function-scoped type variable - then it's useful if repeated in the signature more than once (not necessary "clean" - it may be parametrizing another generic)
  • or use type variables in generic aliases (like LongTuple = tuple[T, T, T, T] - then you can do x: LongTuple[int] = (1, 2, 3, 4)
  • or do something more exotic with type variables, which is probably out of scope
🌐
ArjanCodes
arjancodes.com › blog › python-generics-syntax
Python 3.12 Generics: Cleaner, Easier Type-Hinting | ArjanCodes
June 6, 2024 - Issues frequently arose, such as metaclass conflicts when combining generic types with other types, leading to verbose and complex code. The new generics syntax in Python 3.12 simplifies this significantly, making type hints more intuitive and less verbose.
Find elsewhere
🌐
Python
peps.python.org › pep-0646
PEP 646 – Variadic Generics | peps.python.org
February 1, 2025 - PEP 484 introduced TypeVar, enabling creation of generics parameterised with a single type. In this PEP, we introduce TypeVarTuple, enabling parameterisation with an arbitrary number of types - that is, a variadic type variable, enabling variadic generi...
🌐
Real Python
realpython.com › ref › glossary › generic-type
generic type | Python Glossary – Real Python
In Python, a generic type is a type that you can parameterize with other types.
🌐
Tutorialspoint
tutorialspoint.com › python › python_generics.htm
Python - Generics
In Python, generics is a mechanism with which you to define functions, classes, or methods that can operate on multiple types while maintaining type safety. With the implementation of Generics enable it is possible to write reusable code that can be
🌐
YouTube
youtube.com › watch
Generics are VITAL in typed Python - YouTube
Generics are a slightly odd (at first) but incredibly useful part of Python's type system that allow you to create a single typed interface, then provide spe...
Published   September 2, 2024
🌐
YouTube
youtube.com › arjancodes
Python 3.12 Generics in a Nutshell - YouTube
👷 Review code better and faster with my 3-Factor Framework: https://arjan.codes/diagnosis.Generics in Python 3.12 can transform your code by allowing classe...
Published   April 2, 2024
Views   51K
🌐
Reddit
reddit.com › r/learnpython › when to make classes & functions generic in python?
r/learnpython on Reddit: When to make classes & functions generic in python?
August 29, 2023 -

I have been generally making my methods generic mostly for the following reasons:

  • I am subclassing an abstract class and want to override a method and narrow the type hinting in the arguments, which would otherwise violate the Liskov substitution principle

  • I am not subclassing/overriding, but would like return values, attributes, etc. of a class to be more narrow than the type hints it is currently bound to, since I may be using that class in many different places with different types.

In particular for the second case, I have realized that there are actually two approaches to tackle this:

  1. make the class generic and provide the type arguments for the instance type hints.

  2. do not make the class generic, but subclass simply for the purpose of updating the type hints

With projects I am working on, with "context" and "manager" classes, there can be many different attributes and methods with many different types (5+), hence, making the class generic on all of them is too verbose. If I do make a class generic, if any other attributes (containing instances of other classes) return those same generic types, I have to propagate the generic type down the entire chain when I am using composition instead of inheritance. This is something I would like to avoid. If I choose option 2, there would be an explosion of subclasses just to override the type hints.

When should I choose 1 or 2? Is there a better way to do this?

Option 1 example:

from typing import Self, TypeVar, Generic

BazT = TypeVar('BazT')

class Bar(Generic[BazT]):
    def method1(self: Self) -> BazT:
        ...

class Foo(Generic[BazT]):
    bar: Bar[BazT]
    
    def method1(self: Self, baz: BazT) -> None:
        ...
    
    def method2(self: Self) -> Bar[BazT]:
        ...

Option 2 example:

from typing import Self, Any, TypeVar

Baz = Any

class Bar:
    def method1(self: Self) -> Baz:
        ...

class Foo:
    bar: Bar
    
    def method1(self: Self, baz: Baz) -> None:
        ...
    
    def method2(self: Self) -> Bar:
        ...
        
BazNarrowed = TypeVar('BazNarrowed', bound=Baz) # (doesn't matter what this is just some more narrow type)

class BarSubclass(Bar):
    def method1(self: Self) -> BazNarrowed:
        ...

class FooSubclass(Foo):
    bar: BarSubclass
    
    def method1(self: Self, baz: BazNarrowed) -> None:
        ...
    
    def method2(self: Self) -> BarSubclass:
        ...
Top answer
1 of 3
2
I don't understand the, idunno, premise of the question, I guess? Firstly, narrowing the type of a function parameter (or more generally, anything that's contravariant) is not allowed. This is a violation of Liskov: class Parent: def func(self, x: int): ... class Child(Parent): def func(self, x: bool): ... And secondly, your 2nd example doesn't typecheck. The way you're using the TypeVar makes no sense - it's neither bound to a generic class, nor does it appear in the function signature more than once. It's really unclear to me what problem you're trying to solve.
2 of 3
1
Please roast me if I'm wrong on this, but this appears to be the exact situation for which TypeGuard in typing module was developed, as of Python 3.10. PEP-647 ~~~TypeGuard = typing.TypeGuard~~~ Special typing form used to annotate the return type of a user-defined type guard function. ``TypeGuard`` only accepts a single type argument. At runtime, functions marked this way should return a boolean. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static type checkers to determine a more precise type of an expression within a program's code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a "type guard". Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use ``TypeGuard[...]`` as its return type to alert static type checkers to this intention. Using ``-> TypeGuard`` tells the static type checker that for a given function: 1. The return value is a boolean. 2. If the return value is ``True``, the type of its argument is the type inside ``TypeGuard``. For example:: def is_str(val: Union[str, float]): # "isinstance" type guard if isinstance(val, str): # Type of ``val`` is narrowed to ``str`` ... else: # Else, type of ``val`` is narrowed to ``float``. ... Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower form of ``TypeA`` (it can even be a wider form) and this may lead to type-unsafe results. The main reason is to allow for things like narrowing ``List[object]`` to ``List[str]`` even though the latter is not a subtype of the former, since ``List`` is invariant. The responsibility of writing type-safe type guards is left to the user. ``TypeGuard`` also works with type variables. For more information, see PEP 647 (User-Defined Type Guards).
🌐
Gui Commits
guicommits.com › python-generic-type-function-class
Python Generic function and class types
March 1, 2024 - Python does have generics! Learn how to use typing TypeVar and Generic to reuse code with proper typing.
🌐
GitHub
github.com › python › typing › discussions › 1424
Reasons for not allowing generics in `ClassVar`? · python/typing · Discussion #1424
I believe the technical reason why this was not allowed is that different generic instantiations of the same class share a single runtime class object, which only has space for a single ClassVar of one type.
Author   python
🌐
Gaohongnan
gaohongnan.com › computer_science › type_theory › 04-generics.html
Generics and Type Variables — Omniverse
In the course Unit 20: Generics - CS2030S, it is written in Java, so there is only mention of generic methods. But in Python, we can also define generic functions where the function signature and return type (need not be both) are parameterized by type variables.
🌐
CodeSignal
codesignal.com › learn › courses › advanced-functional-programming-techniques-2 › lessons › python-generics
Python Generics | CodeSignal Learn
For example, a list can hold integers, strings, or objects. Wouldn't it be nice to write code that works with any type, just like a list? Generics help us achieve this. Python's typing module provides tools for generics, like TypeVar, which lets us define a variable type.
🌐
YouTube
youtube.com › watch
python Generics (intermediate) anthony explains #430 - YouTube
today we introduce another typing / mypy concept: generics! I show a few examples of how to write generic functions and generic classes- intro to typing: ht...
Published   May 16, 2022
🌐
LabEx
labex.io › tutorials › python-how-to-leverage-generics-in-python-type-hints-398035
How to leverage generics in Python type hints | LabEx
Instantiate the Generic Type: When you use the generic type, you need to specify the actual type that you want to use. For example: numbers: list[int] = [1, 2, 3] first_number = get_first(numbers) In this example, the get_first function is called with a list of integers, and the type variable T is automatically inferred to be int. Python's type system also supports more advanced generic concepts, such as:
🌐
Medium
medium.com › @r_bilan › generics-in-python-3-12-whats-new-in-the-syntax-and-how-to-use-it-now-1024fcdf02f8
Generics in Python 3.12: What’s New in the Syntax and How to Use It Now | by Rostyslav Bilan | Medium
October 2, 2024 - There’s no longer a need to import Generic and TypeVar, and we can directly use generics in classes and methods, making the process of working with generics significantly easier. Previously, you had to use TypeAlias from the typing module to declare a type alias: from typing import TypeAlias, TypeVar _T = TypeVar("_T") ListOrSet: TypeAlias = list[_T] | set[_T] But now, with the new syntax in Python 3.12, it can be written as: