How to create a generic method in Python

3 Answers

0 votes
# Python is dynamically typed, so generics don’t change runtime behavior. 
# Instead, they improve clarity, correctness, and tooling.

# Generic methods make your code safer, clearer, and easier to maintain 
# especially in large projects.

from typing import TypeVar, Generic

# A generic method uses a TypeVar to represent an unknown type.

# Define a type variable
T = TypeVar('T')

# Generic method
def print_value(value: T) -> None:
    print(value)

# Generic class (optional, for demonstration)
class Box(Generic[T]):
    def __init__(self, value: T):
        self.value = value

    def show(self) -> None:
        print(self.value)

def main():
    # Using the generic method
    print_value(123)
    print_value("Python Generics")
    print_value(3.14)
    print_value(True)

    # Using the generic class
    b1 = Box(10)
    b2 = Box("Hello")
    b3 = Box(2.718)

    b1.show()
    b2.show()
    b3.show()

if __name__ == "__main__":
    main()
    
    
'''
run:

123
Python Generics
3.14
True
10
Hello
2.718

'''

 



answered 4 hours ago by avibootz
edited 2 hours ago by avibootz
0 votes
from typing import TypeVar, Generic

# Generic Method With Two Type Parameters

from typing import TypeVar

K = TypeVar('K')
V = TypeVar('V')

def print_pair(key: K, value: V) -> None:
    print(f"{key} = {value}")

print_pair("Age", 50)
print_pair(101, "Employee ID")
print_pair("Pi", 3.14159)


    
'''
run:

Age = 50
101 = Employee ID
Pi = 3.14159

'''

 



answered 4 hours ago by avibootz
0 votes
from typing import TypeVar, Generic

# Generic Swap Method in Python

from typing import TypeVar, List

T = TypeVar('T')

# Generic swap function
def swap(arr: List[T], i: int, j: int) -> None:
    arr[i], arr[j] = arr[j], arr[i]

# Helper function to print lists
def print_list(label: str, arr: List[T]) -> None:
    print(f"{label}: {arr}")

def main():
    # Integer list
    nums = [10, 20, 30, 40]
    print_list("Before swap (int)", nums)
    swap(nums, 1, 3)
    print_list("After swap  (int)", nums)
    print()

    # String list
    words = ["Python", "Java", "C#", "Go"]
    print_list("Before swap (str)", words)
    swap(words, 0, 2)
    print_list("After swap  (str)", words)
    print()

    # Float list
    floats = [1.1, 2.2, 3.3, 4.4]
    print_list("Before swap (float)", floats)
    swap(floats, 2, 3)
    print_list("After swap  (float)", floats)

if __name__ == "__main__":
    main()


    
'''
run:

Before swap (int): [10, 20, 30, 40]
After swap  (int): [10, 40, 30, 20]

Before swap (str): ['Python', 'Java', 'C#', 'Go']
After swap  (str): ['C#', 'Java', 'Python', 'Go']

Before swap (float): [1.1, 2.2, 3.3, 4.4]
After swap  (float): [1.1, 2.2, 4.4, 3.3]

'''

 



answered 4 hours ago by avibootz
...