charlesreid1.com blog

Python Patterns: The Registry

Posted in Python

permalink

Overview

This post is a summary of a useful Python programming pattern called the Registry pattern.

The Registry pattern is a way of keeping track of all subclasses of a given class.

More details about this pattern are available at https://github.com/faif/python-patterns.

What is the Registry Pattern?

Let's start with a common scenario: you have some kind of manager class that is managing multiple related subclasses, and you are looking for a simpler way to manage the subclasses.

The registry pattern creates a map of labels to class types, and allows you to access a single registry common to all of those classes. The registry is updated every time a new class is added.

This is useful for several situations, including these two examples:

  • You want the manager class to iterate over every available subclass and call a particular method on each subclass
  • You want to streamline a factory class, which takes an input label (like the name of a class) and creates/returns an object of that type

The Registry Base Type

We start by defining a registry base type (or class). This class defines one behavior, which is adding itself to the class registry. It creates a shared instance variable called REGISTRY which is shared amongst all of the classes, and is also accessible via a class method.

This is the base class; any class we want registered should inherit from this class. It should also extend the type class, since it is itself a class type:

class RegistryBase(type):

    REGISTRY = {}

    def __new__(cls, name, bases, attrs):
        # instantiate a new type corresponding to the type of class being defined
        # this is currently RegisterBase but in child classes will be the child class
        new_cls = type.__new__(cls, name, bases, attrs)
        cls.REGISTRY[new_cls.__name__] = new_cls
        return new_cls

    @classmethod
    def get_registry(cls):
        return dict(cls.REGISTRY)

The design here is subtle, but the details are important to understand how it works.

A few important things to note, progressing from top to bottom:

  • The REGISTRY variable is defined outside the scope of any class methods, meaning it is a shared instance variable (a variable that is shared across all instances of RegistryBase); this is an example of the Borg pattern.

  • The RegistryBase class defines __new__, not __init__; the __new__ method is run when the class is defined, while __init__ is run when the classs is instantiated. This ensures that any subclasses that inherit from RegistryBase add themselves to the registry when they are defined, not when they are instantiated.

  • In the constructor, we store a reference to the current class using this line:

new_cls = type.__new__(cls, name, bases, attrs)

This creates a new class, but of type type (confusing, but basically it means we store a reference to this type of object, not just a reference to a particular object).

It is important to note that once we use the registry, the value that is returned is callable, and will create an object corresponding to that type.

  • We define a get_registry method to return a copy of the registry; this must be decorated with a @classmethod decorator (not a @staticmethod decorator) so that it has access to the registry, which is a class instance variable.

BONUS NOTE: From prior experience, we have found it easiest to ignore the case of the label (uppercase, lowercase, CamelCase, etc) and convert all class names to lowercase in the registry:

        cls.REGISTRY[new_cls.__name__.lower()] = new_cls

The Base Registered Class

Now we can define a base class that will extend the RegistryBase class. However, because RegistryBase is a type class, we shouldn't extend it directly - we should use it as a metaclass.

class BaseRegisteredClass(metaclass=RegistryBase):
    pass

Any class that inherits from this BaseRegisteredClass will now be included in the registry when it is defined.

Extending the Base Registered Class

The next step is to use the base registered class to start creating interesting classes:

class ExtendedRegisteredClass(BaseRegisteredClass):
    def __init__(self, *args, **kwargs):
        pass

We skip defining constructor behavior, as the call order is what's important.

Seeing it in action

Now we can see the process of adding subclasses to the registry in action.

Start by checking the registry before we have created any subclasses:

>>> print(RegistryHolder.REGISTRY)
['BaseRegisteredClass']

Next, define the extended registered class:

>>> class ExtendedRegisteredClass(BaseRegisteredClass):
...     def __init__(self, *args, **kwargs):
...         pass

Remember, we add the new class to the registry in the __new__ method, not the __init__ method, so we don't even need to instantiate an ExtendedRegisteredClass object for it to be added to the registry. Check the registry again:

>>> print(RegistryHolder.REGISTRY)
['BaseRegisteredClass', 'ExtendedRegisteredClass']

Examples

Let's consider a specific example to help illustrate the usefulness of the Registry pattern: adding the ability to index different kinds of documents to a search engine.

Example: Search Engine

Suppose we are writing a search engine, and we are working on the search engine backend. Specifically, consider the backend portion that iterates over a group of documents, checks if the document is already in the search index, and either adds a new item to the search index, updates an existing item in the search index, or deletes an item from the search index.

Registry Subclasses

A search engine may index multiple kinds of documents, each living in different locations. For example, a search index may index .docx files in a Google Drive folder, Github issues, and/or a local folder full of Markdown files. For each of these document types, we must define:

  • How to add or update all documents in the document storage system (Google Drive, Github API, local filesystem, etc.); this method should be able to get a list of documents of this document type that are already in the search index, either by running a query itself, or by accepting a list of documents already in the index as an input argument

  • What schema to use (mapping various field names to data types) for documents of this type

  • How to display search results when they are documents of this type (i.e., how to display what fields when showing the user search results)

This can be done by defining classes corresponding to different document types, where each class defines how to do the above actions, and wraps them in high-level API methods that the manager classes can call.

The manager classes want a way to get a list of available document types, and to call each document type's high-level API methods. This can be done with the registry.

Doctype Registry Base Type

Start by defining a base type that will register new subclasses in a doctype registry. Note that as per the __new__ documentation, the __new__ method takes the class (in our case, a class of type type) as the first argument cls, and it should return a new object instance (which, again, is an instance of type type).

class DoctypeRegistryBase(type):

    DOCTYPE_REGISTRY = {}

    def __new__(cls, name, bases, attrs):
        new_cls = type.__new__(cls, name, bases, attrs)
        cls.DOCTYPE_REGISTRY[new_cls.__name__.lower()] = new_cls
        return new_cls

    @classmethod
    def get_doctype_registry(cls):
        return dict(cls.DOCTYPE_REGISTRY)

Base Registered Doctype Class

Next, we define a base class for any document type that we want registered in the doctype registry, using DoctypeRegistryBase as our metaclass (because it is a class of type type, as opposed to a normal class). All document types are required to define three bits of behavior (interacting with the document storage system to iterate over all documents; extracting information from individual documents; and displaying a given document type when it is a search result. We define these virtual methods on the base registered doctype class.

class BaseRegisteredDoctypeClass(metaclass=DoctypeRegistryBase):

    def add_update_delete(self, *args, **kwargs):
        """
        Iterate over all documents in the document storage system
        and add/update/delete documents as needed.
        """
        raise NotImplementedError()

    def get_schema(self, *args, **kwargs):
        """
        Assemble and return the schema (map of field names to data types)
        """
        raise NotImplementedError()

    def render_search_result(self, *args, **kwargs):
        """
        Use a Jinja template to render a single search result of type doctype
        to display to the user via the web interface
        """
        raise NotImplementedError()

Derived Registered Doctype Class

Now that we have a base class, we can define child classes that have the specific API functionality needed.

Here is a high-level sketch of what the Github issue document type class might look like, starting with the add/update/delete method, which boils down to some set operations to determine what documents to add, update, or delete from the search index.

(Also note, these methods are defined as class methods because they are called once for each doctype class, but this does not necessarily need to be the case.)

class GithubIssueDoctype(BaseRegisteredDoctypeClass):

    @classmethod
    def add_update_delete(cls, *args, **kwargs):
        # Get set of indexed document IDs
        indexed_docs = set()
        results = run_search_index_query(doctype = cls.__name__.lower())
        for result in results:
            indexed_docs.add(result.id)

        # Get set of remote document IDs
        remote_docs = set()
        for org_name in get_org_names():
            for repo_name in get_repo_names(org_name):
                for file in get_repo_files(repo_name, org_name):
                    remote_docs.add(file.id)

        # Do some set math to figure out what to add/update/delete
        add_ids = remote_docs.difference(indexed_docs)
        update_ids = indexed_docs.union(remote_docs)
        delete_ids = indexed_docs.difference(remote_docs)

        # Do the operations
        for add_id in add_ids:
            add_document_to_index(add_id)
        for update_id in update_ids:
            update_document_in_index(update_id)
        for delete_id in delete_ids:
            delete_document_in_index(delete_id)

    @classmethod
    def get_schema(cls, *args, **kwargs):
        ...

    @classmethod
    def render_search_result(cls, *args, **kwargs):
        ...

Now we do the same for documents on Google Drive, defining a different add_update_delete() method specific to Google Drive documents (note that while the sketch of this method looks similar to the Github doctype above, the implementation will look more and more different as we include more and more detail in our method and API calls).

As before, we make these methods class methods.

class GoogleDocsDoctype(BaseRegisteredDoctypeClass):

    @classmethod
    def add_update_delete(cls, *args, **kwargs):
        # Get set of indexed document IDs
        indexed_dcos = set()
        results = run_search_index_query(doctype = cls.__name__.lower())
        for result in results:
            indexed_docs.add(result.id)

        # Get set of remote document IDs
        remote_docs = set()
        for files in get_gdrive_file_list():
            remote_docs.add(file.id)

        # Do some math to figure out what to add/update/delete
        add_ids = remote_docs.difference(indexed_docs)
        update_ids = indexed_docs.union(remote_docs)
        delete_ids = indexed_docs.difference(remote_docs)

        # Do the operations
        for add_id in add_ids:
            add_document_to_index(add_id)
        for update_id in update_ids:
            update_document_in_index(update_id)
        for delete_id in delete_ids:
            delete_document_in_index(delete_id)

    @classmethod
    def get_schema(cls, *args, **kwargs):
        ...

    @classmethod
    def render_search_result(cls, *args, **kwargs):
        ...

Using the Registry

The last step is to actually use the registry from the class that manages all of our subclasses. In this case, we have a Search class that defines high-level operations (such as, "add/update/delete all documents indexed by this search engine") and in turn calls the corresponding method for each doctype that has been registered.

class Search(object):

    def add_update_delete_all(self, *args, **kwargs):

        # Iterate over every doc type
        for doctype_name in DoctypeRegistryBase.DOCTYPE_REGISTRY:

            # Get a handle to the doctype class
            doctype_class = DoctypeRegistryBase.DOCTYPE_REGISTRY[doctype_name]

            # Call the class method add_update_delete on the doctype class
            doctype_class.add_update_delete(*args, **kwargs)

            # Note: if we need to create an instance first
            # doctype_instance = doctype_class()
            # doctype_instance.add_update_delete(*args, **kwargs)

Further Modifications

In the example above, we don't have any need to create specific instances of the document type classes, since they do not need to preserve their state between calls, and we only need one instance of the doctype class per search engine.

We could re-implement this pattern, modifying the search engine doctype classes to be normal, non-static classes. This would allow us to have, say, two instances of the Github issues doctype class (corresponding to two different sets of Github API credentials, or two different Github accounts), or two instances of the Google Drive doctype class (corresponding to two different Google Drive folders). In this case, we would want to restructure the Search class to instantiate and save doctype class instances in the constructor, and use them later.

Here's an example Search class that would instantiate one of each subclass in the constructor, to be used in later methods:

class Search(object):

    def __init__(self, *args, **kwargs):

        # Store instances of each doctype
        self.all_doctypes = []

        # Iterate over every doc type
        for doctype_name in DoctypeRegistryBase.DOCTYPE_REGISTRY:

        # Get a handle to the doctype class
        doctype_class = DoctypeRegistryBase.DOCTYPE_REGISTRY[doctype_name]

        # Create an instance of type doctype_class
        doctype_instance = doctype_class()

        # Save for later
        all_doctypes.append(doctype_instance)

    def add_update_delete(self, *args, **kwargs):

        # Call the add_update_delete method on each doctype instance
        for doctype_name, doctype_instance in self.all_doctypes.items():
            doctype_instance.add_update_delete(*args, **kwargs)

(Note that this would work best if we removed the @classmethod decorators from the doctype classes defined above.)

Summary

In this post, we covered a useful programming pattern, the Registry, and showed it in action for one example - allowing a search engine index to register various document type subclasses, then use those registered subclasses to propagate calls to all document types later.

Tags:    python    programming    patterns    design patterns    registry    computer science   

Incorporating Terraform Commands into Makefiles

Posted in Terraform

permalink

Summary

This blog post covers a useful pattern for incorporating terraform commands into a Makefile.

This is useful for cases where terraform is being used to manage infrastructure. In the end you will be able to run a command like

make plan-infra
make deploy-infra

and and have this call the corresponding terraform commands to plan and deploy your terraformed cloud infrastructure.

The post is divided into a few steps:

  • Directory and file layout - how we lay out the files for this tutorial
  • Top level Makefile - make commands to add to the top level Makefile
  • Infra level Makefile - make commands to add to the infra level Makefile
  • Writing Terraform component - how to write a configurable component that is ready to terraform
  • Initializing Terraform component - script to initialize terraform components
  • Workflow - plan, deploy, update, destroy

Step 0: Directory and File Layout

This tutorial presumes you have a top level directory corresponding to a git repository. We will use the following directory structure for this example:

my-project/
    Readme.md
    environment
    Makefile
    infra/
        Makefile
        component-1/
            variables.tf
            main.tf

Environment Variables

In order to keep track of environment variables used in the terraform process, we use the file envronment in the top level project directory to keep all environment variable values under version control.

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
export PROJECT_HOME="$(cd -P "$(dirname "$SOURCE")" && pwd)"

set -a
PROJECT_DEPLOYMENT_STAGE="dev"

# bucket name
PROJECT_S3_BUCKET="my-organization-my-project-my-bucket"

# aws tags
PROJECT_INFRA_TAG_PROJECT="my-project"
PROJECT_INFRA_TAG_SERVICE="my-service"
PROJECT_INFRA_TAG_OWNER="whoami@email.com"

# aws settings
AWS_DEFAULT_OUTPUT=json
AWS_DEFAULT_REGION=us-east-1
set +a

Optionally, a local environment file can contain environment variable values that are sensitive or should not be kept under version control, so add this to the bottom of the environment file too:

if [[ -f "${PROJECT_HOME}/environment.local" ]]; then
    source "${PROJECT_HOME}/environment.local"
fi

Step 1: Top Level Makefile

Start by creating the plan-infra and deploy-infra commands in your top-level Makefile. These commands will, in turn, call make commands defined in infra/Makefile:

plan-infra:
    $(MAKE) -C infra plan-all

deploy-infra:
    $(MAKE) -C infra apply-all

The -C infra flag indicates make should use a Makefile in a subdirectory.

Step 2: Infra Level Makefile

Next we define infra/Makefile. This Makefile will have two parts:

  • terraform commands for a single component (example: init, plan, apply, destroy)
  • wrapper commands to run the above commands for every component (example: for each component, run the plan terraform command)

We cover the Makefile from the bottom up.

Fake Targets

Start by defining "fake" targets or rules, that is, make rules whose names are not file names:

.PHONY: init-all plan-all apply-all clean-all plan apply destroy init clean

Commands for Single Components

Next, above that, we define terraform commands for a single component:

init:
    rm -rf $(COMPONENT)/.terraform/*.tfstate
    ./build_deploy_config.py $(COMPONENT)
    cd $(COMPONENT); terraform init;

plan: init
    cd $(COMPONENT); terraform plan -detailed-exitcode

apply: init
    cd $(COMPONENT); terraform apply

destroy: init
    cd $(COMPONENT); terraform destroy

clean:
    cd $(COMPONENT); rm -rf .terraform

Note that the init command is running a build_deploy_config.py script, which we will cover in a moment. This script creates the terraform variables file variables.tf and populates the variable values using environment variables.

Commands for All Components

Above that, we have commands to perform each action on all components:

all: init-all

init-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) init COMPONENT=$$c || exit 1; \
    done

plan-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) plan COMPONENT=$$c || exit 1; \
    done

apply-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) apply COMPONENT=$$c || exit 1; \
    done

destroy-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) destroy COMPONENT=$$c || exit 1; \
    done

clean-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) clean COMPONENT=$$c || exit 1; \
    done

Variables

Last but not least, we define a few variables at the top of the Makefile: most importantly, the list of infrastructure components. This is created by extracting the names of subdirectories in infra/ containing *.tf files:

DIRS=${shell find . -name "*.tf" -exec dirname {} \; | sort --unique}
COMPONENTS=${shell for d in $(DIRS); do basename $$d; done}

Final Makefile

Here is the final infra/Makefile:

infra/Makefile:

DIRS=${shell find . -name "*.tf" -exec dirname {} \; | sort --unique}
COMPONENTS=${shell for d in $(DIRS); do basename $$d; done}

all: init-all

init-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) init COMPONENT=$$c || exit 1; \
    done

plan-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) plan COMPONENT=$$c || exit 1; \
    done

apply-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) apply COMPONENT=$$c || exit 1; \
    done

destroy-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) destroy COMPONENT=$$c || exit 1; \
    done

clean-all:
    @for c in $(COMPONENTS); do \
        $(MAKE) clean COMPONENT=$$c || exit 1; \
    done

plan: init
    cd $(COMPONENT); terraform plan -detailed-exitcode

apply: init
    cd $(COMPONENT); terraform apply

destroy: init
    cd $(COMPONENT); terraform destroy

init:
    rm -rf $(COMPONENT)/.terraform/*.tfstate
    ./build_deploy_config.py $(COMPONENT)
    cd $(COMPONENT); terraform init;

clean:
    cd $(COMPONENT); rm -rf .terraform

.PHONY: init-all plan-all apply-all clean-all plan apply destroy init clean

Step 3: Writing Terraform Components

As an example, we will consider an example of terraform-managed buckets.

Start by creating a directory called infra/buckets/ to store terraform files for creating and managing the buckets.

We can create one file per cloud provider. As an example, here is s3.tf:

s3.tf:

data "aws_caller_identity" "current" {}

locals {
  common_tags = "${map(
    "project"   , "${var.PROJECT_INFRA_TAG_PROJECT}",
    "env"       , "${var.PROJECT_DEPLOYMENT_STAGE}",
    "service"   , "${var.PROJECT_INFRA_TAG_SERVICE}"
  )}"
  aws_tags = "${map(
  "Name"      , "${var.PROJECT_INFRA_TAG_SERVICE}-s3-storage",
  "owner"     , "${var.PROJECT_INFRA_TAG_OWNER}",
  "managedBy" , "terraform"
  )}"
}

resource aws_s3_bucket dss_s3_bucket {
  count = length(var.PROJECT_S3_BUCKET) > 0 ? 1 : 0
  bucket = var.PROJECT_S3_BUCKET
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }
  tags = merge(local.common_tags, local.aws_tags)
}

Note that this requires several environment variables to be defined in environment and requires the operator to run:

source environment

Step 4: Initializing Terraform Components

The following script will automatically generate terraform files for our component that are populated with the correct environment variable values.

It is called build_deploy_config.py.

Start with a simple argument parser that just accepts a single argument, the component to make terraform files for:

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("component")
args = parser.parse_args()

Next, we define several terraform file templates using Python's bracket template syntax. Start with a template for defining a terraform variable:

terraform_variable_template = """
variable "{name}" {{
  default = "{val}"
}}
"""

Next, define a template for the terraform backend buket:

terraform_backend_template = """# Auto-generated during infra build process.
# Please edit infra/build_deploy_config.py directly.
terraform {{
  backend "s3" {{
    bucket = "{bucket}"
    key = "{comp}-{stage}.tfstate"
    region = "{region}"
    {profile_setting}
  }}
}}
"""

Next define terraform cloud providers:

terraform_providers_template = """# Auto-generated during infra build process.
# Please edit infra/build_deploy_config.py directly.
provider aws {{
  region = "{aws_region}"
}}
"""

Provide a list of environment variables that should also be defined as terraform variables:

env_vars_to_infra = [
PROJECT_DEPLOYMENT_STAGE="dev"

# bucket name
PROJECT_S3_BUCKET="my-organization-my-project-my-bucket"

# aws tags
PROJECT_INFRA_TAG_PROJECT="my-project"
PROJECT_INFRA_TAG_SERVICE="my-service"
PROJECT_INFRA_TAG_OWNER="whoami@email.com"

# aws settings
AWS_DEFAULT_OUTPUT=json
AWS_DEFAULT_REGION=us-east-1

    "AWS_DEFAULT_REGION",
    "PROJECT_DEPLOYMENT_STAGE",
    "PROJECT_S3_BUCKET",
    "PROJECT_INFRA_TAG_PROJECT",
    "PROJECT_INFRA_TAG_SERVICE",
    "PROJECT_INFRA_TAG_OWNER"
]

Finally, substitute environment variable values into the templates, and write the templated content to the appropriate *.tf file. First, the backend:

# Write backend.tf
with open(os.path.join(infra_root, args.component, "backend.tf"), "w") as fp:
    caller_info = boto3.client("sts").get_caller_identity()
    if os.environ.get('AWS_PROFILE'):
        profile = os.environ['AWS_PROFILE']
        profile_setting = f'profile = "{profile}"'
    else:
        profile_setting = ''
    fp.write(terraform_backend_template.format(
        bucket=os.environ['DSS_TERRAFORM_BACKEND_BUCKET_TEMPLATE'].format(account_id=caller_info['Account']),
        comp=args.component,
        stage=os.environ['DSS_DEPLOYMENT_STAGE'],
        region=os.environ['AWS_DEFAULT_REGION'],
        profile_setting=profile_setting,
    ))

Next, the variables.tf for the component:

# Write variables.tf
with open(os.path.join(infra_root, args.component, "variables.tf"), "w") as fp:
    fp.write("# Auto-generated during infra build process." + os.linesep)
    fp.write("# Please edit infra/build_deploy_config.py directly." + os.linesep)
    for key in env_vars_to_infra:
        val = os.environ[key]
        fp.write(terraform_variable_template.format(name=key, val=val))

Finally, the cloud providers file providers.tf:

with open(os.path.join(infra_root, args.component, "providers.tf"), "w") as fp:
    fp.write(terraform_providers_template.format(
        aws_region=os.environ['AWS_DEFAULT_REGION'],
        gcp_project_id=GCP_PROJECT_ID,
    ))

Workflow

We now have a top-level Makefile that wraps the plan and apply commands directly, and we have an infra-level Makefile with additional commands for managing infrastructure (plan, apply, destroy).

Plan

The terraform plan step assembles the various templated terraform files and substitutes environment variables into them, creating a new version of them with up-to-date values.

The plan step (make plan-infra) calls the build_deploy_config.py script (detailed above) to regenerate the terraform files when environment variables are changed.

make plan-infra

This script will iterate over each cloud infrastructure component in infra/, use terraform to plan the changes it would make to cloud resources, and print a summary of those changes to the screen.

The make plan-infra command does not change any cloud infra.

Deploy

The terraform deploy step makes the changes summarized in the make plan-infra step. This command automates the terraform commands, but still requires interactive "yes" responses to commands.

Update

Using the make plan-infra command will remake the terraform files using environment variable values, and will display any changes that will be made to cloud infra. This includes updates to existing infrastructure.

When you finish deploying infrastructure, store the version of your environment file in version control and tag it as the current deployed infra. This will make it easier to delete infra later.

If you need to rename infra, use the following workflow:

  1. Source the old environment file

  2. Destroy the old infra with the old names using:

    text make -C infra COMPONENT=buckets destroy

    Or destroy all infra with the destroy-all command:

    text make -C infra destroy-all

  3. Update the environment file with the new names, and source the new environment file

  4. Plan the new infra with

    text make plan-infra

  5. Deploy the new infra with

    text make deploy-infra

Destroy

As seen above, infrastructure components can be deleted with the delete command in the infra Makefile, and all infrastructure components can be deleted with the delete-all command.

To delete a particular component:

make -C infra COMPONENT=buckets destroy

To destroy all infra:

make -C infra destroy-all

Tags:    terraform    makefile    make    python   

Automatically Generating Up-To-Date requirements.txt for Python Projects

Posted in Python

permalink

Summary

In this post, we cover a pattern for automatically generating a requirements.txt file that has the latest compatible versions of required software, and that specifies the full and exact version of each package to make the Python environment reproducible.

This will turn a requirements input file (called requirements.txt.in for example) that looks like

numpy

into a requirements file that specifies the exact version of numpy and all dependencies, like

numpy==1.18.1

By the end of this post, you'll be able to do this to refresh and update the versions of all the software your project depends on:

make requirements.txt

All of this code comes from the Human Cell Atlas data-store project!

What is requirements.txt?

When developing a Python project, the requirements.txt file is a plain text file that contains a list of Python software packages that need to be installed for the current Python software package to work. The software can be installed using the command

pip install -r requirements.txt

For example, if a package foobar has import numpy at the top of a Python file in the project, the numpy package must be installed before importing foobar. In this case, the requirements.txt could just contain

numpy

or it could specify a particular version of numpy, or a minimum version of numpy:

numpy >= 1.10

Start by creating a requirements.txt.in, which should look like a normal requirements.txt file, listing software packages for pip to install (and optionally version information - but version information does not need to be specified).

This file is a looser set of specifications of software versions.

Example requirements.txt.in:

numpy
pandas > 0.22
sphinx

Converting requirements.txt.in to requirements.txt

Next, we use the requirements.txt.in file to install the latest versions of each software package (and all dependent software packages) into a virtual environment.

From that virtual environment, we can use pip freeze to output the names of each software package installed in the virtual environment, along with its exact version. This can be used to make a requirements.txt file.

The manual steps are

virtualenv -p $(which python3) venv
venv/bin/pip install -r requirements.txt
venv/bin/pip install -r requirements.txt.in
venv/bin/pip freeze >> requirements.txt
rm -fr venv

Using pip freeze means the resulting results.txt contains detailed version numbers:

alabaster==0.7.12
Babel==2.7.0
certifi==2019.11.28
chardet==3.0.4
docutils==0.15.2
idna==2.8
imagesize==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
numpy==1.17.4
packaging==19.2
pandas==0.25.3
Pygments==2.5.2
pyparsing==2.4.5
python-dateutil==2.8.1
pytz==2019.3
requests==2.22.0
six==1.13.0
snowballstemmer==2.0.0
Sphinx==2.2.2
sphinxcontrib-applehelp==1.0.1
sphinxcontrib-devhelp==1.0.1
sphinxcontrib-htmlhelp==1.0.2
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.2
sphinxcontrib-serializinghtml==1.1.3
urllib3==1.25.7

This is automated with a make rule next.

Automating the step with a make rule

We have a nice Makefile rule that can be dropped into any Makefile that allows users to run

make requirements.txt

and it will use requirements.txt.in, perform the above steps, and output an updated requirements.txt with the latest compatible versions of software.

Here is the Makefile rule:

requirements.txt: %.txt : %.txt.in
    [ ! -e .requirements-env ] || exit 1
    virtualenv -p $(shell which python3) .$<-env
    .$<-env/bin/pip install -r $@
    .$<-env/bin/pip install -r $<
    echo "# You should not edit this file directly.  Instead, you should edit $<." >| $@
    .$<-env/bin/pip freeze >> $@
    rm -rf .$<-env

Summary of the make rule:

  • The first two lines create a virtual environment at .requirements-env/

  • The next two lines run pip install, first on requirements.txt (the existing version), then requirements.txt.in (which installs/updates any software packages in requirements.txt.in)

  • A comment is added to the top of the requirements.txt file to help give users a hint about where to update software requirements.

  • The pip freeze command is used to create a requirements.txt file from the current virtual environment

Refreshing requirements

To update the requirements, update the requirements.txt with these manual steps:

refresh_all_requirements:
    @cat /dev/null > requirements.txt
    @if [ $$(uname -s) == "Darwin" ]; then sleep 1; fi  # this is require because Darwin HFS+ only has second-resolution for timestamps.
    @touch requirements.txt.in
    @$(MAKE) requirements.txt

Now requirements.txt can be updated with

make refresh_all_requirements

This can be done periodically, and the new requirements.txt updated in the version control system.

Tags:    python    pip    version control    make    makefile   

November 2026

Baby Mac Crypto

March 2022

How to Read Ulysses

July 2020

Applied Gitflow

September 2019

Mocking AWS in Unit Tests

November 2017

A Hard(y) Math Problem