'Is there a way to apply typing.cast globally?

class FooBar:
    def __init__(self):
        self.attr: Optional[str] = None
    
    def f(self):
        self.attr = 'a'
        print(self.attr.title())

If I tried to check the code above using MyPy, I would get an error: NoneType object does not have method title. Of course, I can use typing.cast locally, in f method, like so:

    def f(self):
        self.attr = 'a'
        cast(str, self.attr)
        print(self.attr.title())

But this would only cast type to the variable locally, that is in the f method. Is there a way to cast type globally so MyPy will not complain again?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source