Skip to content

Instantly share code, notes, and snippets.

@2tony2
Created May 22, 2024 06:57
Show Gist options
  • Select an option

  • Save 2tony2/b90c6e030c00ccfafdb69d83ba68859e to your computer and use it in GitHub Desktop.

Select an option

Save 2tony2/b90c6e030c00ccfafdb69d83ba68859e to your computer and use it in GitHub Desktop.
from typing import get_origin, get_args
# Define some generic and non-generic types
generic_type = list[int]
non_generic_type = int
generic_type_without_params = list
# Function to check if a type is a generic type
def is_generic_type(tp):
return get_origin(tp) is not None or hasattr(tp, '__origin__') and tp.__origin__ is not None
# Function to check if a type is a parameterized generic type
def is_parameterized_generic_type(tp):
return get_origin(tp) is not None and len(get_args(tp)) > 0
if __name__ == "__main__":
print(f'Is {generic_type} a generic type? {is_generic_type(generic_type)}') # True
print(f'Is {non_generic_type} a generic type? {is_generic_type(non_generic_type)}') # False
print(f'Is {generic_type_without_params} a generic type? {is_generic_type(generic_type_without_params)}') # True
print(f'Is {generic_type} a parameterized generic type? {is_parameterized_generic_type(generic_type)}') # True
print(f'Is {generic_type_without_params} a parameterized generic type? {is_parameterized_generic_type(generic_type_without_params)}') # False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment