Skip to content

Why can't a Literal string value be used to override a str? #9477

Answered by erictraut
awgymer asked this question in Q&A
Discussion options

You must be logged in to vote

Literal['KEY'] is a subtype of str, but they are not equivalent types. The a field is mutable, so subclasses of MyBase cannot safely override its type with a subtype of the base attribute's type. This can lead to errors if MySpecific is upcast to MyBase and then someone writes a str value to a that is not compatible with Literal['KEY'].

If you want to override a with a subtype in a type-safe manner, the attribute must be immutable in the base class. For example, if you were to define the model as frozen, its attributes would be considered immutable.

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@awgymer
Comment options

@erictraut
Comment options

@awgymer
Comment options

Answer selected by awgymer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants