Search code examples
coding-stylerenamenaming-conventionsnamingprefix

What are the common ways to distinguish between identifier of local variables and global variables?


I write a function with using same identifier for local variable and globel variable, as shown as following codes:

def func(time_len, num_nodes):
    pass

if __name__ == '__main__':
    time_len, num_nodes = input_arrs.shape
    func(time_len=time_len, num_nodes=num_nodes)

I want to reduce this kind of naming style to avoid ambiguity. But the only method I can think of is adding prefix or suffix to identifier, like this:

def func(time_len, num_nodes):
    pass

if __name__ == '__main__':
    global_time_len, global_num_nodes = input_arrs.shape
    func(time_len=global_time_len, num_nodes=global_num_nodes)

My question is: What are the common ways or conventions to distinguish between local variables and global variables?


Solution

  • It is not typical Python Style to do what you suggest. https://pep8.org/#global-variable-names

    However, there are several other styles you can take inspiration from.

    You can try a g_ prefix to note a global variable. I've seen this used although it is not popular.

    Some code styles also have guidance on global variable where you use UpperCamelCase for global variables (and functions) and lowerCamelCase for locals. If you instead prefer underscores, it's easily modified to be Upper_With_Under and lower_with_under.

    Typically, in modern code styles we don't rely on naming to note which variable is in what scope. If a programmer cannot keep track of which name is in what scope, that should tell you that the file is too complex with too many names and too many overlapping scopes. You should take this confusion and turn it into a round of simplification, modularization, and abstraction so that the code is easier to understand and keep in your mind.

    Code that is too complex for you to keep track of is code that is too complex to modify.