Joshua's Docs - Python Notes & WIP Cheatsheet


What & Link Type
Official Docs Official Docs
Florian GOTO - "Python Essentials for Node.js Developers Intro Guide

Using Packages

The default package manager for Python is called "pip", and lets you install packages from the Python Package Index (PyPi).

For those with NodeJS experience, pip is similar to NPM or Yarn, and PyPi is similar to the NPM Package Repository.

Installing packages with pip is fairly straightforward, and the commands are similar to other package managers:

Action Command
Install from PyPi pip install "PackageName"

You can also use semver:
pip install "PackageName~=1.2.6"
Update package to latest pip install --upgrade PackageName
Install from Requirements File pip install -r requirements.txt
Install from VCS / Github pip install -e {VCS_Syntax_String} (*)
Install from local tarball pip install {localTarballPath}.tgz

For the full list of commands, please see the pip reference guide.

🚨 Unlike NodeJS package managers, By default, pip installs packages globally. You can --user to scope the install to the user instead, but the best approach is to use virtual environments

Requirements Files

If you are sharing your python script, or even just using it in different environments, you probably don't want to require that its packages (dependencies) be installed one-by-one, manually with pip. A Requirements File is a way to declare all the packages required by your project, down to the specific versions, and which pip can use to provide a repeatable installation experience.

To generate a requirements file, you can either hand-code it, or use the pip freeze command:

python -m pip freeze > requirements.txt

And, then to install from it:

python -m pip install -r requirements.txt

NodeJS developers: Yes, this is similar to dependencies section of package.json, although pip's package resolution algorithms are not identical to NPM or Yarn.

Virtual Environments

The default behavior of pip, installing packages globally, is not very optimal once you move beyond a single project; you can easily end up with version conflicts (project A requires lib v1.0, but Project B requires lib v2.0), and other issues.

Luckily, Virtual Environments are a way in Python to have packages scoped to individual project directories, instead of the OS or user.

In general, if you are using Python 3.3 or newer, it is recommended to use the built-in venv module. Otherwise, the virtualenv tool (as a separate install) is the standard approach. This is a good guide that covers both.

Markdown Source Last Updated:
Sun Nov 15 2020 04:16:35 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Wed Nov 11 2020 10:38:21 GMT+0000 (Coordinated Universal Time)
© 2021 Joshua Tzucker, Built with Gatsby