Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are:
- Python modules namely ‘math’ and ‘cmath’ have a lot of functions that are common to both of them –
log10()
,acos()
,exp()
etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, likemath.exp()
andcmath.exp()
. - Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn’t change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities.
temp = 10 # global-scope variable
def func():
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 10
This behavior can be overridden using the global
keyword inside the function, as shown in the following example:
temp = 10 # global-scope variable
def func():
global temp
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 20