Skip to main content

Python

About​

Python is an interpreted, high-level and general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects. (Wikipedia, 2020)

Getting Started​

Pyenv (Python Version Management)​

Manage multiple python versions comfortably

Installation​

MacOS

  1. Install via [Homebrew](https://brew.sh)
    brew update
    brew install pyenv
  2. Add pyenv init to your shell to enable shims and autocompletion. Please make sure eval "$(pyenv init -)" is placed toward the end of the shell configuration file since it manipulates PATH during the initialization.
    echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.zshrc
    Bash note: Modify your ~/.bash_profile file instead of ~/.zshrc.
  3. Restart shell
    source ~/.zshrc

Debian based Linux

  1. Install dependencies
    sudo apt install -y make build-essential libssl-dev zlib1g-dev  libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils   tk-dev libffi-dev liblzma-dev python-openssl git
  2. Clone the repository
    git clone https://github.com/pyenv/pyenv.git ~/.pyenv
  3. Update .bashrc
    echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrcnano
    echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
    echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init --path)"\nfi' >> ~/.bashrc

Download specific python version​

pyenv install 3.7.0

List available python versions​

pyenv versions

Activate a specific version locally​

This sets the Python version for the current folder and all subfolders.

pyenv local 3.7.0

Activate a specific version globally​

pyenv global 3.7.0

Virtual environments​

Don't clutter your global pip installation, use one virtual environment per project instead. \ Important: Create virtual environment in project folder

Create a virtual environment & activate it​

python3 -m venv venv
source venv/bin/activate

Deactivate virtual environment​

deactivate

Create a requirements file​

pip freeze > requirements.txt

Install dependencies from a requirements file​

pip install -r requirements.txt

Uninstall virtual environment​

  1. (Optionally) Deactivate venv
    deactivate
  2. Remove venv folder
    rm -rf venv

Useful snippets​

Format String​

text="This"

print("{} {} {} {}!".format(text, 'is', 'super', 'cool')

> This is super cool!

Debug with ic() instead of print()​