---
title: "Discussion on \"Generic Typing in Python\" | Hashnode"
description: "Discussion on \"Generic Typing in Python\". Since Python introduced the ability to add generic types to functions, the language has become much more type-friendly and encourages you to follow this convention for more maintainable code. Obviously, this will lead to a better development experien..."
url: "https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [Generic Typing in Python](https://blog.imsadra.dev/generic-typing-in-python?utm_source=hashnode&utm_medium=feed)

Since Python introduced the ability to add generic types to functions, the language has become much more type-friendly and encourages you to follow this convention for more maintainable code. Obviously, this will lead to a better development experien...

Nov 3, 2024 · 5 min read · blog.imsadra.dev  
Read the article

-   [#python-generics](https://hashnode.com/tag/python-generics)
-   [#type-generics](https://hashnode.com/tag/type-generics)
-   [#python-typing](https://hashnode.com/tag/python-typing)
-   [#python](https://hashnode.com/tag/python)
-   [#python3](https://hashnode.com/tag/python3)
-   [#python-beginner](https://hashnode.com/tag/python-beginner)
-   [#typing](https://hashnode.com/tag/typing)
-   [#types](https://hashnode.com/tag/types)
-   [#generics](https://hashnode.com/tag/generics)
-   [#typescript-generics](https://hashnode.com/tag/typescript-generics)
-   [#pydantic](https://hashnode.com/tag/pydantic)
-   [#mypy](https://hashnode.com/tag/mypy)
-   [#type-checking](https://hashnode.com/tag/type-checking)

## Written by

[Sadra Yahyapour](https://hashnode.com/@lnxpy)

@lnxpy

  
[View profile](https://hashnode.com/@lnxpy)

Campus Expert at GitHub · Open-Source Contributor · Python Developer · ML Enthusiast

A passionate software developer who enjoys sharing his thoughts with others and learning from them vise versa!

## Responses 3

Markdown supported · ⌘↵ to post

[Edith Pixie](https://hashnode.com/@edithpixie)

[Dec 6, 2024](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/67524cb3e07570a8b8aefadd)

For many people and businesses, navigating the frequently dangerous landscape of financial loss can be an intimidating and overwhelming process. Nevertheless, the knowledgeable staff at Wizard Hilton Cyber Tech provides a ray of hope and direction with their indispensable range of services. Their offerings are based on a profound grasp of the far-reaching and terrible effects that financial setbacks, whether they be the result of cyberattacks, data breaches, or other unforeseen tragedies, can have. Their highly-trained analysts work tirelessly to assess the scope of the damage, identifying the root causes and developing tailored strategies to mitigate the fallout. From recovering lost or corrupted data to restoring compromised systems and securing networks, Wizard Hilton Cyber Tech employs the latest cutting-edge technologies and industry best practices to help clients regain their financial footing. But their support goes beyond the technical realm, as their compassionate case managers provide a empathetic ear and practical advice to navigate the emotional and logistical challenges that often accompany financial upheaval. With a steadfast commitment to client success, Wizard Hilton Cyber Tech is a trusted partner in weathering the storm of financial loss, offering the essential services and peace of mind needed to emerge stronger and more resilient than before. Call; Email : wizardhiltoncybertech ( @ ) gmail (. ) com  
OR support ( @ ) wizardhiltoncybertech (.) com

WhatsApp number +13024457895

[jun hu](https://hashnode.com/@hujunjun)

[Nov 6, 2024](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/672ae1749328b9fbb09c1a92)

关于通用类型的精彩文章，以简单且用户友好的格式呈现。感谢 Sadra 准备这篇文章

[Sadra Yahyapour](https://hashnode.com/@lnxpy)

[May 5](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/672ae1749328b9fbb09c1a92#reply-69f9f780a386d7f12196af32)

Thank you, Jun. Glad you liked it!

[Saeed Ramezani](https://hashnode.com/@saeedrz75)

[Nov 5, 2024](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/672a1f643f27c616bf167902)

Useful article about generic typing. Thanks for that.

[Sadra Yahyapour](https://hashnode.com/@lnxpy)

[Nov 5, 2024](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/672a1f643f27c616bf167902#reply-672a23c834c11475dda51523)

:D

[NancyChaput](https://hashnode.com/@michellefisher241)

[Nov 5, 2024](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/67298bc5d251c2d711610cfa)

**Generic Typing in Python**

Generic typing in Python allows developers to create more flexible and reusable code by defining types that work with multiple data types. This is especially useful for functions and classes that need to handle a variety of types but still enforce type safety. Here are the main elements of generic typing:

1.  **Type Variables** (`TypeVar`):  
    A `TypeVar` allows you to define a generic type variable that can be used to create functions or classes that work with multiple types. For example:
    
    ```
    from typing import TypeVar, List
    
    T = TypeVar('T')  # Generic type variable
    
    def get_first_element(lst: List[T]) -> T:
        return lst[0]
    ```
    
    Here, `T` can be any type, and `get_first_element` can be used with lists of any type.
    
2.  **Generic Classes**: You can create classes that operate on multiple types by using `TypeVar` within the class definition. For example:
    
    ```
    from typing import Generic
    
    T = TypeVar('T')
    
    class Stack(Generic[T]):
        def __init__(self):
            self.items: List[T] = []
    
        def push(self, item: T):
            self.items.append(item)
    
        def pop(self) -> T:
            return self.items.pop()
    ```
    
    This `Stack` class can hold elements of any type, and the type is enforced by `TypeVar`.
    
3.  **Union and Optional**: When a function can accept more than one type, `Union` can be used to specify multiple allowed types, while `Optional` is shorthand for `Union[type, None]`. For example:
    
    ```
    from typing import Union, Optional
    
    def display(value: Union[int, str]):
        print(value)
    
    def get_username(user_id: int) -> Optional[str]:
        # returns a string or None
        return None  # or some string based on logic
    ```
    
4.  **Parameterized Collections**: Generic types can also be used with built-in collections like `List`, `Dict`, and `Tuple`. For example:
    
    ```
    from typing import List, Dict
    
    def process_items(items: List[str]):
        # List containing only strings
        for item in items:
            print(item.upper())
    ```
    

Using generics improves code readability and reliability by ensuring types are consistent and well-defined. This is particularly valuable in large codebases and projects where type safety helps avoid errors freddys-menu.com

[Danyal T](https://hashnode.com/@danytgh)

[Nov 4, 2024](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/67287bf3bed56a15509e309b)

Great article on generic typing, presented in a simple and user-friendly format. Thank you, Sadra, for preparing this!

[Sadra Yahyapour](https://hashnode.com/@lnxpy)

[Nov 4, 2024](https://hashnode.com/posts/generic-typing-in-python/6727e668a990fe8761ce3e80/comment/67287bf3bed56a15509e309b#reply-67287d6e5a1b86f01bfae6b8)

You're welcome. Glad you found it useful. 😃
