Modules

  • A python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We may have a runnable code inside the python module.
  • Modules in Python provides us the flexibility to organize the code in a logical way.
  • To use the functionality of one module into another, we must have to import the specific module.
  • Example
  • In this example, we will create a module named as file.py which contains a function func that contains a code to print some message on the console.
  • Let's create the module named as file.py.

  • Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.

LOADING THE MODULE IN OUR PYTHON CODE

  • We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.

    1. The import statement
    2. The from-import statement

THE IMPORT STATEMENT

  • The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the functionality of any python source file by importing that file as the module into another python source file.
  • We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into our file.
  • The syntax to use the import statement is given below.

  • Hence, if we need to call the function displayMsg() defined in the file file.py, we have to import that file as a module into our module as shown in the example below.
  • Example:

  • Output:


VARIABLES IN MODULE

  • The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
  • Example: Save this code in the file mymodule.py

  • Import the module named mymodule, and access the person1 dictionary: demo_module2.py


  • Output:

THE FROM-IMPORT STATEMENT

  • Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from-import statement. The syntax to use the from-import statement is given below.

  • Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.
  • calculation.py

  • Main.py:

  • Output:

  • Example
  • mymodule.py 
  • Main.py:

  • Output:

  • Note: When importing using the from keyword, do not use the module name when referring to elements in the module.
  • Example: person1["age"], not mymodule.person1["age"]
  • The from...import statement is always better to use if we know the attributes to be imported from the module in advance. It doesn't let our code to be heavier. We can also import all the attributes from a module by using *.
  • Consider the following syntax.

RENAMING A MODULE

  • Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our python source file.
  • You can create an alias when you import a module, by using the as keyword
  • The syntax to rename a module is given below.

  • Example

  • Output:

BUILT-IN MODULES

  • There are several built-in modules in Python, which you can import whenever you like.
  • Example: Import and use the platform module:

  • Output:

LOCATING MODULES

  • When you import a module, the Python interpreter searches for the module in the following sequences −
    • The current directory.
    • If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.
    • If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.
  • The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.

THE PYTHONPATH VARIABLE

  • The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.
  • Here is a typical PYTHONPATH from a Windows system −

  • And here is a typical PYTHONPATH from a UNIX system −

NAMESPACES AND SCOPING

  • Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).
  • A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.
  • Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
  • Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
  • Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
  • The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.
  • For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable.
  • However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
  • Example:

THE DIR( ) FUNCTION

  • The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and functions defined in this module.
  • Consider the following example.

  • When the above code is executed, it produces the following result −

  • Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.

SCOPE OF VARIABLES

  • In Python, variables are associated with two types of scopes. All the variables defined in a module contain the global scope unless or until it is defined within a function.
  • All the variables defined inside a function contain a local scope that is limited to this function itself. We can not access a local variable globally.
  • If two variables are defined with the same name with the two different scopes, i.e., local and global, then the priority will always be given to the local variable.

THE GLOBALS() AND LOCALS() FUNCTIONS

  • Example

  • Output:

  • The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.
  • If locals() is called from within a function, it will return all the names that can be accessed locally from that function.
  • If globals() is called from within a function, it will return all the names that can be accessed globally from that function.
  • The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.

THE RELOAD() FUNCTION

  • When the module is imported into a script, the code in the top-level portion of a module is executed only once.
  • Therefore, if you want to re-execute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −

  • For example, to reload the module calculation defined in the previous example, we must use the following line of code.

PYTHON PACKAGES

  • The packages in python facilitate the developer with the application development environment by providing a hierarchical directory structure where a package contains sub-packages, modules, and sub-modules. The packages are used to categorize the application level code efficiently.
  • Let's create a package named Employees in your home directory.
  • Consider the following steps.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name ITEmployees.py on the path /home/ Employees.
  • ITEmployees.py
3. Similarly, create one more python file with name BPOEmployees.py and create a function getBPONames().
4. Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a package, we need to include one more file here, that is __init__.py which contains the import statements of the modules defined in this directory.
  • __init__.py
5. Now, the directory Employees has become the package containing two python modules. Here we must notice that we must have to create __init__.py inside a directory to convert this directory to a package.
6. To use the modules defined inside the package Employees, we must have to import this in our python source file. Let's create a simple python source file at our home directory (/home) which uses the modules defined in this package.
  • Test.py
  • Output:

  • We can have sub-packages inside the packages. We can nest the packages up to any level depending upon the application requirements.
  • The following image shows the directory structure of an application Library management system which contains three sub-packages as Admin, Librarian, and Student. The sub-packages contain the python modules.

Comments

Popular posts from this blog

Control Structures

Classes and Objects