How to rewrite this code, such that PyCharm doesn't warn Local variable might be referenced before assignment?

Viewed 39

Please consider

def foo():
    bs = (4, 5)
    for b in bs:
        c = b + 1
    return c

PyCharm marks the c in the return c with

Local variable 'c' might be referenced before assignment

This is a good warning, usually, and I don't want to disable it. (#noqa is not an answer)

In this case, however, it can be deduced before running that c always has a value.


How to rewrite the code to help PyCharm understand this?

1 Answers

You can do what is done in most languages which is to instantiate c to a value of 0.

def foo():
    bs = (4, 5)
    c = 0     
    for b in bs:
        c = b + 1
    return c
Related