Functions and libraries

Programming – Session 2

  • Functions
  • Visibility of variables
  • Code organization
  • Modules and virtual environments

Functions

Definitions

Definition and use

Function is a key concept to ensure the readability and reusability of your code. Functions allow to:

  • Factorize (regroup) statements that perform a specific task.
  • Be called on demand anywhere in your code.
  • Be tested independently to then be safely reused and shared.

A function can take parameters and returns a value.

Algorithmic statements involving functions

  • Defining functions
  • Calling functions

Functions

Defining functions

Defining functions in Python

The name of a function, the number and types of its arguments, and the type of its returned value(s) is generally called the “signature”, or the “prototype” of a function.

def func_name (param_1: int, param_2: int) -> float:

    """
        This is an example of how to define a function in Python.
        Here, we use type hinting to indicate to the user how they should use it. 
        In:
            * param_1: The first argument to take as an input.
            * param_2: The second argument to take as an input.
        Out:
            * A result computed by the function.
    """

    # Do something
    ...

    # Return something
    return result

Functions

Calling a function

Calling a function in Python

Once defined, a function can be called from anywhere just using its name and passing a value for each expected parameter. Values given in a function call are called “actual parameters” or “arguments”.

def func_name (param_1: int = 123, param_2: int = 456) -> float:

    """
        This is an example of how to define a function in Python.
        Here, we use type hinting to indicate to the user how they should use it. 
        In:
            * param_1: The first argument to take as an input.
            * param_2: The second argument to take as an input.
        Out:
            * A result computed by the function.
    """

    # Do something
    ...

    # Return something
    return result



# Call the function
res : float = func_name(4, 2)

Functions

Visibility of variables accross functions

The visibility of a variable determines its lifetime, and two types of visibility are considered in Python, namely local and global variables.

Local variables

Local variables are defined inside a function and not accessible outside it.

# Example function with two local variables
def example (a):
    b = 2
    print(a, b)

# Call it and try to access variables
example(1)
print(a, b) # -> NameError: name 'a' is not defined

Global variables

Global variables are defined outside all functions and accessible anywhere in the code.

# Define a global variable
a = 1

# Example function with a local variable, also named "a"
def example ():
    a = 2
    print(a)

# See what we got
print(a)
example()
print(a)

Code organization

Files and modules

Importing modules

Functions may be thematically regrouped into separated files my_functions.py (named modules). To use the functions located in my_functions.py, it has to be imported:

# Let's assume the file is not in the path
# For instance, assume it's in a directory "my_python_files" in the parent directory containing this script
import sys
import os
sys.path.append(os.path.join("..", "my_python_files"))

# Let's import the "my_functions" module
import my_functions # or from my_functions import func_ext

# Now we can use the function precising the module in which it is
# This can be very practical when multiple modules have functions with the same name
my_functions.funct_ext() # or directly call funct_ext() if the function is explicitly imported

When a file is imported it is also executed.

# This test indicates that we only run this when the file is executed directly
if __name__ == "__main__":
    print("Testing of the module")

Code organization

Files and modules (cont)

To keep code organized, it’s good practice to split it into multiple files. For example:
  • main.py – The main script.
  • functions.py – Contains reusable functions.

The structure of a file such as functions.py should follow the following convention:

"""
    General description of the document contents.
"""

# Needed imports
# ...

# Various functions, well documented.
# ...

# Things to do when running this code directly
if __name__ == "__main__":
    # ...

Code organization

Modules and virtual environments

The Python language comes with a plethora of already defined functions regrouped into thematical modules.
  • Always favor the use of existing (official) modules (Python Standard Library + addional modules).

The python modules installer

The Python Package Index (PyPI) is a repository of software for the Python programming language. PyPI helps you find and install software developed and shared by the Python community, using the pip installer. pip install matplotlib

Managing projects and their dependencies with virtual environments

virtualenv is a tool to create lightweight virtual environments, each with their own independent set of Python packages installed in their site directories.

python -m venv venvpath