Skip to content

Commit

Permalink
fix: set default to None for optional fields
Browse files Browse the repository at this point in the history
- fix in Pydantic Python Generator for optional values.
- default=None should be added in `Field()` if the property is optional.
- updated the test snapshot to compare the new default value argument.

Signed-off-by: Harshil Jani <harshiljani2002@gmail.com>
  • Loading branch information
Harshil-Jani committed Dec 19, 2023
1 parent 7f7c3b3 commit 1643da1
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
exports[`Should be able to render python models and should log expected output to console: class-model 1`] = `
Array [
"class Root(BaseModel):
optionalField: Optional[str] = Field(alias='''this field is optional''')
optionalField: Optional[str] = Field(alias='''this field is optional''', default=None)
requiredField: str = Field(alias='''this field is required''')
noDescription: Optional[str] = Field()
options: Optional[Options] = Field()
noDescription: Optional[str] = Field(default=None)
options: Optional[Options] = Field(default=None)
",
]
`;
Expand Down
18 changes: 11 additions & 7 deletions src/generators/python/presets/Pydantic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,18 @@ const PYTHON_PYDANTIC_CLASS_PRESET: ClassPresetType<PythonOptions> = {
);
},
property(params) {
const type = params.property.required
? params.property.property.type
: `Optional[${params.property.property.type}]`;
const alias = params.property.property.originalInput['description']
? `alias='''${params.property.property.originalInput['description']}'''`
: '';
const { propertyName, required, property } = params.property;
const type = required ? property.type : `Optional[${property.type}]`;
const description = property.originalInput['description'];
const alias = description ? `alias='''${description}'''` : '';
const defaultValue = required ? '' : 'default=None';

return `${params.property.propertyName}: ${type} = Field(${alias})`;
if (alias && defaultValue) {
return `${propertyName}: ${type} = Field(${alias}, ${defaultValue})`;
} else if (alias) {
return `${propertyName}: ${type} = Field(${alias})`;
}
return `${propertyName}: ${type} = Field(${defaultValue})`;
},
ctor: () => '',
getter: () => '',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ exports[`PYTHON_PYDANTIC_PRESET should render pydantic for class 1`] = `
prop: Optional[str] = Field(alias='''test
multi
line
description''')
additionalProperties: Optional[dict[Any, Any]] = Field()
description''', default=None)
additionalProperties: Optional[dict[Any, Any]] = Field(default=None)
"
`;

0 comments on commit 1643da1

Please sign in to comment.