Reputation: 31
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:
b
is set to None
which seems ugly in my opinion.Upvotes: 2
Views: 115
Reputation: 19414
Why do you even need b
?
def my_function(n, condition):
a = 1
for _ in range(n):
a += 1
if condition:
a += 2
return a
If all you want is to avoid PyCharm's warning, please it by setting a default value for b
. As I understand your code, it will not be used anyway, this is just to silence the warning:
def my_function(n, condition):
a = 1
b = None
if condition:
b = 2
[...]
Lastly, assuming you only access b
under if condition:
blocks, then there is no need to conditionally assign it in the first place. You can set it to the desired value, and you will only use it when needed:
def my_function(n, condition):
a = 1
b = 2
for _ in range(n):
a += 1
if condition:
a += b
Upvotes: 3
Reputation: 24133
You could create an increment variable which is either 1
or 3
:
def my_function(n, condition):
if condition:
increment = 3
else:
increment = 1
a = 1
for _ in range(n):
a += increment
return a
Upvotes: 1