The code:
assets = {} # line 1
def myfunc():
global assets # line 4
if assets.get("a", None) is None:
assets["a"] = 2
The pylint result:
C: 1, 0: Invalid constant name "assets" (invalid-name)
C: 4, 4: Invalid constant name "assets" (invalid-name)
W: 4, 4: Using global for 'assets' but \
no assignment is done (global-variable-not-assigned)
The function will be called later more than once so I just want to assign (in real life some time-consuming process) the value only once.
How should I do it properly?
p.s.: Thanks @deceze, I was confused by the fact that if instead of assets = {}
I use assets = {"a":2}
the behavior will be absolutely different.
The linter tells you that you're not assigning to assets
, meaning assets = ...
. Which means you do not need global assets
. The variable assets
from the outer scope will be available inside myfunc
anyway for reading. You only need global
if you want to assign a different value to the variable in the outer scope. assets['a'] = 2
is not assigning a different value to it, it's just mutating the existing value.
So, remove the global assets
line.