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?
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.
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.
The global keyword is used to create global variables from a no-global scope, e.g. inside a function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With