Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 612
Gulzar Avatar asked Jan 26 '26 11:01

Gulzar


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
like image 77
Lihka_nonem Avatar answered Jan 27 '26 23:01

Lihka_nonem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!