Python Modules and Packages

CSC 223 - Advanced Scientific Programming

Modules and Packages

  • The Python standard library includes may useful tools for a wide range of tasks.

  • This feature is sometimes called “batteries included”.

  • Python organizes libraries into modules that can be used in Python scripts.

  • There are also many third-party tools and packages that offer more specialized functionality.

The import Statement

  • The import statement loads built-in and third party modules and can be used in various ways:

    • Explicit import (preserves the modules content in a namespace)

      import math
      math.cos(math.pi)
    • Explicit import by alias

      import math as m
      m.cos(m.pi)
    • Explicit import of module contents

      from math import cos, pi
      cos(pi)
    • Implicit import of module contents

      from math import *
      cos(pi)

Python Module Conventions

  • A Python script can be treated as a module (imported into another Python program) or as a stand alone program.

  • A runnable script typically has a this statement

    if __name__ == '__main__':
        # statements that should not
        # be executed when imported
        # into another file
  • The code in the main block will not be executed when the file is imported.

Useful Standard Library Modules

  • os and sys: tools for interfacing with the operating system.

  • math: mathematical functions and operations

  • itertools: tools for constructing and interacting with iterators and generators.

  • random: tools for generating pseudorandom numbers

  • json and csv: tools for reading file formats.

Third-Party Modules

  • Python has modules that are not included in the standard library.

  • These modules can be imported like the standard library modules provided that they are installed.

  • Useful third-party modules:

    • numpy: provides an efficient way to store and manipulate multi-dimensional dense arrays.

    • pandas: provides a labeled interface to multi-dimensional data.

    • matplotlib: provides a way to create scientific visualizations.