Skip to content

Commit

Permalink
Handle variables defined only under a type checking clause
Browse files Browse the repository at this point in the history
These kind of variables will cause a runtime error, since the variable
will not be defined, unless we use the `annotations` future.

Close #3081
  • Loading branch information
PCManticore committed Sep 17, 2019
1 parent 2a5c1ab commit a7f2365
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,11 @@ def _is_variable_violation(
# Single statement function, with the statement on the
# same line as the function definition
maybee0601 = False
if isinstance(defstmt, (astroid.Import, astroid.ImportFrom)):
defstmt_parent = defstmt.parent
if isinstance(defstmt_parent, astroid.If):
if defstmt_parent.test.as_string() in TYPING_TYPE_CHECKS_GUARDS:
maybee0601 = True

return maybee0601, annotation_return, use_outer_definition

Expand Down
11 changes: 11 additions & 0 deletions tests/functional/u/undefined_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,14 @@ def onclick(event):
fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show(block=True)


# pylint: disable=wrong-import-position
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from datetime import datetime


def func_should_fail(_dt: datetime): # [used-before-assignment]
pass
1 change: 1 addition & 0 deletions tests/functional/u/undefined_variable.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ undefined-variable:161::Undefined variable 'unicode_2'
undefined-variable:171::Undefined variable 'unicode_4'
undefined-variable:226:LambdaClass4.<lambda>:Undefined variable 'LambdaClass4'
undefined-variable:234:LambdaClass5.<lambda>:Undefined variable 'LambdaClass5'
used-before-assignment:257:func_should_fail:Using variable 'datetime' before assignment

0 comments on commit a7f2365

Please sign in to comment.