When using Git to collaborate on a software project, team members should work in the same development environment. New changes should have the same effect for all members of the project and all users of the product.
The Python programming language supports multiple ways of packaging software for reliable results.
When your Python code requires specific Python modules,
pip can be used to manage these dependencies.
By adding a file called
requirements.txt to your project, each developer can install the required modules by using
pip install -r requirements.txt
The structure of
requirements.txt is simple: a line with the name of each package to install,
and optionally the version restrictions using ==, >= and <=.
When you add code to the project that depends on a module not previously used in the project,
pip freeze > requirements.txt on the command line, and include the changes to this file in your commit.
If the required modules haven't been installed yet at runtime, it's still not too late. Pip can be called from within a Python script as follows:
# Import pip for installing new modules from pip._internal import main # List of module names to import dependencies = [ 'pandas' ] # Iterate over the module names for dep in dependencies: try: # Import module if available # This notation is required for module names in string format __import__(dep) except ModuleNotFoundError: # Use 'pip install' if the module is not available main(['install', dep]) __import__(dep)
When you're working on multiple projects, you might have a more modules installed than just those for the current project.
If you use
pip freeze now, you will also include the other, unnecessary, modules.
You can set up a Python virtual environment
for each of your projects, to control your dependencies per project.
When you want to share your virtualenv or add this information to the Git repository, simply using
pip freeze again
will create the
requirements.txt for the current virtual environment only.
When you're (mostly) sure that your software is in a final, shippable state, you can compile the Python code to an executable. See here.