Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the global keyword not required in this case?

Tags:

cache = {}
def func():
    cache['foo'] = 'bar'
print cache['foo'] 

output

bar

Why does this work and why doesn't it require use of the global keyword?

like image 294
Bunny Rabbit Avatar asked Dec 29 '12 11:12

Bunny Rabbit


People also ask

Why should we not use global variables in Python?

The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.

Do you need global keyword in Python?

The basic rules for global keyword in Python are: When we create a variable inside a function, it is local by default. When we define a variable outside of a function, it is global by default. You don't have to use global keyword.

What is the purpose of global keyword in Python?

The global keyword is used to create global variables from a no-global scope, e.g. inside a function.

What is the need of global keywords?

A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to create global variables in Python from a non-global scope, i.e. inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable.


1 Answers

Because you are not assigning to cache, you are changing the dictionary itself instead. cache is still pointing to the dictionary, thus is itself unchanged. The line cache['foo'] = 'bar' translates to cache.__setitem__('foo', 'bar'). In other words, the value of cache is a python dict, and that value is itself mutable.

If you tried to change what cache refers to by using cache = 'bar' instead, you would be changing what cache points to and then you need the global keyword.

Perhaps this older answer of mine to a similar question helps you understand the difference: Python list doesn't reflect variable change.

like image 98
Martijn Pieters Avatar answered Sep 29 '22 02:09

Martijn Pieters