Home > Software engineering >  Python Cookie Cutter - Conditional Code Block?
Python Cookie Cutter - Conditional Code Block?

Time:11-04

Is it possible do some sort of conditional code block depending on the variable(s) set? I am trying to templatize a project which has some yaml configuration files. I would like a section of the yaml configuration to be optional though, but I do not know if there is a way to do this using cookiecutter. I do know that cookiecutter supports optional files and directories.

Here is an example:

{{ cookiecutter.pipeline_name }}:
  models:
    {{ cookiecutter.model_name }}:
      inference:
        instance_type: {{ cookiecutter.instance_type }}
        containers:
          - image:
              name: {{ cookiecutter.image_name }}
              repo: {{ cookiecutter.image_repo }}
              tag: {{ cookiecutter.image_tag }}
            provider: ecr
            data: {{ cookiecutter.model_artifact }}
        async_inference_config:
          s3_output_path: {{ cookiecutter.async_output_path }}
          max_concurrent_invocations_per_instance: {{ cookiecutter.max_invocations }}

The async_inference_config block should be optional. If the user doesn't fill in the async_output_path and the max_invocations variables, then the entire block should be removed. If this is not possible, I could create 2 different cookiecutter templates. But seems like a waste considering the only difference between these 2 templates would be the async_inference_config block.

CodePudding user response:

This is not really cookiecutter's functionality but rather Jinja2's one. Take a look at this part of it's documentation.

So your code should look similar to this one:

{{ cookiecutter.pipeline_name }}:
  models:
    {{ cookiecutter.model_name }}:
      inference:
        instance_type: {{ cookiecutter.instance_type }}
        containers:
          - image:
              name: {{ cookiecutter.image_name }}
              repo: {{ cookiecutter.image_repo }}
              tag: {{ cookiecutter.image_tag }}
            provider: ecr
            data: {{ cookiecutter.model_artifact }}
{% if cookiecutter.async_output_path and cookiecutter.max_invocations %}
        async_inference_config:
          s3_output_path: {{ cookiecutter.async_output_path }}
          max_concurrent_invocations_per_instance: {{ cookiecutter.max_invocations }}
{% endif %}

  • Related