Search code examples
pythonsubclassmypy

How to declare additional attributes when subclassing str?


Consider the following class:

class StrWithInt(str):
    def __new__(cls, content, value: int):
        ret = super().__new__(cls, content)
        ret.value = value
        return ret

This class just works fine, but when using mypy, the following error occurs: "StrWithInt" has no attribute "value" [attr-defined]

Is there some way to explicitly state the attribute in this case? What is the proper way to solve this issue?

Note that this is a minimal example and not using a subclass of str is not an option in the non-minimal example.


Solution

  • class StrWithInt(str):
        value: int
    
        def __new__(cls, content, value: int):
            ret = super().__new__(cls, content)
            ret.value = value
            return ret