Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created April 19, 2022 00:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/b774878a3f650626c4d54d2df5a38930 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/b774878a3f650626c4d54d2df5a38930 to your computer and use it in GitHub Desktop.
Allows one to obtain all concrete generic type arguments for any Python type.
from typing import List, Sequence, get_args
def get_args_all(t: type) -> List[type]:
all_args: List[type] = []
all_args.extend(get_args(t))
try:
orig_bases = t.__orig_bases__
except AttributeError:
pass
else:
for x in orig_bases:
all_args.extend(get_args_all(x))
return all_args
@malcolmgreaves
Copy link
Author

malcolmgreaves commented Apr 19, 2022

from typing import TypeVar, Generic, get_args

from get_args_improved import get_args_all


A = TypeVar('A')
B = TypeVar('B')


class F(Generic[A,B]):
  pass

print(f"{get_args(F)=}")      # ()
print(f{"get_args_all(F)=}")  # [~A, ~B]

print(f"{get_args(F[float,float])=}")      # (float, float)
print(f"{get_args_all(F[float,float])=}")  # [float, float]


class D(F[int,str]):
  pass

print(f"{get_args(D)=}")      # ()
print(f{"get_args_all(D)=}")  # [int, str]

print(f"{get_args(D())=}")      # ()
print(f{"get_args_all(D())=}")  # [int, str]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment