Gulzar
Gulzar

Reputation: 27966

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

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?

Upvotes: 3

Views: 371

Answers (1)

Lihka_nonem
Lihka_nonem

Reputation: 378

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

Upvotes: 1

Related Questions