Python – Modules

Course Curriculum

Python – Modules

As your program gets longer, you may want to split it into several files for easier maintenance.
You may also want to use a handy function that you’ve written in several programs without copying
its definition into each program.
To support this, Python has a way to put definitions in a file and use them in a script or in an
interactive instance of the interpreter. Such a file is called a module; definitions from a module
can be imported into other modules or into the main module (the collection of variables that you
have access to in a script executed at the top level and in calculator mode).
A module is a file containing Python definitions and statements. The file name is the module name
with the suffix .py appended. Within a module, the module’s name (as a string) is available as the
value of the global variable name.
When the interpreter executes the import statement, it searches for module in a list of
directories assembled from the following sources:

  • The directory from which the input script was run or the current directory if the interpreter is
    being run interactively
  • The list of directories contained in the PYTHONPATH environment variable, if it is set. (The
    format for PYTHONPATH is OS-dependent but should mimic the PATH environment variable.)
  • An installation-dependent list of directories configured at the time Python is installed

    Example

    we have a file called module.py which has following content:

    def sum(num1,num2):
    return num1 + num2;
    def areaOfRectangle(height,width):
    return 2*height*width;

    The import Statement

    You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax −

    import module1[, module2[,... moduleN]

    When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module module.py, you need to put the following command at the top of the script −

    import module
    print(module.sum(5,8))

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

    13

    A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

    The from...import Statement

    Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −

    from modname import name1[, name2[, ... nameN]]

    For example, to import the function fibonacci from the module fib, use the following statement −

    from fib import fibonacci

    This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.

    The from...import * Statement

    It is also possible to import all names from a module into the current namespace by using the following import statement −

    from modname import *

    This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

    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 −

    set PYTHONPATH = c:python20lib;

    And here is a typical PYTHONPATH from a UNIX system −

    set PYTHONPATH = /usr/local/lib/python

    The dir( ) Function

    The dir() built-in function returns a sorted list of strings containing the names defined by a module.
    The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −

    # Importing module module
    import module
    print(dir(module))

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

    ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'areaOfRectangle', 'sum']

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

    The globals() and locals() Functions

    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 reexecute 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 −

    reload(module_name)

    Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −

    reload(sum)

    Packages in Python

    A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

    def english():
    print("this is english book")

    Similar way, we have another two files having different functions with the same name as above −

  • Book/maths.py file having function maths()
  • Book/physics.py file having function physics()
    Now, create one more file init.py in Book directory −
  • Book/init.py
    To make all of your functions available when you've imported Phone, you need to put explicit import statements in init.py as follows −

    from english import english
    from maths import maths
    from physics import physics

    After you add these lines to init.py, you have all of these classes available when you import the Phone package.

    # Now import your Book Package.
    import Book
    Book.english()
    Book.maths()
    Book.physics()

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

    this is english book
    this is maths book
    this is physics book

    In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.

Python – Functions (Prev Lesson)
(Next Lesson) Python – Files I/O
', { 'anonymize_ip': true });