【问题标题】:Argument parser from a Pydantic modelPydantic 模型中的参数解析器
【发布时间】:2022-06-24 17:10:52
【问题描述】:

如何从 Pydantic 模型创建参数解析器 (argparse.ArgumentParser)?

我有一个 Pydantic 模型:

from pydantic import BaseModel, Field

class MyItem(BaseModel):
    name: str
    age: int
    color: str = Field(default="red", description="Color of the item")

我想使用命令行创建MyItem 的实例:

python myscript.py --name Jack --age 10 --color blue

这应该屈服于:

item = MyItem(name="Jack", age=10, color="blue")
... # Process the item

我不想硬编码命令行参数,我想从 Pydantic 模型动态创建命令行参数。

【问题讨论】:

    标签: python argparse pydantic


    【解决方案1】:

    我自己找到了答案。只是:

    1. 创建参数解析器,
    2. 将模型的字段作为解析器的参数,
    3. 解析命令行参数,
    4. 将参数转换为 dict 并将它们传递给模型并
    5. 处理模型实例
    import argparse
    from pydantic import BaseModel, Field
    
    class MyItem(BaseModel):
        name: str
        age: int
        color: str = Field(default="red", description="Color of the item")
    
    def add_model(parser, model):
        "Add Pydantic model to an ArgumentParser"
        fields = model.__fields__
        for name, field in fields.items():
            parser.add_argument(
                f"--{name}", 
                dest=name, 
                type=field.type_, 
                default=field.default,
                help=field.field_info.description,
            )
    
    # 1. Create and parse command line arguments
    parser = argparse.ArgumentParser()
    
    # 2. Turn the fields of the model as arguments of the parser
    add_model(parser, MyItem)
    
    # 3. Parse the command-line arguments
    args = parser.parse_args()
    
    # 4. Turn the arguments as dict and pass them to the model
    item = MyItem(**vars(args))
    
    # 5. Do whatever
    print(repr(item))
    ...
    

    如果您希望向解析器添加更多功能,也可以添加子解析器:https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 1970-01-01
      • 2019-09-09
      • 2020-08-13
      • 2021-11-05
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2022-10-21
      相关资源
      最近更新 更多