Global Variables are evil, we all know that (by global variables, I mean module level variables). I want to write a custom lint rule to protect its updation. For example,
GLOBAL_DICT = {
'a': 1,
'b': 2,
}
def func():
var_1 = GLOBAL_DICT.get('a') # Should be a valid case
GLOBAL_DICT.update({ # Should be an invalid case, and Lint should catch this
'c': 3,
})
func()
Accessing (reading) the module level variables is a common pattern that we use, however updating a module level (global) variables is an unsafe operation.
I have tried using the ast library and the libCST library to catch this updation. But I couldn't find any way of detecting mutation of a global variable. The only way I could think of is hard coding a list of update operations for mutable data structures, like .extend()
, .append()
, etc for list
data structure; and .update()
, .pop()
, etc for dict
data structure. And while traversing the tree (AST or CST), store a list of all the global variables if they are mutable type, and if one of the mentioned method is called on one of them, the lint rule can call it out. But this doesn't look like a full proof solution.
Can you please tell ideas around how can I implement a custom lint rule for this?