Custom libraries#

When programming python for some time, you may be using again and again the same code. You could copy&paste it from jupyter notebook to jupyter notebook. However, notebooks are not meant to hold many functions. Notebooks are meant to show short and concise examples of code. Thus, in order to organize our code, we can put functions we use more often into a python file, a custom library, and then import the functions.

See also:

Within the same folder, there exists a my_library.py file. It contains two functions. Let’s import them and use them:

from my_library import square
square(5)
25
from my_library import *
wuzzle(5)
2.449489742783178

When maintaining your own library of functions, make sure that the functions have reasonable names and useful docstrings. You may otherwise be confused about your own code later on.

This is a good example:

print(square.__doc__)
    Squares a number by multiplying it with itself  and returns its result.
    

This is a bad example:

print(wuzzle.__doc__)
    The wuzzle function manipulates a number in a magic way and returns the result.
    

Modifying code in custom libraries#

If you modify code in a python library file side-by-side with the code in a notebook, you may have restart your notebook after modifying the library file. You can do this in the menu Kernel > Restart & Run All.

Exercise#

Create an own library and write a function that can compute the Euclidean distance between two points. The point coordinates are given as tuples. Hint: You will need a for-loop in this function that iterates pair-wise over the two coordinates:

p = (1.5, 6.4, 7.3)
q = (3.4, 1.0, 0.9)