Appendix E — Self Study Session - Runtime stability
In this section we are mainly concerned with the scientific computing libraries and approaches of Python, nevertheless you are expected to use git and pdm to solve the problems at hand.
Once you are familiar with how Python handles these topics you will be able to answer questions like:
How is slicing working in exceptions, Pathlib, logging and testing?
Exercise E.1 (Decorators) In Python we can use decorators to modify the functionality of a function by wrapping it in another function, you can find introductions in the following links
Write a decorator @positive that checks arguments to be positive and raise an Exception (with raise Exception("Sorry, not positive")). Test this implementation with Exercise D.3 and Exercise D.4. We will look at exception handling later.
Can you modify the decorator such that you can give an optional argument specifying the location to check for positivity?
@positiv(1)def testfun(a, b, c)# error fortestfun(-1, -1, -1)# but not fortestfun(-1, 1, -1)
Exercise E.2 (Pydantic) In Python the Pydantic module is a widely used data validation library.
Exercise E.3 (Define log level via environment variable) In Chapter 11 we specified how to customize the logger for a project. Quite often you want to define the log level via an environment variable. If the variable myloglevel=DEBUG is set, it is used. If nothing is specified the default value is used.
Implement this for the following snippet and test it accordingly to produce different output.
import logginglogging.basicConfig(format="%(asctime)s:%(levelname)s: %(message)s", level=logging.DEBUG)numberlist = [-2, -1, 0, 1, 2, "a", 1/4]for number in numberlist: try: logging.debug(f"Working on number {number}") inverse =1.0/ numberexceptZeroDivisionErroras e: logging.error(f"Tried to divide by zero, error is {e}")exceptTypeError: logging.warning(f"The list does not only contain numbers")
Hint: The os module provides a function to get environment variables, docs.
Exercise E.4 (Pathlib) In Python the pathlib module is a widely used for working with paths and files. Use it to solve the following exercises.
Create a directory tmp with current path of the program. Do not forget to first check if the directory already exists.
What would be the alternative with a try-catch statement?
Create the following files with this directory: [test.txt, file.txt, README.md, random.py]
Use collections.Counter to get a dictionary with the number of files per ending in the directory tmp. The output should look something like this:
Counter({'.md': 1, '.txt': 2, '.py': 1})
Find the last modified file in the directory.
Clean up and delete all files as well as the directory.
The rest of the runtime stability topics will be part of the project and implemented there.