13

I'm trying to model an API request in Pydantic. I have to model a field called "from". Since "from" is a keyword in python, Pydantic throws an error.

Model

class MyRequest(BaseModel):
    foo: str
    abc: int
    from: int

Error thrown by Pydantic

File "test.py", line 6
    from: int

SyntaxError: invalid syntax

Is there to model this "from" field? Changing the parameter name is not an option.

shrshank
  • 131
  • 1
  • 3

1 Answers1

20

Use an alias:

class MyRequest(BaseModel):
    foo: str
    abc: int
    from_field: int = Field(..., alias='from')
SColvin
  • 11,584
  • 6
  • 57
  • 71
  • 1
    how should it be instantiated? `MyRequest(foo='a', abc=1, from=2)` still raises a `SyntaxError`, while using `from_field` instead of `from` will lead to a `pydantic.ValidationError`. – Algebra8 Mar 09 '21 at 23:21
  • 4
    Have you tried `MyRequest(**{'foo': 'a', 'abc': 1, 'from': 2})`? – SColvin Mar 10 '21 at 16:37