4

I wrote a python code to give a value to a variable if it is not defined, but nevertheless PyCharm warns me that the variable can be not defined:

if 'TEST' not in globals():
    TEST = "test"

print(TEST)

Name 'TEST' can be not defined

Is there an other way to define undefined variables such that PyCharm understand it?

7
  • Problem is with pycharm.you can ignore the warning
    – rawwar
    Commented May 25, 2018 at 14:58
  • 1
    PyCharm can't really tell that the logic of this ensures that the name must be defined. It only looks at syntax, it can't figured out the implication of the test.
    – Barmar
    Commented May 25, 2018 at 15:00
  • @Barmar I disagree with this because if I add the statement else: TEST = globals().get('TEST') I get rid of the warning. I think the problem comes more from the fact that we access to the variable via a string, which I find ugly but apparently there is no way to do otherwise.
    – Jean Paul
    Commented May 28, 2018 at 9:20
  • @JeanPaul It has nothing to do with accessing variable through a string. It gets rid of the warning only because you provided an else block. PyCharm can't understand the logic if 'TEST' not in globals() is False then it is already defined
    – DeepSpace
    Commented May 28, 2018 at 9:39
  • @JeanPaul Consider this piece of code: x = 1 ; if x == 1: foo = 2 ; print(foo) Here we also get the warning that foo may not be defined even though we hardcoded the condition which defines foo to always be True. Pycharm follows all possible branches according to the syntax, not logically.
    – DeepSpace
    Commented May 28, 2018 at 9:44

2 Answers 2

7

You can use a nonconditional initializer, e.g. with get, to get rid of the warning:

TEST = globals().get('TEST', 'test')
print(TEST)
1
  • 3
    @Barmar Indeed. However using get will get rid of the warning (and the unnecessary if). I changed the wording a bit.
    – DeepSpace
    Commented May 25, 2018 at 15:16
0

You should ensure that TEST is initialized.

TEST = 'TEST'
if 'TEST' not in globals():
    TEST = "test"
print(TEST)
1
  • The goal of my code is not to overwrite the TEST variable if it has been previously initialized. Explicitlly initialize it is not a solution for me, and doing so the two lines in the middle are useless.
    – Jean Paul
    Commented Jan 14, 2020 at 15:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.