Mypy: `@final` decorator is not honored. no error on override.

Created on 20 Oct 2020  Â·  5Comments  Â·  Source: python/mypy

Bug Report

Overriding class methods marked with @final (pep-0591) are not reported as errors. The example script will not produce an error with mypy even though it probably should.

9612 is potentially related, but they have a final problem in the other direction.

To Reproduce

from typing import final

class Base:
    @final
    def foo(self):
        pass

    def bar(self):
        pass

class Derived(Base):
    def foo(self):
        pass

Your Environment

✗ python --version && mypy --version && mypy foo.py 
Python 3.8.5
mypy 0.790
Success: no issues found in 1 source file
bug

Most helpful comment

I suppose this is because of mypy's general principle to not give errors for unannotated code. It feels like we should give the error if --check-untyped-defs is on, though.

All 5 comments

Hi, just wanted to note that when I tried this example, mypy gives the expected error about final as soon as any annotation is added to Derived's foo method. It's possible that the design was intentionally not to check final for untyped functions? Either way, the workaround is easy.

(There is the --check-untyped-defs option but that does not work to produce the error, which I guess makes sense since the docs say it enables checking the body of a function).

hey @a-reich, i cannot reproduce your statement. adding some other decorator didn't change the outcome.

class Derived(Base):
    @cached_property
    @final
    def foo(self):   
        return 2 

also using @final again with derived did nothing:

class Derived(Base):
    @final
    def foo(self):   
        return 2 

@tfranzel Did you look at the mypy-playground example I linked to? Here's the content:

from typing import final

class Base:
    @final
    def foo(self):
        pass

    def bar(self):
        pass

class Derived(Base):
    def foo(self) -> None:
        pass

It's the same as your OP but with a return annotation " -> None" added to Derived.foo. When I said this is fixed by adding an annotation I meant in the usual PEP 484 sense of type annotations, not decorators.

ahh sorry i somehow missed the link. i see, so the functionality is there. nonetheless kind of weird to only activate the check once a type hint is present.

I suppose this is because of mypy's general principle to not give errors for unannotated code. It feels like we should give the error if --check-untyped-defs is on, though.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mplanchard picture mplanchard  Â·  3Comments

JukkaL picture JukkaL  Â·  4Comments

squarewave24 picture squarewave24  Â·  3Comments

kissge picture kissge  Â·  3Comments

mxr picture mxr  Â·  3Comments