Python Programming - Scope and Module

You can learn about Python Variable Scope Programs with Outputs helped you to understand the language better.

Python Programming – Scope and Module

Variables are reserved memory locations to store values. When you assign a variable with = to an instance, you are binding or mapping the variable to that instance. Python keeps track of all these map-pings with namespaces. Roughly speaking, name spaces are just containers for mapping names to objects, i.e., these are containers for mapping names of variables to objects. You can think of them as dictionaries, containing name: object mappings, where the dictionary keys represent the names and the dictionary values the object itself. Such a ” name-to-object” mapping allows you to access an object by the name that you have assigned to it. For example, if we make a simple string assignment via a_string = “Hello”, you created a reference to the “Hello” object, and hereafter you can access via its variable name a_string.

Also, you have multiple independent namespaces in Python, and names can be reused for different namespaces with unique objects. Namespaces also have different levels of hierarchy called “scope”. The “scope” in Python defines the “hierarchy level” in which you search namespaces for certain “name- to-object” mappings. A scope represents the textual area of a Python program where a namespace is directly accessible.

Scope of objects and names

The scope of a variable determines the portion of the program where you can access a particular identi¬fier. There are two basic scopes of variables in Python:

  • Local scope
  • Global scope

Variables that are defined inside a function body have a local scope. In other words, it is local to that function and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, If you then try to access the variable x outside the function, it will give NameError.

  • A local scope refers to the local objects available in the current function.

Example
Demo of local scope.

def func1 ( ) :
x = 9 # local scope
print ( x )
func1 ( )RUN
>>>
9
>>>

Global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
Let us discuss the global scope of a variable in brief:

(a) The global names are variables assigned at the top level of the enclosing module file. It means that it is visible everywhere within the program.
(b) The global names must be declared only if they are assigned within a function.
(c) Global variables must be referenced within a function without being declared.

  • A global scope refers to the objects available through the code execution since their inception.

Example
Demo of global scope.

y=9 # Global scope
def func2 ( ):
print(y)
func2 ( )RUN
>>>
9
>>>

Example
Demo of local and global variables.

total = 0; # This is global variable.
# Function definition
def sum(arg1, arg2):
# Add both the parameters and return them
total = arg1 + arg2; # Here total is local variable
print(“Inside the function local total : “, total)
return total
# Now you can call
sum function sum(20, 40)
print(“Outside the function global total : “, total)RUN
>>>
Inside the function local total: 60
Outside the function global total : 0
>>>

Here, you just defined the variable name total twice. So, how does Python know which namespace it has to search if you want to print the value of the variable total? This is where Python’s LEGB-rule comes into play. The order for name resolution (for names inside a function) is local, enclosing function for nested def, global, and then the built-in namespaces (i.e., LEGB).

However, if you assign a new value to a name, a local name is created, which hides the global name. The global statement is necessary if you are changing the reference to an object (e.g. with an assignment).
In Example 4, to modify the contents of the array, the global statement is not needed because you are only modifying the object. Whereas in Example 5, you are modifying the reference to the variable, global is needed, otherwise, a local variable will be created inside the function.

If you want to print out the dictionary mapping of the global and local variables, you can use the functions global ( ) and local ( ).

Example
Demo of local variable.

>>> X = [ ]
>>> def myfun():
x.append(‘Hello’) # Don’t need global, no change of reference for x
>>> myfun ( )
>>> XRUN
>>>
[‘Hello’]
> > >

Example
Demo of global variable.

>>> X = 1
>>> def myfun ( ) :
global x
x = 5
>>> myfun ( )
>>> xRUN
>>>
5
> > >

The global keyword

In Python global keyword is used to a globally defined variable instead of locally defining them. This is useful when you want to change the value of a variable through a function. To use it, simply type global followed by the variable name, as shown in Figures 12.6 and 12.7.

Example
Demo of the global keyword.

x=10
def change(y):
global x #global keyword
x = y
change(11)
print (x)RUN
>>>
11
>>>

Example
Demo of global keyword

x = ” i ”
def outside ( ) :
x = ” j ”
def inside ( ) :
global x
x = ” k ”
print ( ” inside : ” , x )
inside ( )
print ( ” Outside : ” , x )
outside ( )
print ( ” global : ” , x )RUN
>>>
inside : k
outside : j
global : k
>>>

In Finger 12.7, using the global keyword, the x in inside( ) will refer to the global variable. That one will be changed, but not the one in outside( ), because you are only referring to the global x. The nonlocal keyword is useful in nested functions. It causes the variable to refer to the previously bound variable in the closest enclosing scope. In other words, it will prevent the variable from trying to bind locally first, and force it to go a level ‘higher up’. (See Figure 12.8).

Example
Demo of nonlocal keyword.

def outside ( ) :
x = 10
def inside ( ) :
nonlocal x
x = 11
print ( x )
inside ( )
print ( x )
outside ( )RUN
>>>
11
11
>>>

Example
Demo of nonlocal keyword

x = “i”
def outside():
x = “j”
def inside():
nonlocal x
x = “k”
print(“Inside, x)
inside ( )
print(“Outside:”, x)
outside ( )
print(“global, x)RUN
>>>
Inside: k
Outside: k
global: i
>>>

In Figure 12.9, using the nonlocal keyword, x in the inside( ) function should actually refer to the x defined in the outside() function, which is one level higher. So, x in both inside( ) and outside( ) is defined as “k”, because it could be accessed by inside( ).

Module Basics

A Python module is a file containing Python codes including statements, variables, functions, and classes. It shall be saved with a file extension of “.py”. The module name is the filename, i.e., a module shall be saved as “<module_name>.py”.

A module in Python is just a file containing Python definitions and statements.

Advantages of Python modules are:

  1. The module allows you to logically organize your Python codes.
  2. Groping related code into a module makes the code easier to understand and use.
  3. Similar types of attributes can be categorized and placed in a single module.
  4. The module provides a facility for the reusability of codes.

Module files as Namespaces

Namespaces are just containers for mapping names to objects. You know that everything in Python literals, lists, dictionaries, functions, classes, etc., is an object. Also, namespaces can exist independently from each other, and that they are structured in a certain hierarchy. The name references create or change local names by default. The global declarations are used to design assigned names to an enclosing module’s scope. In Python programming, all function names assigned inside a def statement are locals by default whereas the functions written in Python can use global but they must be declared as global.

  • A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.

Reloading Modules

As you know that, a module is loaded once despite the number of times it is imported into the Python source file. If you want to reload the already imported module to re-execute the top-level code, Python provides you the reload ( ) function. This is useful if you have edited the module source file 5. using an external editor and want to try out the new version without leaving the Python interpreter. The syntax to use the reload ( ) function is as below: reload(<module-name>)

Leave a Reply

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