summaryrefslogtreecommitdiff
path: root/pyflakes/test/test_type_annotations.py
blob: 885302c259c3f4f388ae89ff28f3940ef21ed27b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
"""
Tests for behaviour related to type annotations.
"""

from sys import version_info

from pyflakes import messages as m
from pyflakes.test.harness import TestCase, skipIf


class TestTypeAnnotations(TestCase):

    def test_typingOverload(self):
        """Allow intentional redefinitions via @typing.overload"""
        self.flakes("""
        import typing
        from typing import overload

        @overload
        def f(s: None) -> None:
            pass

        @overload
        def f(s: int) -> int:
            pass

        def f(s):
            return s

        @typing.overload
        def g(s: None) -> None:
            pass

        @typing.overload
        def g(s: int) -> int:
            pass

        def g(s):
            return s
        """)

    def test_typingExtensionsOverload(self):
        """Allow intentional redefinitions via @typing_extensions.overload"""
        self.flakes("""
        import typing_extensions
        from typing_extensions import overload

        @overload
        def f(s: None) -> None:
            pass

        @overload
        def f(s: int) -> int:
            pass

        def f(s):
            return s

        @typing_extensions.overload
        def g(s: None) -> None:
            pass

        @typing_extensions.overload
        def g(s: int) -> int:
            pass

        def g(s):
            return s
        """)

    def test_typingOverloadAsync(self):
        """Allow intentional redefinitions via @typing.overload (async)"""
        self.flakes("""
        from typing import overload

        @overload
        async def f(s: None) -> None:
            pass

        @overload
        async def f(s: int) -> int:
            pass

        async def f(s):
            return s
        """)

    def test_overload_with_multiple_decorators(self):
        self.flakes("""
            from typing import overload
            dec = lambda f: f

            @dec
            @overload
            def f(x: int) -> int:
                pass

            @dec
            @overload
            def f(x: str) -> str:
                pass

            @dec
            def f(x): return x
       """)

    def test_overload_in_class(self):
        self.flakes("""
        from typing import overload

        class C:
            @overload
            def f(self, x: int) -> int:
                pass

            @overload
            def f(self, x: str) -> str:
                pass

            def f(self, x): return x
        """)

    def test_aliased_import(self):
        """Detect when typing is imported as another name"""
        self.flakes("""
        import typing as t

        @t.overload
        def f(s: None) -> None:
            pass

        @t.overload
        def f(s: int) -> int:
            pass

        def f(s):
            return s
        """)

    def test_not_a_typing_overload(self):
        """regression test for @typing.overload detection bug in 2.1.0"""
        self.flakes("""
            def foo(x):
                return x

            @foo
            def bar():
                pass

            def bar():
                pass
        """, m.RedefinedWhileUnused)

    def test_variable_annotations(self):
        self.flakes('''
        name: str
        age: int
        ''')
        self.flakes('''
        name: str = 'Bob'
        age: int = 18
        ''')
        self.flakes('''
        class C:
            name: str
            age: int
        ''')
        self.flakes('''
        class C:
            name: str = 'Bob'
            age: int = 18
        ''')
        self.flakes('''
        def f():
            name: str
            age: int
        ''', m.UnusedAnnotation, m.UnusedAnnotation)
        self.flakes('''
        def f():
            name: str = 'Bob'
            age: int = 18
            foo: not_a_real_type = None
        ''', m.UnusedVariable, m.UnusedVariable, m.UnusedVariable, m.UndefinedName)
        self.flakes('''
        def f():
            name: str
            print(name)
        ''', m.UndefinedName)
        self.flakes('''
        from typing import Any
        def f():
            a: Any
        ''', m.UnusedAnnotation)
        self.flakes('''
        foo: not_a_real_type
        ''', m.UndefinedName)
        self.flakes('''
        foo: not_a_real_type = None
        ''', m.UndefinedName)
        self.flakes('''
        class C:
            foo: not_a_real_type
        ''', m.UndefinedName)
        self.flakes('''
        class C:
            foo: not_a_real_type = None
        ''', m.UndefinedName)
        self.flakes('''
        def f():
            class C:
                foo: not_a_real_type
        ''', m.UndefinedName)
        self.flakes('''
        def f():
            class C:
                foo: not_a_real_type = None
        ''', m.UndefinedName)
        self.flakes('''
        from foo import Bar
        bar: Bar
        ''')
        self.flakes('''
        from foo import Bar
        bar: 'Bar'
        ''')
        self.flakes('''
        import foo
        bar: foo.Bar
        ''')
        self.flakes('''
        import foo
        bar: 'foo.Bar'
        ''')
        self.flakes('''
        from foo import Bar
        def f(bar: Bar): pass
        ''')
        self.flakes('''
        from foo import Bar
        def f(bar: 'Bar'): pass
        ''')
        self.flakes('''
        from foo import Bar
        def f(bar) -> Bar: return bar
        ''')
        self.flakes('''
        from foo import Bar
        def f(bar) -> 'Bar': return bar
        ''')
        self.flakes('''
        bar: 'Bar'
        ''', m.UndefinedName)
        self.flakes('''
        bar: 'foo.Bar'
        ''', m.UndefinedName)
        self.flakes('''
        from foo import Bar
        bar: str
        ''', m.UnusedImport)
        self.flakes('''
        from foo import Bar
        def f(bar: str): pass
        ''', m.UnusedImport)
        self.flakes('''
        def f(a: A) -> A: pass
        class A: pass
        ''', m.UndefinedName, m.UndefinedName)
        self.flakes('''
        def f(a: 'A') -> 'A': return a
        class A: pass
        ''')
        self.flakes('''
        a: A
        class A: pass
        ''', m.UndefinedName)
        self.flakes('''
        a: 'A'
        class A: pass
        ''')
        self.flakes('''
        T: object
        def f(t: T): pass
        ''', m.UndefinedName)
        self.flakes('''
        T: object
        def g(t: 'T'): pass
        ''')
        self.flakes('''
        a: 'A B'
        ''', m.ForwardAnnotationSyntaxError)
        self.flakes('''
        a: 'A; B'
        ''', m.ForwardAnnotationSyntaxError)
        self.flakes('''
        a: '1 + 2'
        ''')
        self.flakes('''
        a: 'a: "A"'
        ''', m.ForwardAnnotationSyntaxError)

    def test_variable_annotation_references_self_name_undefined(self):
        self.flakes("""
        x: int = x
        """, m.UndefinedName)

    def test_TypeAlias_annotations(self):
        self.flakes("""
        from typing_extensions import TypeAlias
        from foo import Bar

        bar: TypeAlias = Bar
        """)
        self.flakes("""
        from typing_extensions import TypeAlias
        from foo import Bar

        bar: TypeAlias = 'Bar'
        """)
        self.flakes("""
        from typing_extensions import TypeAlias
        from foo import Bar

        class A:
            bar: TypeAlias = Bar
        """)
        self.flakes("""
        from typing_extensions import TypeAlias
        from foo import Bar

        class A:
            bar: TypeAlias = 'Bar'
        """)
        self.flakes("""
        from typing_extensions import TypeAlias

        bar: TypeAlias
        """)
        self.flakes("""
        from typing_extensions import TypeAlias
        from foo import Bar

        bar: TypeAlias
        """, m.UnusedImport)

    def test_annotating_an_import(self):
        self.flakes('''
            from a import b, c
            b: c
            print(b)
        ''')

    def test_unused_annotation(self):
        # Unused annotations are fine in module and class scope
        self.flakes('''
        x: int
        class Cls:
            y: int
        ''')
        self.flakes('''
        def f():
            x: int
        ''', m.UnusedAnnotation)
        # This should only print one UnusedVariable message
        self.flakes('''
        def f():
            x: int
            x = 3
        ''', m.UnusedVariable)

    def test_unassigned_annotation_is_undefined(self):
        self.flakes('''
        name: str
        print(name)
        ''', m.UndefinedName)

    def test_annotated_async_def(self):
        self.flakes('''
        class c: pass
        async def func(c: c) -> None: pass
        ''')

    @skipIf(version_info < (3, 7), 'new in Python 3.7')
    def test_postponed_annotations(self):
        self.flakes('''
        from __future__ import annotations
        def f(a: A) -> A: pass
        class A:
            b: B
        class B: pass
        ''')

        self.flakes('''
        from __future__ import annotations
        def f(a: A) -> A: pass
        class A:
            b: Undefined
        class B: pass
        ''', m.UndefinedName)

        self.flakes('''
        from __future__ import annotations
        T: object
        def f(t: T): pass
        def g(t: 'T'): pass
        ''')

    def test_type_annotation_clobbers_all(self):
        self.flakes('''\
        from typing import TYPE_CHECKING, List

        from y import z

        if not TYPE_CHECKING:
            __all__ = ("z",)
        else:
            __all__: List[str]
        ''')

    def test_return_annotation_is_class_scope_variable(self):
        self.flakes("""
        from typing import TypeVar
        class Test:
            Y = TypeVar('Y')

            def t(self, x: Y) -> Y:
                return x
        """)

    def test_return_annotation_is_function_body_variable(self):
        self.flakes("""
        class Test:
            def t(self) -> Y:
                Y = 2
                return Y
        """, m.UndefinedName)

    @skipIf(version_info < (3, 8), 'new in Python 3.8')
    def test_positional_only_argument_annotations(self):
        self.flakes("""
        from x import C

        def f(c: C, /): ...
        """)

    def test_partially_quoted_type_annotation(self):
        self.flakes("""
        from queue import Queue
        from typing import Optional

        def f() -> Optional['Queue[str]']:
            return None
        """)

    def test_partially_quoted_type_assignment(self):
        self.flakes("""
        from queue import Queue
        from typing import Optional

        MaybeQueue = Optional['Queue[str]']
        """)

    def test_nested_partially_quoted_type_assignment(self):
        self.flakes("""
        from queue import Queue
        from typing import Callable

        Func = Callable[['Queue[str]'], None]
        """)

    def test_quoted_type_cast(self):
        self.flakes("""
        from typing import cast, Optional

        maybe_int = cast('Optional[int]', 42)
        """)

    def test_type_cast_literal_str_to_str(self):
        # Checks that our handling of quoted type annotations in the first
        # argument to `cast` doesn't cause issues when (only) the _second_
        # argument is a literal str which looks a bit like a type annotation.
        self.flakes("""
        from typing import cast

        a_string = cast(str, 'Optional[int]')
        """)

    def test_quoted_type_cast_renamed_import(self):
        self.flakes("""
        from typing import cast as tsac, Optional as Maybe

        maybe_int = tsac('Maybe[int]', 42)
        """)

    def test_quoted_TypeVar_constraints(self):
        self.flakes("""
        from typing import TypeVar, Optional

        T = TypeVar('T', 'str', 'Optional[int]', bytes)
        """)

    def test_quoted_TypeVar_bound(self):
        self.flakes("""
        from typing import TypeVar, Optional, List

        T = TypeVar('T', bound='Optional[int]')
        S = TypeVar('S', int, bound='List[int]')
        """)

    def test_literal_type_typing(self):
        self.flakes("""
        from typing import Literal

        def f(x: Literal['some string']) -> None:
            return None
        """)

    def test_literal_type_typing_extensions(self):
        self.flakes("""
        from typing_extensions import Literal

        def f(x: Literal['some string']) -> None:
            return None
        """)

    def test_annotated_type_typing_missing_forward_type(self):
        self.flakes("""
        from typing import Annotated

        def f(x: Annotated['integer']) -> None:
            return None
        """, m.UndefinedName)

    def test_annotated_type_typing_missing_forward_type_multiple_args(self):
        self.flakes("""
        from typing import Annotated

        def f(x: Annotated['integer', 1]) -> None:
            return None
        """, m.UndefinedName)

    def test_annotated_type_typing_with_string_args(self):
        self.flakes("""
        from typing import Annotated

        def f(x: Annotated[int, '> 0']) -> None:
            return None
        """)

    def test_annotated_type_typing_with_string_args_in_union(self):
        self.flakes("""
        from typing import Annotated, Union

        def f(x: Union[Annotated['int', '>0'], 'integer']) -> None:
            return None
        """, m.UndefinedName)

    def test_literal_type_some_other_module(self):
        """err on the side of false-negatives for types named Literal"""
        self.flakes("""
        from my_module import compat
        from my_module.compat import Literal

        def f(x: compat.Literal['some string']) -> None:
            return None
        def g(x: Literal['some string']) -> None:
            return None
        """)

    def test_literal_union_type_typing(self):
        self.flakes("""
        from typing import Literal

        def f(x: Literal['some string', 'foo bar']) -> None:
            return None
        """)

    def test_deferred_twice_annotation(self):
        self.flakes("""
            from queue import Queue
            from typing import Optional


            def f() -> "Optional['Queue[str]']":
                return None
        """)

    @skipIf(version_info < (3, 7), 'new in Python 3.7')
    def test_partial_string_annotations_with_future_annotations(self):
        self.flakes("""
            from __future__ import annotations

            from queue import Queue
            from typing import Optional


            def f() -> Optional['Queue[str]']:
                return None
        """)

    def test_idomiatic_typing_guards(self):
        # typing.TYPE_CHECKING: python3.5.3+
        self.flakes("""
            from typing import TYPE_CHECKING

            if TYPE_CHECKING:
                from t import T

            def f() -> T:
                pass
        """)
        # False: the old, more-compatible approach
        self.flakes("""
            if False:
                from t import T

            def f() -> T:
                pass
        """)
        # some choose to assign a constant and do it that way
        self.flakes("""
            MYPY = False

            if MYPY:
                from t import T

            def f() -> T:
                pass
        """)

    def test_typing_guard_for_protocol(self):
        self.flakes("""
            from typing import TYPE_CHECKING

            if TYPE_CHECKING:
                from typing import Protocol
            else:
                Protocol = object

            class C(Protocol):
                def f() -> int:
                    pass
        """)

    def test_typednames_correct_forward_ref(self):
        self.flakes("""
            from typing import TypedDict, List, NamedTuple

            List[TypedDict("x", {})]
            List[TypedDict("x", x=int)]
            List[NamedTuple("a", a=int)]
            List[NamedTuple("a", [("a", int)])]
        """)
        self.flakes("""
            from typing import TypedDict, List, NamedTuple, TypeVar

            List[TypedDict("x", {"x": "Y"})]
            List[TypedDict("x", x="Y")]
            List[NamedTuple("a", [("a", "Y")])]
            List[NamedTuple("a", a="Y")]
            List[TypedDict("x", {"x": List["a"]})]
            List[TypeVar("A", bound="C")]
            List[TypeVar("A", List["C"])]
        """, *[m.UndefinedName]*7)
        self.flakes("""
            from typing import NamedTuple, TypeVar, cast
            from t import A, B, C, D, E

            NamedTuple("A", [("a", A["C"])])
            TypeVar("A", bound=A["B"])
            TypeVar("A", A["D"])
            cast(A["E"], [])
        """)

    def test_namedtypes_classes(self):
        self.flakes("""
            from typing import TypedDict, NamedTuple
            class X(TypedDict):
                y: TypedDict("z", {"zz":int})

            class Y(NamedTuple):
                y: NamedTuple("v", [("vv", int)])
        """)

    @skipIf(version_info < (3, 11), 'new in Python 3.11')
    def test_variadic_generics(self):
        self.flakes("""
            from typing import Generic
            from typing import TypeVarTuple

            Ts = TypeVarTuple('Ts')

            class Shape(Generic[*Ts]): pass

            def f(*args: *Ts) -> None: ...

            def g(x: Shape[*Ts]) -> Shape[*Ts]: ...
        """)