buesma
buesma

Reputation: 31

Assign and use variables with the same condition without getting a warning

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:

Upvotes: 2

Views: 115

Answers (2)

Tomerikoo
Tomerikoo

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

Open AI - Opting Out
Open AI - Opting Out

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

Related Questions