pythonglobal-variables

How can I change that global variables are the default in Python?


Everyone says not to use Global variables. But, in Python the default is that all variables are global. Is there any way to change this?

def function():
    dic['one']=35
    
dic={}
function()
print(dic)

Solution

  • A global variable is a named variable whose value can be reassigned from any scope. In order to reach into a higher scope and reassign a variable that was defined there, you need to explicitly use the global or nonlocal keyword. For example:

    def function():
        global foo
        foo = 5
    
    foo = 3
    function()
    print(foo)  # prints 5
    

    Variables are not global by default:

    def function():
        foo = 5
    
    foo = 3
    function()
    print(foo)  # prints 3
    

    In your example, the variable dic is not itself being modified, but rather the value that it references (this is possible because dictionaries are a mutable type of value; you can modify the contents of a dictionary via the [] operator). If we try to modify the variable dic inside the function, this change is not reflected in the outer scope:

    def function():
        dic = {'one': 35}
    
    dic={}
    function()
    print(dic) # prints {}