Python 3 Cheat Sheet

Installing Python and pip

brew install [email protected]
brew install [email protected]

Another option is pyenv – Simple Python version management:

brew install pyenv
pyenv install 3.7.2
pyenv install 2.7.14
pyenv global 3.7.2

Pipenv integrates with pyenv and will automatically install missing Python versions if they’re required by a Pipfile.

Virtual Environments

venv

Docs

Pros

  • Built-in feature.
  • Generates a config file.
  • Doesn’t require copying the Python binary to a project location.

Cons

  • Works only with Python 3.3+

virtualenv

pip3 install virtualenv

# create environment
virtualenv -p python3 ~/project_dir
# (de)activate environment
cd ~/project_dir
source bin/activate
deactivate

Pros

  • Easy to upgrade via pip.
  • Easily work with multiple versions of Python.
  • Supports Python 2.7+

Cons

  • Copies Python binary for any new environment.

pipenv

Docs

brew install pipenv
# create a Pipfile and install a package
cd ~/project_folder
pipenv install requests
# (de)activate environment
pipenv shell
exit
# directly run a command
pipenv run python
pipenv run django-admin startproject project_name
# delete environment
cd ..
pipenv —-rm

Compatibility With Non-pipenv projects

pip install -r requirements.txt
pipenv lock -r

Pros

  • Combines package and environment management into a single tool.
  • Supports multiple sub-envs for project environment, e.g. production or test.
  • Pipfile includes the list of packages, Python version and other information.

Cons

  • It’s slow.
  • Spawns a new subshell.
  • By default, creates an environemnt in the current user’s home directory. This can be solved with export PIPENV_VENV_IN_PROJECT=1.
  • Supports loading .env files, but only when running pipenv shell and pipenv run.
  • Does not handle any parts of packaging.

VS Code Plugins

Settings

{
  "autoDocstring.docstringFormat": "google",
  "editor.snippetSuggestions": "top",
  "files.watcherExclude": {
    "**/.direnv/**": true,
    "**/.venv/**": true
  }
}

pytest

Command Description
pip3 install pytest pytest-cache pytest-pep8 Install pytest
python3 -m pytest –version Run the Python 3 version of pytest
pytest hello_world_test.py Run all tests for hello_world.py
pytest -x hello_world_test.py Stop after first failure
pytest –ff hello_world_test.py Run failed tests first
pytest -x –ff hello_world_test.py Recommended approach
pytest –pdb hello_world_test.py Drop you into the Python debugger when a test fails
pytest –pep8 hello_world_test.py Test for compliance to the style guide

pytest documentation, pytest-cache documentation