NB: Importing Functions

Programming for Data Science

Importing

Previously we saw that we can extend the functions available to use in a Python program by importing them.

For example, we imported the Math module to make its log function available.

import math

In this notebook, we cover some basic properties of import statements.

We’ll go into greater detail when we cover Modules.

Quick Example

Recall that calling a function from the import math object is straightforward:

For example, to get the square root of \(12\) we can now do this:

import math

math.sqrt(12)
3.4641016151377544
math.floor(2.5)
2

Here’s an example using the Random module.

import random
random.random()
0.602481588733838
random.randint(1, 100)
8

Dot Notation

We call functions from imported modules by object using “dot” notation.

Importing More than One Module

You can import as many modules into your code as you’d like.

We can do this as follows:

import math, random

Or one import per line:

import math
import random

It is generally preferred to separate import statements by line.

This makes you code more readable and modular.

Regarding modularity, with one import per line, you can do things like this:

import math
# import random

Here’s we quickly comment out an import statement without having to rewrite our code.

It is also a standard practice to put all of your import statements at the very top of your code, before any other code.

Importing Specific Functions

If you know what to use a specific function from an imported module, you can import them directly, like so:

from math import sqrt
sqrt(99)
9.9498743710662

This reduces the memory used by the library in your program, since it is not importing all of the module’s code.

It also allows you to call the function directly, with the object dot notation.

Aliasing Imported Functions

You can alias the imported function.

This avoids having the function name conflict with an existing function in your program.

from math import sqrt as SquareRoot
SquareRoot(65000)
254.95097567963924