Debian Codegraph @

test-data/unit/check-newtype.test

raw
1 -- Checks NewType(...)
2
3 -- Checks for basic functionality
4
5 [case testNewTypePEP484Example1]
6 from typing import NewType
7
8 UserId = NewType('UserId', int)
9
10 def name_by_id(user_id: UserId) -> str:
11 return "foo"
12
13 UserId('user') # E: Argument 1 to "UserId" has incompatible type "str"; expected "int"
14 name_by_id(42) # E: Argument 1 to "name_by_id" has incompatible type "int"; expected "UserId"
15 name_by_id(UserId(42))
16
17 id = UserId(5)
18 num = id + 1
19
20 reveal_type(id) # N: Revealed type is "__main__.UserId"
21 reveal_type(num) # N: Revealed type is "builtins.int"
22
23 [targets __main__, __main__.UserId.__init__, __main__.name_by_id]
24
25 [case testNewTypePEP484Example2]
26 from typing import NewType
27
28 class PacketId:
29 def __init__(self, major: int, minor: int) -> None:
30 self._major = major
31 self._minor = minor
32
33 TcpPacketId = NewType('TcpPacketId', PacketId)
34
35 packet = PacketId(100, 100)
36 tcp_packet = TcpPacketId(packet)
37 tcp_packet = TcpPacketId(127, 0)
38
39 [out]
40 main:12: error: Too many arguments for "TcpPacketId"
41 main:12: error: Argument 1 to "TcpPacketId" has incompatible type "int"; expected "PacketId"
42
43 [case testNewTypeWithTuples]
44 from typing import NewType, Tuple
45 TwoTuple = NewType('TwoTuple', Tuple[int, str])
46 a = TwoTuple((3, "a"))
47 b = TwoTuple(("a", 3)) # E: Argument 1 to "TwoTuple" has incompatible type "tuple[str, int]"; expected "tuple[int, str]"
48
49 reveal_type(a[0]) # N: Revealed type is "builtins.int"
50 reveal_type(a[1]) # N: Revealed type is "builtins.str"
51 [builtins fixtures/tuple.pyi]
52 [out]
53
54 [case testNewTypeWithLists]
55 from typing import NewType, List
56 UserId = NewType('UserId', int)
57 IdList = NewType('IdList', List[UserId])
58
59 bad1 = IdList([1]) # E: List item 0 has incompatible type "int"; expected "UserId"
60
61 foo = IdList([])
62 foo.append(3) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "UserId"
63 foo.append(UserId(3))
64 foo.extend([UserId(1), UserId(2), UserId(3)])
65 foo.extend(IdList([UserId(1), UserId(2), UserId(3)]))
66 bar = IdList([UserId(2)])
67
68 baz = foo + bar
69 reveal_type(foo) # N: Revealed type is "__main__.IdList"
70 reveal_type(bar) # N: Revealed type is "__main__.IdList"
71 reveal_type(baz) # N: Revealed type is "builtins.list[__main__.UserId]"
72
73 [builtins fixtures/list.pyi]
74 [out]
75
76 [case testNewTypeWithGenerics]
77 from typing import TypeVar, Generic, NewType, Any
78
79 T = TypeVar('T')
80
81 class Base(Generic[T]):
82 def __init__(self, item: T) -> None:
83 self.item = item
84
85 def getter(self) -> T:
86 return self.item
87
88 Derived1 = NewType('Derived1', Base[str])
89 Derived2 = NewType('Derived2', Base) # Implicit 'Any'
90 Derived3 = NewType('Derived3', Base[Any]) # Explicit 'Any'
91
92 Derived1(Base(1)) # E: Argument 1 to "Base" has incompatible type "int"; expected "str"
93 Derived1(Base('a'))
94 Derived2(Base(1))
95 Derived2(Base('a'))
96 Derived3(Base(1))
97 Derived3(Base('a'))
98
99 reveal_type(Derived1(Base('a')).getter()) # N: Revealed type is "builtins.str"
100 reveal_type(Derived3(Base('a')).getter()) # N: Revealed type is "Any"
101 [out]
102
103 [case testNewTypeWithNamedTuple]
104 from collections import namedtuple
105 from typing import NewType, NamedTuple
106
107 Vector1 = namedtuple('Vector1', ['x', 'y'])
108 Point1 = NewType('Point1', Vector1)
109 p1 = Point1(Vector1(1, 2))
110 reveal_type(p1.x) # N: Revealed type is "Any"
111 reveal_type(p1.y) # N: Revealed type is "Any"
112
113 Vector2 = NamedTuple('Vector2', [('x', int), ('y', int)])
114 Point2 = NewType('Point2', Vector2)
115 p2 = Point2(Vector2(1, 2))
116 reveal_type(p2.x) # N: Revealed type is "builtins.int"
117 reveal_type(p2.y) # N: Revealed type is "builtins.int"
118
119 class Vector3:
120 def __init__(self, x: int, y: int) -> None:
121 self.x = x
122 self.y = y
123 Point3 = NewType('Point3', Vector3)
124 p3 = Point3(Vector3(1, 3))
125 reveal_type(p3.x) # N: Revealed type is "builtins.int"
126 reveal_type(p3.y) # N: Revealed type is "builtins.int"
127
128 [builtins fixtures/list.pyi]
129
130 [out]
131
132 [case testNewTypeWithCasts]
133 from typing import NewType, cast
134 UserId = NewType('UserId', int)
135 foo = UserId(3)
136 foo = cast(UserId, 3)
137 foo = cast(UserId, "foo")
138 foo = cast(UserId, UserId(4))
139 [out]
140
141 [case testNewTypeWithTypeAliases]
142 from typing import NewType
143 Foo = int
144 Bar = NewType('Bar', Foo)
145 Bar2 = Bar
146
147 def func1(x: Foo) -> Bar:
148 return Bar(x)
149
150 def func2(x: int) -> Bar:
151 return Bar(x)
152
153 def func3(x: Bar2) -> Bar:
154 return x
155
156 x = Bar(42)
157 y = Bar2(42)
158
159 y = func3(x)
160 [out]
161
162 [case testNewTypeWithNewType]
163 from typing import NewType
164 A = NewType('A', int)
165 B = NewType('B', A)
166 C = A
167 D = C
168 E = NewType('E', D)
169
170 a = A(1)
171 b = B(a)
172 e = E(a)
173
174 def funca(a: A) -> None: ...
175 def funcb(b: B) -> None: ...
176
177 funca(a)
178 funca(b)
179 funca(e)
180 funcb(a) # E: Argument 1 to "funcb" has incompatible type "A"; expected "B"
181 funcb(b)
182 funcb(e) # E: Argument 1 to "funcb" has incompatible type "E"; expected "B"
183
184 [out]
185
186 -- Make sure NewType works as expected in a variety of different scopes/across files
187
188 [case testNewTypeInLocalScope]
189 from typing import NewType
190 A = NewType('A', int)
191 a = A(3)
192
193 def func() -> None:
194 A = NewType('A', str)
195 B = NewType('B', str)
196
197 a = A(3) # E: Argument 1 to "A" has incompatible type "int"; expected "str"
198 a = A('xyz')
199 b = B('xyz')
200
201 class MyClass:
202 C = NewType('C', float)
203
204 def foo(self) -> 'MyClass.C':
205 return MyClass.C(3.2)
206
207 b = A(3)
208 c = MyClass.C(3.5)
209
210 [case testNewTypeInMultipleFiles]
211 import a
212 import b
213 list1 = [a.UserId(1), a.UserId(2)]
214 list1.append(b.UserId(3)) # E: Argument 1 to "append" of "list" has incompatible type "b.UserId"; expected "a.UserId"
215
216 [file a.py]
217 from typing import NewType
218 UserId = NewType('UserId', int)
219
220 [file b.py]
221 from typing import NewType
222 UserId = NewType('UserId', int)
223
224 [builtins fixtures/list.pyi]
225 [out]
226
227 [case testNewTypeWithIncremental]
228 import m
229
230 [file m.py]
231 from typing import NewType
232
233 UserId = NewType('UserId', int)
234
235 def name_by_id(user_id: UserId) -> str:
236 return "foo"
237
238 name_by_id(UserId(42))
239
240 id = UserId(5)
241 num = id + 1
242
243 [file m.py.2]
244 from typing import NewType
245
246 UserId = NewType('UserId', int)
247
248 def name_by_id(user_id: UserId) -> str:
249 return "foo"
250
251 name_by_id(UserId(42))
252
253 id = UserId(5)
254 num = id + 1
255
256 reveal_type(id)
257 reveal_type(num)
258 [rechecked m]
259 [stale]
260 [out1]
261 [out2]
262 tmp/m.py:13: note: Revealed type is "m.UserId"
263 tmp/m.py:14: note: Revealed type is "builtins.int"
264
265
266 -- Check misuses of NewType fail
267
268 [case testNewTypeBadInitializationFails]
269 from typing import NewType
270
271 a = NewType('b', int) # E: String argument 1 "b" to NewType(...) does not match variable name "a"
272 b = NewType('b', 3) # E: Argument 2 to NewType(...) must be a valid type
273 c = NewType(2, int) # E: Argument 1 to NewType(...) must be a string literal
274 d = NewType(b'f', int) # E: Argument 1 to NewType(...) must be a string literal
275 foo = "d"
276 e = NewType(foo, int) # E: Argument 1 to NewType(...) must be a string literal
277 f = NewType(name='e', tp=int) # E: NewType(...) expects exactly two positional arguments
278 g = NewType('f', tp=int) # E: NewType(...) expects exactly two positional arguments
279 [out]
280
281 [case testNewTypeWithAnyFails]
282 from typing import NewType, Any
283 A = NewType('A', Any) # E: Argument 2 to NewType(...) must be subclassable (got "Any")
284 [out]
285
286 [case testNewTypeWithUnionsFails]
287 from typing import NewType, Union
288 Foo = NewType('Foo', Union[int, float]) # E: Argument 2 to NewType(...) must be subclassable (got "int | float")
289 [out]
290
291 [case testNewTypeWithTypeTypeFails]
292 from typing import NewType, Type
293 Foo = NewType('Foo', Type[int]) # E: Argument 2 to NewType(...) must be subclassable (got "type[int]")
294 a = Foo(type(3))
295 [builtins fixtures/args.pyi]
296 [out]
297
298 [case testNewTypeWithTypeVarsFails]
299
300 from typing import NewType, TypeVar, List
301 T = TypeVar('T')
302 A = NewType('A', T)
303 B = NewType('B', List[T])
304 [builtins fixtures/list.pyi]
305 [out]
306 main:4: error: Argument 2 to NewType(...) must be subclassable (got T?)
307 main:4: error: Type variable "__main__.T" is unbound
308 main:4: note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class)
309 main:4: note: (Hint: Use "T" in function signature to bind "T" inside a function)
310 main:5: error: Type variable "__main__.T" is unbound
311 main:5: note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class)
312 main:5: note: (Hint: Use "T" in function signature to bind "T" inside a function)
313
314 [case testNewTypeRedefiningVariablesFails]
315
316 from typing import NewType
317
318 a = 3
319 def f(): a
320 a = NewType('a', int) # E: Cannot redefine "a" as a NewType \
321 # E: Name "a" already defined on line 4
322
323 b = NewType('b', int)
324 def g(): b
325 b = NewType('b', float) # E: Cannot redefine "b" as a NewType \
326 # E: Name "b" already defined on line 8
327
328 c = NewType('c', str) # type: str # E: Cannot declare the type of a NewType declaration
329
330 [case testNewTypeAddingExplicitTypesFails]
331 from typing import NewType
332 UserId = NewType('UserId', int)
333
334 a = 3 # type: UserId # E: Incompatible types in assignment (expression has type "int", variable has type "UserId")
335 [out]
336
337 [case testNewTypeTestSubclassingFails]
338 from typing import NewType
339 class A: pass
340 B = NewType('B', A)
341 class C(B): pass # E: Cannot subclass "NewType"
342 [out]
343
344 [case testCannotUseNewTypeWithProtocols]
345 from typing import Protocol, NewType
346
347 class P(Protocol):
348 attr: int = 0
349 class D:
350 attr: int
351
352 C = NewType('C', P) # E: NewType cannot be used with protocol classes
353
354 x: C = C(D()) # We still accept this, treating 'C' as non-protocol subclass.
355 reveal_type(x.attr) # N: Revealed type is "builtins.int"
356 x.bad_attr # E: "C" has no attribute "bad_attr"
357 C(1) # E: Argument 1 to "C" has incompatible type "int"; expected "P"
358 [out]
359
360 [case testNewTypeAny]
361 from typing import NewType
362 Any = NewType('Any', int)
363 Any(5)
364
365 [case testNewTypeWithIsInstanceAndIsSubclass]
366 from typing import NewType
367 T = NewType('T', int)
368 d: object
369 if isinstance(d, T): # E: Cannot use isinstance() with NewType type
370 reveal_type(d) # N: Revealed type is "builtins.int"
371 issubclass(object, T) # E: Cannot use issubclass() with NewType type
372 [builtins fixtures/isinstancelist.pyi]
373
374 [case testInvalidNewTypeCrash]
375
376 from typing import List, NewType, Union
377 N = NewType('N', XXX) # E: Argument 2 to NewType(...) must be subclassable (got "Any") \
378 # E: Name "XXX" is not defined
379 x: List[Union[N, int]]
380 [builtins fixtures/list.pyi]
381
382 [case testTypingExtensionsNewType]
383 from typing_extensions import NewType
384 N = NewType("N", int)
385 x: N
386 [builtins fixtures/tuple.pyi]