2

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?

  • 1
    I think you need to be clearer about your goal (at least, reading the first answer and various comments to it). Normally, "mutation of a global variable" would mean direct assignment to a global variable (`a = 5`), which requires some work but is clearly doable. But I think you're hoping to statically catch mutation of an object assigned to a global variable (`a['b'] = 5`), which is going to be extremely difficult (if not impossible) with static analysis, and also might not be all that useful. – rici Sep 25 '22 at 01:23
  • 2
    FWIW, it looks like „global“ here is a ref herring and needlessly restrictive. Finding out whether something is rooted at a global is the easy part; the challenge is detecting mutations, and that would work the same for any scope. – MisterMiyagi Sep 25 '22 at 05:00

0 Answers0