1.2.5. Reusing code: scripts and modules

For now, we have typed all instructions in the interpreter. For longer sets of instructions we need to change track and write the code in text files (using a text editor), that we will call either scripts or modules. Use your favorite text editor (provided it offers syntax highlighting for Python), or the editor that comes with the Scientific Python Suite you may be using.

1.2.5.1. Scripts

Tip

Let us first write a script, that is a file with a sequence of instructions that are executed each time the script is called. Instructions may be e.g. copied-and-pasted from the interpreter (but take care to respect indentation rules!).

The extension for Python files is .py. Write or copy-and-paste the following lines in a file called test.py

message = "Hello how are you?"
for word in message.split():
print(word)

Tip

Let us now execute the script interactively, that is inside the Ipython interpreter. This is maybe the most common use of scripts in scientific computing.

Note

in Ipython, the syntax to execute a script is %run script.py. For example,

In [1]: %run test.py
Hello
how
are
you?
In [2]: message
Out[2]: 'Hello how are you?'

The script has been executed. Moreover the variables defined in the script (such as message) are now available inside the interpreter’s namespace.

Tip

Other interpreters also offer the possibility to execute scripts (e.g., execfile in the plain Python interpreter, etc.).

It is also possible In order to execute this script as a standalone program, by executing the script inside a shell terminal (Linux/Mac console or cmd Windows console). For example, if we are in the same directory as the test.py file, we can execute this in a console:

$ python test.py
Hello
how
are
you?

Tip

Standalone scripts may also take command-line arguments

In file.py:

import sys
print(sys.argv)
$ python file.py test arguments
['file.py', 'test', 'arguments']

Warning

Don’t implement option parsing yourself. Use a dedicated module such as argparse.

1.2.5.2. Importing objects from modules

In [3]: import os
In [4]: os
Out[4]: <module 'os' (frozen)>
In [5]: os.listdir('.')
Out[5]:
['systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-systemd-logind.service-b9Rzjz',
'profile_aigtsgcb',
'profile_mmurb8al',
'profile_xvonz9yf',
'profile_4hs_w_mh',
'dotnet-diagnostic-1659-25920-socket',
'clr-debug-pipe-1659-25920-out',
'profile_lgnuvwyt',
'profile_xcrx5vq8',
'profile_r8j35hgb',
'systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-chrony.service-fI5AKM',
'systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-haveged.service-mIZITo',
'snap-private-tmp',
'profile_4ikxwrj1',
'profile_rts6jo7t',
'profile_sxoh34un',
'.Test-unix',
'profile_ho8psflt',
'profile_czgm0fx3',
'profile_fgaa3812',
'profile_31ggph82',
'profile_ecrzkms3',
'profile_4oyg93xr',
'dotnet-diagnostic-606-982-socket',
'profile_1_9wxfx4',
'profile_aq6t3dxq',
'profile_pulh7uyz',
'profile_5_tt0l9w',
'clr-debug-pipe-606-982-out',
'.X11-unix',
'.ICE-unix',
'.font-unix',
'profile_h7s5rvrk',
'profile_qsp3_q4p',
'profile_o23tpc6n',
'profile_wkzbriqc',
'clr-debug-pipe-606-982-in',
'profile_agvc7v4m',
'systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-systemd-resolved.service-LZYFSu',
'profile_kcc2n4g7',
'clr-debug-pipe-1641-25689-out',
'profile_9nz6obms',
'profile_z53xjajo',
'profile_ewil8srw',
'profile_bkzd2sj_',
'clr-debug-pipe-1641-25689-in',
'profile_zk2rhhsn',
'profile_aq3hxf0g',
'profile_pu0vk1xu',
'profile_dk_b2g1k',
'profile_9fsj2k75',
'profile_0m71mlo2',
'clr-debug-pipe-1659-25920-in',
'profile_q3_da92m',
'.XIM-unix',
'profile_o6gr3f53',
'profile_ud5som2r',
'www-data-temp-aspnet-0',
'profile_0h7ljo86',
'profile_4r0wr_uf',
'profile_evxijf16',
'profile_m23qdbuk',
'profile_kxp0ehvn',
'profile__2tb6hf4',
'profile_iatzm6x3',
'profile_r3xscs1p',
'profile_tk9omgbb',
'profile_37leef3_',
'profile_om7err07',
'profile_t7peg56y',
'profile_30z2ds56',
'profile_nnurehu6',
'profile__y38edp6',
'dotnet-diagnostic-1641-25689-socket',
'profile_4esqldpc',
'profile_az_xm5hv',
'profile_zzggzu6j',
'profile_j48t_pkc',
'profile_sjaajzbs']

And also:

In [6]: from os import listdir

Importing shorthands:

In [7]: import numpy as np

Warning

from os import *

This is called the star import and please, Do not use it

  • Makes the code harder to read and understand: where do symbols come from?

  • Makes it impossible to guess the functionality by the context and the name (hint: os.name is the name of the OS), and to profit usefully from tab completion.

  • Restricts the variable names you can use: os.name might override name, or vise-versa.

  • Creates possible name clashes between modules.

  • Makes the code impossible to statically check for undefined symbols.

Tip

Modules are thus a good way to organize code in a hierarchical way. Actually, all the scientific computing tools we are going to use are modules:

>>> import numpy as np # data arrays
>>> np.linspace(0, 10, 6)
array([ 0., 2., 4., 6., 8., 10.])
>>> import scipy as sp # scientific computing

1.2.5.3. Creating modules

Tip

If we want to write larger and better organized programs (compared to simple scripts), where some objects are defined, (variables, functions, classes) and that we want to reuse several times, we have to create our own modules.

Let us create a module demo contained in the file demo.py:

"A demo module."
def print_b():
"Prints b."
print("b")
def print_a():
"Prints a."
print("a")
c = 2
d = 2

Tip

In this file, we defined two functions print_a and print_b. Suppose we want to call the print_a function from the interpreter. We could execute the file as a script, but since we just want to have access to the function print_a, we are rather going to import it as a module. The syntax is as follows.

In [8]: import demo
In [9]: demo.print_a()
a
In [10]: demo.print_b()
b

Importing the module gives access to its objects, using the module.object syntax. Don’t forget to put the module’s name before the object’s name, otherwise Python won’t recognize the instruction.

Introspection

In [11]: demo?
Type: module
Base Class: <type 'module'>
String Form: <module 'demo' from 'demo.py'>
Namespace: Interactive
File: /home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/demo.py
Docstring:
A demo module.
In [12]: who
demo
In [13]: whos
Variable Type Data/Info
------------------------------
demo module <module 'demo' from 'demo.py'>
In [14]: dir(demo)
Out[14]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'c',
'd',
'print_a',
'print_b']
In [15]: demo.<TAB>
demo.c demo.print_a demo.py
demo.d demo.print_b demo.pyc

Importing objects from modules into the main namespace

In [16]: from demo import print_a, print_b
In [17]: whos
Variable Type Data/Info
--------------------------------
demo module <module 'demo' from 'demo.py'>
print_a function <function print_a at 0xb7421534>
print_b function <function print_b at 0xb74214c4>
In [18]: print_a()
a

Warning

Module caching

Modules are cached: if you modify demo.py and re-import it in the old session, you will get the old one.

Solution:

In [10]: importlib.reload(demo)

1.2.5.4. ‘__main__’ and module loading

Tip

Sometimes we want code to be executed when a module is run directly, but not when it is imported by another module. if __name__ == '__main__' allows us to check whether the module is being run directly.

File demo2.py:

def print_b():
"Prints b."
print("b")
def print_a():
"Prints a."
print("a")
# print_b() runs on import
print_b()
if __name__ == "__main__":
# print_a() is only executed when the module is run directly.
print_a()

Importing it:

In [19]: import demo2
b
In [20]: import demo2

Running it:

In [21]: %run demo2
b
a

1.2.5.5. Scripts or modules? How to organize your code

Note

Rule of thumb

  • Sets of instructions that are called several times should be written inside functions for better code reusability.

  • Functions (or other bits of code) that are called from several scripts should be written inside a module, so that only the module is imported in the different scripts (do not copy-and-paste your functions in the different scripts!).

How modules are found and imported

When the import mymodule statement is executed, the module mymodule is searched in a given list of directories. This list includes a list of installation-dependent default path (e.g., /usr/lib64/python3.11) as well as the list of directories specified by the environment variable PYTHONPATH.

The list of directories searched by Python is given by the sys.path variable

In [22]: import sys
In [23]: sys.path
Out[23]:
['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python312.zip',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/lib-dynload',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages']

Modules must be located in the search path, therefore you can:

  • write your own modules within directories already defined in the search path (e.g. $HOME/.venv/lectures/lib64/python3.11/site-packages). You may use symbolic links (on Linux) to keep the code somewhere else.

  • modify the environment variable PYTHONPATH to include the directories containing the user-defined modules.

    Tip

    On Linux/Unix, add the following line to a file read by the shell at startup (e.g. /etc/profile, .profile)

    export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules
    

    On Windows, https://support.microsoft.com/kb/310519 explains how to handle environment variables.

  • or modify the sys.path variable itself within a Python script.

    Tip

    import sys
    
    new_path = '/home/emma/user_defined_modules'
    if new_path not in sys.path:
    sys.path.append(new_path)

    This method is not very robust, however, because it makes the code less portable (user-dependent path) and because you have to add the directory to your sys.path each time you want to import from a module in this directory.

See also

See https://docs.python.org/3/tutorial/modules.html for more information about modules.

1.2.5.6. Packages

A directory that contains many modules is called a package. A package is a module with submodules (which can have submodules themselves, etc.). A special file called __init__.py (which may be empty) tells Python that the directory is a Python package, from which modules can be imported.

$ ls
_build_utils/ fft/ _lib/ odr/ spatial/
cluster/ fftpack/ linalg/ optimize/ special/
conftest.py __init__.py linalg.pxd optimize.pxd special.pxd
constants/ integrate/ meson.build setup.py stats/
datasets/ interpolate/ misc/ signal/
_distributor_init.py io/ ndimage/ sparse/
$ cd ndimage
$ ls
_filters.py __init__.py _measurements.py morphology.py src/
filters.py _interpolation.py measurements.py _ni_docstrings.py tests/
_fourier.py interpolation.py meson.build _ni_support.py utils/
fourier.py LICENSE.txt _morphology.py setup.py

From Ipython:

In [24]: import scipy as sp
In [25]: sp.__file__
Out[25]: '/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/scipy/__init__.py'
In [26]: sp.version.version
Out[26]: '1.14.1'
In [27]: sp.ndimage.morphology.binary_dilation?
Signature:
sp.ndimage.morphology.binary_dilation(
input,
structure=None,
iterations=1,
mask=None,
output=None,
border_value=0,
origin=0,
brute_force=False,
)
Docstring:
Multidimensional binary dilation with the given structuring element.
...

1.2.5.7. Good practices

  • Use meaningful object names

  • Indentation: no choice!

    Tip

    Indenting is compulsory in Python! Every command block following a colon bears an additional indentation level with respect to the previous line with a colon. One must therefore indent after def f(): or while:. At the end of such logical blocks, one decreases the indentation depth (and re-increases it if a new block is entered, etc.)

    Strict respect of indentation is the price to pay for getting rid of { or ; characters that delineate logical blocks in other languages. Improper indentation leads to errors such as

    ------------------------------------------------------------
    
    IndentationError: unexpected indent (test.py, line 2)

    All this indentation business can be a bit confusing in the beginning. However, with the clear indentation, and in the absence of extra characters, the resulting code is very nice to read compared to other languages.

  • Indentation depth: Inside your text editor, you may choose to indent with any positive number of spaces (1, 2, 3, 4, …). However, it is considered good practice to indent with 4 spaces. You may configure your editor to map the Tab key to a 4-space indentation.

  • Style guidelines

    Long lines: you should not write very long lines that span over more than (e.g.) 80 characters. Long lines can be broken with the \ character

    >>> long_line = "Here is a very very long line \
    
    ... that we break in two parts."

    Spaces

    Write well-spaced code: put whitespaces after commas, around arithmetic operators, etc.:

    >>> a = 1 # yes
    
    >>> a=1 # too cramped

    A certain number of rules for writing “beautiful” code (and more importantly using the same conventions as anybody else!) are given in the Style Guide for Python Code.