Python Programming/Modules

From Wikiversity
Jump to navigation Jump to search

This lesson introduces Python modules and packages.

Objectives and Skills[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Modules
    • Byte-compiled .pyc files
    • The from ..import ..statement
    • A module's __name__ and custom modules
    • The dir function and packages

Readings[edit | edit source]

  1. Wikipedia: Modular programming
  2. Python.org: Modules

Multimedia[edit | edit source]

  1. YouTube: Python Modules

Examples[edit | edit source]

Modules[edit | edit source]

Modules are regular Python .py files that define functions or classes that may be imported and reused in other Python programs.[2]

functions.py:

"""This module contains functions that will be imported and reused."""

def function1():
    """Function1"""
    print("In function1")

classes.py:

"""This module contains classes that will be imported and reused."""

class Class1(object):
    """Class1"""

    def method1(self):
        """method1"""
        print("In method1")

The import Statement[edit | edit source]

The import statement finds a module, loads it, initializes it if necessary, and defines a name or names which are used to reference code in the module.[3]

import functions
import classes

functions.function1()

class1 = classes.Class1()
class1.method1()

Output:

In function1
In method1

The from ... import Statement[edit | edit source]

The from...import statement finds a module, loads it, initializes it if necessary, and then adds module references to the local namespace, allowing functions and classes to be accessed without a module reference.[4] Use of import rather than from...import is preferred. While from ... import supports an * option to import all references rather than naming specific functions or classes, this use is discouraged.[5]

from functions import function1
from classes import Class1

function1()

class1 = Class1()
class1.method1()

Output:

In function1
In method1

Module Name[edit | edit source]

When modules are imported, the __name__ variable is set to the name of the module. When the Python interpreter runs a module directly, the __name__ variable is set to "__main__". This allows a module designed to be imported to add a main() function that will only execute when the module is run directly.[6][7]

def main():
    """Used to demonstrate and/or test module code."""
    ...

if __name__ == "__main__":
    main()

The dir() Function[edit | edit source]

The dir() function returns the list of names in the current local scope, or for the object, if specified.[8]

print(dir())

Activities[edit | edit source]

Tutorials[edit | edit source]

  1. Complete one or more of the following tutorials:

Practice[edit | edit source]

  1. Create a module with at least one function or class. In a separate module, import the first module and use the dir() function to display the names in the local scope. Then import the first module using from ... import * and use the dir() function to display the names in the local scope. Compare the difference between import and from ... import.
  2. Modify one or more of the Python Programming/Functions#Practice activities so that the function code is in a different module. Use import to import the module and then call the function.
  3. Modify one or more of the Python Programming/Classes#Practice activities so that the class code is in a different module. Use import to import the module and then instantiate and use the class.
  4. Review Python.org: os. Import the Python os library and then use getlogin() and uname() to display the current username, computer name, operating system, and version.

Lesson Summary[edit | edit source]

  • Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.[9]
  • Modules are regular Python .py files that define functions or classes that may be imported and reused in other Python programs.[10]
  • The import statement finds a module, loads it, initializes it if necessary, and defines a name or names which are used to reference code in the module.[11]
  • The from...import statement finds a module, loads it, initializes it if necessary, and then adds module references to the local namespace, allowing functions and classes to be accessed without a module reference.[12]
  • Use of import rather than from...import is preferred.[13]
  • While from ... import supports an * option to import all references rather than naming specific functions or classes, this use is discouraged.[14]
  • When modules are imported, the __name__ variable is set to the name of the module. When the Python interpreter runs a module directly, the __name__ variable is set to "__main__".[15][16]
  • __name__ allows a module designed to be imported to add a main() function that will only execute when the module is run directly.[17][18]
  • To speed up loading modules, Python caches the compiled bytecode version of each module.[19]
  • A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.[20]
  • Python comes with a library of standard modules.[21]
  • The sys module provides access to operating system or operating environment variables and functions.[22]
  • The dir() function returns the list of names in the current local scope, or for the object, if specified.[23]

Key Terms[edit | edit source]

bytecode
A form of instruction set designed for efficient execution by a software interpreter.[24]

Review Questions[edit | edit source]

Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. Modular programming is _____.
    Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.
  2. Python modules are _____.
    Python modules are regular Python .py files that define functions or classes that may be imported and reused in other Python programs.
  3. The import statement _____.
    The import statement finds a module, loads it, initializes it if necessary, and defines a name or names which are used to reference code in the module.
  4. The from...import statement _____.
    The from...import statement finds a module, loads it, initializes it if necessary, and then adds module references to the local namespace, allowing functions and classes to be accessed without a module reference.
  5. When importing Python modules, use of _____ rather than _____ is preferred.
    When importing Python modules, se of import rather than from...import is preferred.
  6. While from ... import supports _____, this use is discouraged.
    While from ... import supports an * option to import all references rather than naming specific functions or classes, this use is discouraged.
  7. When modules are imported, the __name__ variable is set to _____. When the Python interpreter runs a module directly, the __name__ variable is set to _____.
    When modules are imported, the __name__ variable is set to the name of the module. When the Python interpreter runs a module directly, the __name__ variable is set to "__main__".
  8. __name__ allows a module designed to be imported to add _____.
    __name__ allows a module designed to be imported to add a main() function that will only execute when the module is run directly.
  9. To speed up loading modules, Python _____.
    To speed up loading modules, Python caches the compiled bytecode version of each module.
  10. A program doesn’t run any faster when it is read from a _____ file than when it is read from a _____ file; the only thing that’s faster about _____ files is _____.
    A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.
  11. Python comes with _____.
    Python comes with a library of standard modules.
  12. The sys module _____.
    The sys module provides access to operating system or operating environment variables and functions.
  13. The dir() function _____.
    The dir() function returns the list of names in the current local scope, or for the object, if specified.

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]