Importing functions from modules

While there are a good number of built-in functions and types, and you can go a long way without needing anything more, they are ultimately limited. Luckily, Python has a “batteries included” philosophy and provides a lot of additional functionality which can be explored in The Python Standard Library.

The functionality provided by the Standard Library is provided in a series of modules, each of which serves a particular purpose. The modules in the Standard Library are always installed in any version of Python you have. Note that even though they are always accessible, they do not count as “built-in” as in Python terms, that means something which you can use without having to access any extra modules.

The math module

Let’s start by looking at one of the modules, the “math — Mathematical functions” module. This module provides a bunch of mathematical tools such as averages, trigonometry etc.

You can get access to the module by importing it by name:

import math

Once it is imported, you can use any of the functions inside it by typing the name of the module, followed by a dot, followed by the name of the function. So to call the square root function you would do:

imports.py
import math

print(math.sqrt(25))
5.0

You can think of this as saying “from the math module that I’ve just imported, get the sqrt function and call it”.

Alternatively, if you want to grab a specific function out of a module so that you can call it without specifying the module name, you can do:

imports.py
from math import sqrt

print(sqrt(25))
5.0

Note that we have seen two examples of places where dot . is used when calling functions in Python:

  1. calling a method on a variable like with my_list.append() or my_string.split(),
  2. calling a function from an imported module like math.sqrt().

In both these cases the dot is doing a very similar job. It’s saying “look inside the thing on the left of the dot for a thing called …”. In some cases, it’s looking inside a data type, and in other it’s looking inside a module.

Exercise

We saw earlier how to check our current working directory in the Command Prompt/Terminal using cd (Windows) and pwd (MacOS and Linux). Using the The Python Standard Library, find a function that returns the working directory in Python.

One possible solution is to use the module os - Miscellaneous operating system interfaces.

import os

current_directory = os.getcwd()
print("CWD:", current_directory)
CWD: /Users/JGI/Training/Python/intermediate-python/