get_origin Unwraps Generic Aliases

get_origin and get_args split generic aliases at runtime: list[int] yields list and int, unions expose their members, plain types expose nothing.

PythonForm Validation

Code

pythonsnippet
28 lines
from typing import get_args, get_origin

hints = {
    'ids': list[int],
    'scores': dict[str, float],
    'label': str | None,
    'payload': tuple[str, int],
    'blob': bytes,
}

# 泛型别名拆成 (origin, args);普通类型 origin 为 None、args 为空
for name, hint in hints.items():
    print(f'{name:>8}:', get_origin(hint), get_args(hint))

# Union 拆出全部成员,NoneType 就是"可空"
print('union:', get_origin(str | None), get_args(str | None))


# 运行时校验单参数容器:容器类型与元素类型都对上才算通过
def matches_list(value, hint) -> bool:
    if get_origin(hint) is not list or not isinstance(value, list):
        return False
    return all(isinstance(item, get_args(hint)[0]) for item in value)


print(matches_list([1, 2, 3], list[int]))
print(matches_list([1, 'x'], list[int]))
print(matches_list((1, 2), list[int]))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ids: <class 'list'> (<class 'int'>,)
  scores: <class 'dict'> (<class 'str'>, <class 'float'>)
   label: <class 'types.UnionType'> (<class 'str'>, <class 'NoneType'>)
 payload: <class 'tuple'> (<class 'str'>, <class 'int'>)
    blob: None ()
union: <class 'types.UnionType'> (<class 'str'>, <class 'NoneType'>)
True
False
False

get_origin Unwraps Generic Aliases: what runs and why

The code’s whole job belongs to the function matches_list.

The loop for name, hint in hints.items() is the only repeated construct.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Signature: def matches_list(value, hint) -> bool

union: — these output prefixes each name the step behind their line.

matches_list is the public entry point; everything else in the file exists to support it.

Core lines

def matches_list(value, hint) -> bool:
    if get_origin(hint) is not list or not isinstance(value, list):
        return False
    return all(isinstance(item, get_args(hint)[0]) for item in value)

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `matches_list` at load time.