Skip to content

Conversation

@JacobHayes
Copy link
Contributor

@JacobHayes JacobHayes commented Jul 24, 2021

Change Summary

A field can be set with a default that is a subclass of the type hint when set together:

class MyStr(str):
    pass

class Simple(BaseModel):
    x: str = MyStr("test")

Additionally, a model can be instantiated with a subclass of the type hint: Simple(x=MyStr("works")).

However, when using model subclasses where the base sets a type hint, but the default (eg: MyStr) is set in a
subclass, the The type of {name}.{var_name} differs from the new default value exception is raised:

class MyStr(str):
    pass

class Base(BaseModel):
    x: str

class Sub(Base):
    x = MyStr("test")

I think rather than checking for an exact match on the type, we should be able to use lenient_issubclass. This seems pretty sane and didn't break any of the existing tests. My use case is actually using an Annotation(BaseModel) as the type hint, but setting subclass defaults like Vendor(Annotation), but that should follow from this simpler test case.

Related issue number

Checklist

  • Unit tests for the changes exist
  • Tests pass on CI and coverage remains at 100%
  • Documentation reflects the changes where applicable
  • changes/<pull request or issue id>-<github username>.md file added describing change
    (see changes/README.md for details)
  • My PR is ready to review, please add a comment including the phrase "please review" to assign reviewers

@JacobHayes
Copy link
Contributor Author

JacobHayes commented Jul 24, 2021

Please review when you have a moment. The change is a bit simpler ignoring whitespace changes.

Copy link
Collaborator

@PrettyWood PrettyWood left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense! Thank you 🙏

@PrettyWood PrettyWood merged commit acb4ff3 into pydantic:master Sep 4, 2021
@JacobHayes JacobHayes deleted the allow-subclass branch September 5, 2021 03:59
jpribyl pushed a commit to liquet-ai/pydantic that referenced this pull request Oct 7, 2021
…tic#3018)

* Add test for type hint subclass as default

* Fix support for using a subclass of an annotation as a default

* Add changes file

* add check in test

Co-authored-by: PrettyWood <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants