Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ from scratch.
If you plan to do Python programming in a Linux or HPC environment you should
be familiar with these as well.

For following along hands-on, you need
* laptop or desktop with internet access.
* a Python environment that can run Jupyter Lab if you want to use your own system;
* access to Google Colaboratory if you prefer not to install software.


## Level

Expand Down
3 changes: 2 additions & 1 deletion docs/_config.yml
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
theme: jekyll-theme-slate
title: "Python software development"
theme: jekyll-theme-slate
Binary file modified python_software_engineering.pptx
Binary file not shown.
4 changes: 4 additions & 0 deletions source-code/decorators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@ What is it?
large. The decorated function in this example is the factorial.
Also it illustrates `functools` wrap decorator to retain the wrapped
function's name, docstring, etc.
1. `decorator_arguments.py`: an example of a decorator that takes arguments.
The `check_range` decorator takes a minimum and maximum value as arguments
and checks if the wrapped function's argument falls within that range,
throwing an exception if it does not.
1. `memoize.py`: an example of adding a cache to a function using a simple
custom decorator, as well as `functools`'s `lru_cache` decorator.
53 changes: 53 additions & 0 deletions source-code/decorators/decorator_arguments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/usr/bin/env python3

import functools


def check_bounds(min_value, max_value):
'''Check bounds of a function argument

Parameters
----------
min_value: float
Smallest value allowed for the function's parameter
max_value: float
Largest value allowed for the function's parameter

Raises
------
ValueError:
If the argument is outside the specified bounds
'''
def check_bounds_wrapper(_func):
@functools.wraps(_func)
def wrapper(x):
if min_value > x or x > max_value:
raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
return _func(x)
return wrapper
return check_bounds_wrapper
Comment on lines +20 to +28
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Decorator only supports a single positional argument; consider generalizing to *args/**kwargs or making this constraint explicit.

Currently check_bounds will throw a generic TypeError if used on a function with more than one argument, because wrapper only accepts x. To make this safer, you could define wrapper(*args, **kwargs), forward all arguments to _func, and explicitly check the relevant argument (e.g., args[0]). If the decorator is intentionally limited to single-argument functions, consider validating _func’s signature up front so incorrect usage fails with a clear error message.

Suggested change
'''
def check_bounds_wrapper(_func):
@functools.wraps(_func)
def wrapper(x):
if min_value > x or x > max_value:
raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
return _func(x)
return wrapper
return check_bounds_wrapper
'''
def check_bounds_wrapper(_func):
@functools.wraps(_func)
def wrapper(*args, **kwargs):
if not args:
raise TypeError(
"check_bounds-decorated functions must have at least one "
"positional argument to check"
)
x = args[0]
if min_value > x or x > max_value:
raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
return _func(*args, **kwargs)
return wrapper
return check_bounds_wrapper



@check_bounds(min_value=-1.0, max_value=1.0)
def silly(x):
'''Compute a rather uninteresting function

Parameters
----------
x: float
Argument for the function

Returns
-------
float:
Value computed by the function
'''
return x**2 - 2.0


if __name__ == '__main__':
print(silly(0.5))
try:
print(silly(2.5))
except ValueError as e:
print(f'Exception raised as expected: {e}')
44 changes: 39 additions & 5 deletions source-code/object-orientation/dynamic_classes.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,15 @@
"metadata": {},
"outputs": [],
"source": [
"Cat = make_dataclass('Cat', [('species', str, 'cat'), ('nr_legs', int, 4), ('sound', str, 'meow')], bases=(Animal, ))"
"Cat = make_dataclass(\n",
" 'Cat',\n",
" [\n",
" ('species', str, 'cat'),\n",
" ('nr_legs', int, 4),\n",
" ('sound', str, 'meow')\n",
" ],\n",
" bases=(Animal, )\n",
")"
]
},
{
Expand Down Expand Up @@ -202,7 +210,15 @@
"metadata": {},
"outputs": [],
"source": [
"Dog = make_dataclass('Dog', [('nr_legs', int, 4), ('species', str, 'dog'), ('sound', str, 'woof')], bases=(Animal, ))"
"Dog = make_dataclass(\n",
" 'Dog',\n",
" [\n",
" ('nr_legs', int, 4),\n",
" ('species', str, 'dog'),\n",
" ('sound', str, 'woof')\n",
" ],\n",
" bases=(Animal, )\n",
")"
]
},
{
Expand Down Expand Up @@ -423,7 +439,16 @@
"metadata": {},
"outputs": [],
"source": [
"Animal = type('Animal', tuple(), {'name': None, 'species': None, 'nr_legs': None, '__init__': animal_init})"
"Animal = type(\n",
" 'Animal',\n",
" tuple(),\n",
" {\n",
" 'name': None,\n",
" 'species': None,\n",
" 'nr_legs': None,\n",
" '__init__': animal_init,\n",
" }\n",
")"
]
},
{
Expand Down Expand Up @@ -579,7 +604,16 @@
"metadata": {},
"outputs": [],
"source": [
"Cat = type('Cat', (Animal, ), {'name': None, 'species': 'cat', 'nr_legs': 4, 'sound': 'meow'})"
"Cat = type(\n",
" 'Cat',\n",
" (Animal, ),\n",
" {\n",
" 'name': None,\n",
" 'species': 'cat',\n",
" 'nr_legs': 4,\n",
" 'sound': 'meow',\n",
" }\n",
")"
]
},
{
Expand Down Expand Up @@ -970,7 +1004,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
"version": "3.12.3"
}
},
"nbformat": 4,
Expand Down
48 changes: 24 additions & 24 deletions source-code/oo_vs_functional.ipynb

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion source-code/prime_time.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
"version": "3.12.3"
}
},
"nbformat": 4,
Expand Down
134 changes: 132 additions & 2 deletions source-code/pydantic.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
{
"cell_type": "code",
"execution_count": 35,
"execution_count": 1,
"id": "b2ba87d0-2447-4a4d-9bae-eb0e86d39ce1",
"metadata": {},
"outputs": [],
Expand Down Expand Up @@ -239,6 +239,136 @@
"As you can see, a Python `dataclass` will not perform validation out-of-the-box."
]
},
{
"cell_type": "markdown",
"id": "f9d4e8b1-22b7-4c25-adc0-fb8eb46ed26f",
"metadata": {},
"source": [
"## Default values"
]
},
{
"cell_type": "markdown",
"id": "3b808ae6-0b73-4fb7-b570-593243b15448",
"metadata": {},
"source": [
"Attributes can have default values. For types such as `int` or `str` these are simple constants for non-trivial types you can use `default_factory`."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e00b9f60-5be3-4cea-9dcd-02497911c33e",
"metadata": {},
"outputs": [],
"source": [
"class Agent(BaseModel):\n",
" name: str\n",
" interactive: bool = False\n",
" tools: list[str] = Field(default_factory=list)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "98381d5a-c8ae-4c70-958d-43206747766c",
"metadata": {},
"outputs": [],
"source": [
"agent1 = Agent(name='my_agent')"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "c664f054-64fc-4a35-8cd6-77f9429313d4",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent1.interactive"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "f031bf63-9de5-4c96-b153-e510da32f223",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent1.tools"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "61bf4564-9266-4edd-a55a-3d796daeffa9",
"metadata": {},
"outputs": [],
"source": [
"agent1.tools.append('screwdriver')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "e5b860c1-530b-4cf7-8e79-30806039ce35",
"metadata": {},
"outputs": [],
"source": [
"agent2 = Agent(name='my_other_agent')"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "edfcebbe-5a7d-4c1c-b47a-2d8c3ddd54f3",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent2.tools"
]
},
{
"cell_type": "markdown",
"id": "094eb08a-1ae8-4d42-9c18-d635ea3fca70",
"metadata": {},
"source": [
"It is clear that using `default_factory` results in the right behavior."
]
},
{
"cell_type": "markdown",
"id": "c31de1d8-2744-48b7-9914-bfeb90cfdac0",
Expand Down Expand Up @@ -608,7 +738,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
"version": "3.12.3"
}
},
"nbformat": 4,
Expand Down