← Back to index

specialtypes_any.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the typing.Any special type.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any
6
7# > Every type is consistent with Any.
8
9from typing import Any, Callable, assert_type
12val1: Any
13val1 = "" # OK
14val1 = 1 # OK
16val2: list[Any]
17val2 = [""] # OK
18val2 = [1] # OK
21def func1(val1: Any, val2: list[Any]) -> int:
22 t1: int = val1 # OK
23 t2: str = val1 # OK
25 t3: list[str] = val2 # OK
26 t4: list[int] = val2 # OK
28 return val1 # OK
31# > A function parameter without an annotation is assumed to be annotated with Any.
34def func2(val):
35 assert_type(val, Any)
37 t1: int = val # OK
38 t2: str = val # OK
40 return 1 # OK
43# > If a generic type is used without specifying type parameters, they are
44# > assumed to be Any.
47def func3(val1: list, val2: dict) -> None:
48 assert_type(val1, list[Any])
49 assert_type(val2, dict[Any, Any])
51 t1: list[str] = val1 # OK
52 t2: list[int] = val1 # OK
54 t3: dict[str, str] = val2 # OK
57# > This rule also applies to tuple, in annotation context it is equivalent
58# > to tuple[Any, ...].
61def func4(val1: tuple) -> None:
62 assert_type(val1, tuple[Any, ...])
64 t1: tuple[str, ...] = val1 # OK
65 t2: tuple[int, ...] = val1 # OK
68# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].
71def func5(val1: Callable):
72 assert_type(val1, Callable[..., Any])
74 t1: Callable[[], Any] = val1 # OK
75 t2: Callable[[int, str], None] = val1 # OK
78# > Any can also be used as a base class. This can be useful for avoiding type
79# > checker errors with classes that can duck type anywhere or are highly dynamic.
81class ClassA(Any):
82 def method1(self) -> int:
83 return 1
85a = ClassA()
86assert_type(a.method1(), int)
87assert_type(a.method2(), Any)
88assert_type(ClassA.method3(), Any)