Python global scopes

The Python global scopes has a larger scope of influence than the local scopes or enclosing scopes. The global scopes contain the global variables. Any variables declared outside the local scopes and enclosed scopes are the global variables.

Link : Pyhton local scopes

In the global scopes the usual scoping rules still apply. This means the local variable has the most power over the local region followed by the enclosed scope variables and then the global variables.

Link : Python enclosing scopes

Consider the code example.

>>> gb=100 #A global variable
>>> def func():
	m=23 #local variable
	print('m=',m )
	print('gb=',gb)

	
>>> func()
m= 23
gb= 100
>>> print( m )
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    print( m )
NameError: name 'm' is not defined

We can access the global variable ‘gb’ inside the local scope because global scope has influence over the local scope, but we cannot access the local variable ‘m’ outside the local scope. Trying to access it will give an error message as shown above.

Here is another example which shows that the local variable has more power over the global variable.

>>> hi=1111
>>> def func():
	hi=444 #Local variable
	print( 'hi=', hi )

	
>>> func()
hi= 444
>>> print('Ourisde func() hi=',hi)
Ourisde func() hi= 1111

Inside the local scope the local variable ‘hi'(444) is preferred over the global value. Outside the local scope the global value is preffered since the local variable has ceased to exist.



More examples

Let us test the power of global variable with the enclosed variable.

>>> k=888
>>> def Outer():
	k=89
	h=90
	def Inner(): #inner scope begins here
		h=555
		print( 'Inner() h=',h )
		print('Inner() k=',k)
	Inner()
	print( 'Outer() k=',k )

	
>>> Outer()
Inner() h= 555
Inner() k= 89
Outer() k= 89
>>> print('k=',k)
k= 888

Inisde the Inner() scope the local ‘h'(555) is preferred. In case of ‘k’, the enclosed ‘k'(89) is preferred not the global ‘k'(888).

Inside Outer() the enclosed ‘K'(89) is still preferred, not the global ‘k'(888).

Outside the enclosde scope the global variable ‘k'(888) is taken.


***Side note

Always remember,the order followed by Python while looking for names in a scope or namespace is : local socpe> enclosing scope > global scope > built-in scope. This order is also known as ‘LEGB‘.

Link :Python scopes types




Leave a Reply

Your email address will not be published. Required fields are marked *