Skip to Main Content

Downloading and Installing Packages

Modules and Packages

A module is simply a python file full of functions, classes, and variables; like all python files, it has the .py extension. We can use modules to group related codes. The dir() function can be used to see which functions are implemented in a module and help() can be used to see more detail about the function we want to use. Here is an example:

import math
dir(math)
Output: ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 
'asinh','atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees',
 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp',
 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

A package is a directory that consists of multiple modules and sub-packages.

dir() and help() can be used to explore packages as well.

Import modules or packages

Python provides several ways to import modules; we introduce three ways below.

  • import math imports the module math. After we run this statement, we can use math.name to refer to functions defined in module math. For example, math.sin can be used to evaluate the value of trigonometric function sine and math.sin(math.pi/2) = 1.
  • from math import * imports the module math. After we run this statement, we can simply use functions defined in module math without specifying the module they came from. For example, sin(pi/2) will evaluate sine of pi/2.
  • from math import sin, cos imports the module math. After we run this statement, we can use sine and cosine without specifying the module, but not other functions in this module. For example, sin(math.pi/2) will evaluate sine of pi/2.

Which way is best?

We use modules in different ways depending on our needs. Sometimes, it is better to use import module, especially if we are using two modules that have a function of the same name - using this method will allow us to distinguish between the two. For example, numpy.sin can evaluate values of sine of an array but math.sin can only be used to evaluate the sine of a single value. An alternate example is the pi function: you can use math.pi, numpy.pi or scipy.pi and they all give the same value for pi. Because all three modules give pi the same value, we can choose one and have easy access to pi without having to import or specify another module.

Center for Analytics and Data Science

165 McVey
105 Tallawanda Rd
Oxford, OH 45056