How can I create and use a variable in Python (3.8) only under a certain condition without a linter warning?
For example, the following code triggers the warning Local variable 'b' might be referenced before assignment in my IDE (PyCharm):
def my_function(n, condition):
a = 1
if condition:
b = 2
for _ in range(n):
a += 1
if condition:
a += b
return a
Setting b = 0 and writing a += 1 + b is not possible for computational reasons.
Possible solutions which came to my mind are:
- Split this function into two separate functions which would lead to repeated code.
- Add an else case in which
bis set toNonewhich seems ugly in my opinion.