summaryrefslogtreecommitdiff
path: root/tests/functional/u/undefined/undefined_variable.py
blob: e1b66910fc829383acc21a37e74821ba1b33304a (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
# pylint: disable=missing-docstring, multiple-statements, import-outside-toplevel
# pylint: disable=too-few-public-methods, bare-except, broad-except
# pylint: disable=using-constant-test, import-error, global-variable-not-assigned, unnecessary-comprehension
# pylint: disable=unnecessary-lambda-assignment


from typing import TYPE_CHECKING

DEFINED = 1

if DEFINED != 1:
    if DEFINED in (unknown, DEFINED):  # [undefined-variable]
        DEFINED += 1


def in_method(var):
    """method doc"""
    var = nomoreknown  # [undefined-variable]
    assert var

DEFINED = {DEFINED:__revision__}  # [undefined-variable]
# +1:[undefined-variable]
DEFINED[__revision__] = OTHER = 'move this is astroid test'

OTHER += '$'

def bad_default(var, default=unknown2):  # [undefined-variable]
    """function with default arg's value set to an nonexistent name"""
    print(var, default)
    print(xxxx)  # [undefined-variable]
    augvar += 1  # [undefined-variable]
    del vardel  # [undefined-variable]

LMBD = lambda x, y=doesnotexist: x+y  # [undefined-variable]
LMBD2 = lambda x, y: x+z  # [undefined-variable]

try:
    POUET # [used-before-assignment]
except NameError:
    POUET = 'something'

try:
    POUETT # [used-before-assignment]
except Exception: # pylint:disable = broad-except
    POUETT = 'something'

try:
    POUETTT # [used-before-assignment]
except: # pylint:disable = bare-except
    POUETTT = 'something'

print(POUET, POUETT, POUETTT)


try:
    PLOUF  # [used-before-assignment]
except ValueError:
    PLOUF = 'something'

print(PLOUF)

def if_branch_test(something):
    """hop"""
    if something == 0:
        if xxx == 1:  # [used-before-assignment]
            pass
    else:
        print(xxx)
        xxx = 3


def decorator(arg):
    """Decorator with one argument."""
    return lambda: list(arg)


@decorator(arg=[i * 2 for i in range(15)])
def func1():
    """A function with a decorator that contains a listcomp."""

@decorator(arg=(i * 2 for i in range(15)))
def func2():
    """A function with a decorator that contains a genexpr."""

@decorator(lambda x: x > 0)
def main():
    """A function with a decorator that contains a lambda."""

# Test shared scope.

def test_arguments(arg=TestClass):  # [used-before-assignment]
    """ TestClass isn't defined yet. """
    return arg

class TestClass(Ancestor):  # [used-before-assignment]
    """ contains another class, which uses an undefined ancestor. """

    class MissingAncestor(Ancestor1):  # [used-before-assignment]
        """ no op """

    def test1(self):
        """ It should trigger here, because the two classes
        have the same scope.
        """
        class UsingBeforeDefinition(Empty):  # [used-before-assignment]
            """ uses Empty before definition """
        class Empty:
            """ no op """
        return UsingBeforeDefinition

    def test(self):
        """ Ancestor isn't defined yet, but we don't care. """
        class MissingAncestor1(Ancestor):
            """ no op """
        return MissingAncestor1

class Self:
    """ Detect when using the same name inside the class scope. """
    obj = Self # [undefined-variable]

class Self1:
    """ No error should be raised here. """

    def test(self):
        """ empty """
        return Self1


class Ancestor:
    """ No op """

class Ancestor1:
    """ No op """

NANA = BAT # [undefined-variable]
del BAT  # [undefined-variable]


class KeywordArgument:
    """Test keyword arguments."""

    enable = True
    def test(self, is_enabled=enable):
        """do nothing."""

    def test1(self, is_enabled=enabled): # [used-before-assignment]
        """enabled is undefined at this point, but it is used before assignment."""

    def test2(self, is_disabled=disabled): # [undefined-variable]
        """disabled is undefined"""

    enabled = True

    func = lambda arg=arg: arg * arg # [undefined-variable]

    arg2 = 0
    func2 = lambda arg2=arg2: arg2 * arg2

# Don't emit if the code is protected by NameError
try:
    unicode_1
except NameError:
    pass

try:
    unicode_2 # [undefined-variable]
except Exception:
    pass

try:
    unicode_3 # [undefined-variable]
except ValueError:
    pass

# See https://bitbucket.org/logilab/pylint/issue/111/
try: raise IOError(1, "a")
except IOError as err: print(err)


def test_conditional_comprehension():
    methods = ['a', 'b', '_c', '_d']
    my_methods = sum(1 for method in methods
                     if not method.startswith('_'))
    return my_methods


class MyError:
    pass


class MyClass:
    class MyError(MyError):
        pass


def dec(inp):
    def inner(func):
        print(inp)
        return func
    return inner

# Make sure lambdas with expressions
# referencing parent class do not raise undefined variable
# because at the time of their calling, the class name will
# be populated
# See https://github.com/pylint-dev/pylint/issues/704
class LambdaClass:
    myattr = 1
    mylambda = lambda: LambdaClass.myattr

# Need different classes to make sure
# consumed variables don't get in the way
class LambdaClass2:
    myattr = 1
    # Different base_scope scope but still applies
    mylambda2 = lambda: [LambdaClass2.myattr for _ in [1, 2]]

class LambdaClass3:
    myattr = 1
    # Nested default argument in lambda
    # Should not raise error
    mylambda3 = lambda: lambda a=LambdaClass3: a

class LambdaClass4:
    myattr = 1
    mylambda4 = lambda a=LambdaClass4: lambda: a # [undefined-variable]

# Make sure the first lambda does not consume the LambdaClass5 class
# name although the expression is is valid
# Consuming the class would cause the subsequent undefined-variable to be masked
class LambdaClass5:
    myattr = 1
    mylambda = lambda: LambdaClass5.myattr
    mylambda4 = lambda a=LambdaClass5: lambda: a # [undefined-variable]


def nonlocal_in_ifexp():
    import matplotlib.pyplot as plt
    def onclick(event):
        if event:
            nonlocal i
            i += 1
            print(i)
    i = 0
    fig = plt.figure()
    fig.canvas.mpl_connect('button_press_event', onclick)
    plt.show(block=True)



if TYPE_CHECKING:
    from datetime import datetime


def func_should_fail(_dt: datetime):  # [used-before-assignment]
    pass


# The following should not emit an error.
# pylint: disable=invalid-name
if TYPE_CHECKING:
    from typing_extensions import Literal

    AllowedValues = Literal['hello', 'world']


if TYPE_CHECKING:
    from collections import Counter
    from collections import OrderedDict
    from collections import defaultdict
    from collections import UserDict
else:
    Counter = object
    OrderedDict = object
    def defaultdict():
        return {}
    class UserDict(dict):
        pass


def tick(counter: Counter, name: str, dictionary: OrderedDict) -> OrderedDict:
    counter[name] += 1
    return dictionary

defaultdict()

UserDict()

# pylint: disable=unused-argument
def not_using_loop_variable_accordingly(iterator):
    for iteree in iteree: # [undefined-variable]
        yield iteree
# pylint: enable=unused-argument


class DunderClass:
    def method(self):
        # This name is not defined in the AST but it's present at runtime
        return __class__

    # It is also present in inner methods
    def method_two(self):
        def inner_method():
            return __class__

        inner_method()

def undefined_annotation(a:x): # [undefined-variable]
    if x == 2: # [used-before-assignment]
        for x in [1, 2]:
            pass
    return a


# #3711's comment regression test
lst = []
lst2 = [1, 2, 3]

for item in lst:
    pass

bigger = [
    [
        x for x in lst2 if x > item
    ]
    for item in lst
]


# 3791
@decorator(x for x in range(3))
def decorated1(x):
    print(x)

@decorator(x * x for x in range(3))
def decorated2(x):
    print(x)

@decorator(x)  # [undefined-variable]
@decorator(x * x for x in range(3))
def decorated3(x):
    print(x)

@decorator(x * x * y for x in range(3))  # [undefined-variable]
def decorated4(x):
    print(x)


# https://github.com/pylint-dev/pylint/issues/5111
# AssignAttr in orelse block of 'TYPE_CHECKING' shouldn't crash
# Name being assigned must be imported in orelse block
if TYPE_CHECKING:
    pass
else:
    from types import GenericAlias
    object().__class_getitem__ = classmethod(GenericAlias)


GLOBAL_VAR: int
GLOBAL_VAR_TWO: int

def global_var_mixed_assignment():
    """One global variable never gets assigned a value"""
    global GLOBAL_VAR
    print(GLOBAL_VAR) # [undefined-variable]
    global GLOBAL_VAR_TWO
    print(GLOBAL_VAR_TWO)

GLOBAL_VAR_TWO = 2


GLOBAL_VAR: int
GLOBAL_VAR_TWO: int


class RepeatedReturnAnnotations:
    def x(self, o: RepeatedReturnAnnotations) -> bool:  # [undefined-variable]
        pass
    def y(self) -> RepeatedReturnAnnotations:  # [undefined-variable]
        pass
    def z(self) -> RepeatedReturnAnnotations:  # [undefined-variable]
        pass