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 16, 2023
1 parent 7f7c3b3 commit e984b0c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
22 changes: 14 additions & 8 deletions src/generators/python/presets/Pydantic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ 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']}'''`
: '';

return `${params.property.propertyName}: ${type} = Field(${alias})`;
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 (
alias && defaultValue
? `${propertyName}: ${type} = Field(${alias}, ${defaultValue})`
: alias
? `${propertyName}: ${type} = Field(${alias})`
: defaultValue
? `${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 e984b0c

Please sign in to comment.