-4

I have two files which roughly look like this. module1.py:

GLOBAL_VAR = False
def some_func():
    if 1 == 1:
        GLOBAL_VAR = True

folder_1/module2.py:

from ..module1 import GLOBAL_VAR

if 2 == 2:
    print(f"GLOBAL_VAR : {GLOBAL_VAR }")

Basically in one file I declare and assign a variable and in another file which is inside a subfolder it is used.

Issue is above throws a linting error in module1.py that

F841 local variable 'GLOBAL_VAR' is assigned to but never used

How it is being used. So, how can I solve this linting error?

Maven
  • 14,587
  • 42
  • 113
  • 174

2 Answers2

0

You should not be using capital case for variables, capital case is used for constants, from PEP8:

Constants

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

You are also trying to define a global variable and mutate it, this is bad practice because of several reasons. Module2 can change your GLOBAL_VAR but module3, maybe written by someone else, can also change it or have dependencies upon GLOBAL_VAR. This will increase the chance of bugs being introduced and it makes the code harder to debug. There are many answers to find on why global variables should be avoided.

It might be that the linter is not expecting a global variable to be mutated and therefore doesn't recognize that the variable is not being assigned but being mutated. Since the function does not return anything to the linter it looks like nothing is being done with the GLOBAL_VAR variable in some_func

Gustafino
  • 40
  • 4
-1

If you want the GLOBAL_VAR in some_func to refer to the same GLOBAL_VAR outside it then you need to insert a global declaration in some_func:

GLOBAL_VAR = False
def some_func():
    global GLOBAL_VAR
    if 1 == 1:
        GLOBAL_VAR = True
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125