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​
- https://www.python.org/about/gettingstarted/
- We highly recommend you to install and get familiar with the following tools before starting to work with python productively, they will save you a lot of time and problems.
Pyenv (Python Version Management)​
Manage multiple python versions comfortably
Installation​
MacOS
- Install via [Homebrew](https://brew.sh)
brew update
brew install pyenv - Add
pyenv init
to your shell to enable shims and autocompletion. Please make sureeval "$(pyenv init -)"
is placed toward the end of the shell configuration file since it manipulatesPATH
during the initialization.Bash note: Modify yourecho -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.zshrc
~/.bash_profile
file instead of~/.zshrc
. - Restart shell
source ~/.zshrc
Debian based Linux
- 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
- Clone the repository
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
- 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​
- (Optionally) Deactivate venv
deactivate
- 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()
​
- Use https://github.com/gruns/icecream
pip install icecream
>>> a = 6
>>> def half(i):
>>> return i / 2
>>> b = half(ic(a))
ic| a: 6
>>> ic(b)
ic| b: 3