XClose

COMP0233: Research Software Engineering With Python

Home
Menu

Using Libraries

Import

To use a function or type from a python library, rather than a built-in function or type, we have to import the library.

In [1]:
math.sin(1.6)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[1], line 1
----> 1 math.sin(1.6)

NameError: name 'math' is not defined
In [2]:
import math
In [3]:
math.sin(1.6)
Out[3]:
0.9995736030415051

We call these libraries modules:

In [4]:
type(math)
Out[4]:
module

The tools supplied by a module are attributes of the module, and as such, are accessed with a dot.

In [5]:
dir(math)
Out[5]:
['__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'cbrt',
 'ceil',
 'comb',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'dist',
 'e',
 'erf',
 'erfc',
 'exp',
 'exp2',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'isqrt',
 'lcm',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'nextafter',
 'perm',
 'pi',
 'pow',
 'prod',
 'radians',
 'remainder',
 'sin',
 'sinh',
 'sqrt',
 'sumprod',
 'tan',
 'tanh',
 'tau',
 'trunc',
 'ulp']

They include properties as well as functions:

In [6]:
math.pi
Out[6]:
3.141592653589793

You can find out where on your storage medium a library has been imported from:

In [7]:
print(math.__file__)
/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so

Some modules do not use the __file__ attribute so you may get an error:

AttributeError: module 'modulename' has no attribute '__file__'

If this is the case print(modulename) should display a description of the module object which will include an indication if the module is a 'built-in' module written in C (in which case the file path will not be specified) or the file path to the module otherwise.

In [8]:
print(math)
<module 'math' from '/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>

Note that import does not install libraries from PyPI. It just makes them available to your current notebook session, assuming they are already installed. Installing libraries is harder, and we'll cover it later. So what libraries are available? Until you install more, you might have just the modules that come with Python, the standard library.

Supplementary Materials: Review the list of standard library modules.

If you installed via Anaconda, then you also have access to a bunch of modules that are commonly used in research.

Supplementary Materials: Review the list of modules that are packaged with Anaconda by default on different architectures (choose your operating system and see which packages have a tick mark).

We'll see later how to add more libraries to our setup.

Why bother?

Why bother with modules? Why not just have everything available all the time?

The answer is that there are only so many names available! Without a module system, every time I made a variable whose name matched a function in a library, I'd lose access to it. In the olden days, people ended up having to make really long variable names, thinking their names would be unique, and they still ended up with "name clashes". The module mechanism avoids this.

Importing from modules

Still, it can be annoying to have to write math.sin(math.pi) instead of sin(pi). Things can be imported from modules to become part of the current module:

In [9]:
import math

print(math.sin(math.pi))
1.2246467991473532e-16
In [10]:
from math import sin

print(sin(math.pi))
1.2246467991473532e-16

Importing one-by-one like this is a nice compromise between typing and risk of name clashes.

It is possible to import everything from a module, but you risk name clashes.

In [11]:
pi = "pie"


def sin(x):
    print(f"eat {x}")

print(sin(pie))
    
from math import *

print(sin(pi))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[11], line 7
      4 def sin(x):
      5     print(f"eat {x}")
----> 7 print(sin(pie))
      9 from math import *
     11 print(sin(pi))

NameError: name 'pie' is not defined

Import and rename

You can rename things as you import them to avoid clashes or for typing convenience

In [12]:
import math as m

print(m.cos(0))
1.0
In [13]:
pi = 3
from math import pi as realpi

print(sin(pi), sin(realpi))
eat 3
eat 3.141592653589793
None None