【问题标题】:Python Cookie Cutter - Conditional Code Block?Python Cookie Cutter - 条件代码块?
【发布时间】:2022-11-03 15:50:45
【问题描述】:

是否可以根据设置的变量执行某种条件代码块?我正在尝试模板化具有一些 yaml 配置文件的项目。我希望 yaml 配置的一部分是可选的,但我不知道是否有办法使用cookiecutter 来做到这一点。我知道cookiecutter 支持可选文件和目录。

这是一个例子:

{{ 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 }}

async_inference_config 块应该是可选的。如果用户没有填写async_output_pathmax_invocations 变量,那么应该删除整个块。如果这不可能,我可以创建 2 个不同的 cookiecutter 模板。但考虑到这两个模板之间的唯一区别是async_inference_config 块,这似乎是一种浪费。

【问题讨论】:

标签: python templates cookiecutter


【解决方案1】:

这不是 cookiecutter 的真正功能,而是 Jinja2 的功能。 看看this part of it's documentation.

所以你的代码应该和这个类似:

{{ 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 %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多