Sobes.tech
Junior — Middle

Can you explain what is meant by using generics in programming?

sobes.tech AI

Answer from AI

Generics (parametric types) are a mechanism that allows writing functions, classes, or methods that work with different data types while maintaining type safety and code readability.

In Python, generics are implemented in the typing module. For example, you can specify that a function accepts a list of elements of any type, but all elements are of the same type:

from typing import TypeVar, List

T = TypeVar('T')

def first_element(lst: List[T]) -> T:
    return lst[0]

print(first_element([1, 2, 3]))  # returns int
print(first_element(['a', 'b']))  # returns str

Thus, generics help create more versatile and safe code that can work with different data types without losing type information.