Python

code snippets and stuff for Python

Programm Setup

Install pyenv and set it to the version you want to use Install virtualenv, using pyenv is not necessary but I like it to keep my python versions managed. Install python3.10-venv if an error message tells to.

curl https://pyenv.run | bash
pyenv install 3.11
pyenv local 3.11
apt install python3.10-venv #might not be needed with pyenv
pyenv local 3.9.0
python -m venv

Shebang and program layout

#!/usr/bin/env python3

def main(kwargs**, args**):
    pass

if __name__ == '__main__':
    main()

Beautiful Soup

Use beautiful soup for scraping and manipulating html content

Commandline execution

The -c flag tells python to run the appended string as a command. For example

Help Function

adding an explantion string to a function can be used by the help() function to give explanation into what it is doing.

for a class this looks like:

and the output from interactive session is:

CLI Arguments

Use the argparse Library to read cli arguments.

argv is a dictionary like {'file' : 'CliArgument'}. args` is the Namespace for all Cli Arguments.

String Formatting

Filling {} with the variable `Name'

More complex solution by definen the positional arguments of the format function

This puts Name in {1} because it is the second positional argument (0-based indexing) and age in {0}.

IF-Else Oneliner

Read this_dict['key'] is other_dict['key'] if that key exists (evalutes to true) otherwise keep the origial value.

Logging

the logger object takes several arguments, the first on is the message that needs to be one string. Not like the print function that automatically concatenates its arguments to a string

Jupyter Notebook

Decorators

Decorators can only be applied to functions and classes see

Last updated