views:

1159

answers:

3

In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?

+2  A: 

As far as I know, there is no special way to indicate an override in Python. You just define the method and include a docstring, like always.

musicfreak
+6  A: 

Python ain't Java. There's of course no such thing really as compile-time checking.

I think a comment in the docstring is plenty. This allows any user of your method to type help(obj.method) and see that the method is an override.

You can also explicitly extend an interface with class Foo(Interface), which will allow users to type help(Interface.method) to get an idea about the functionality your method is intended to provide.

Triptych
The real point of `@Override` in Java isn't to document - it's to catch a mistake when you intended to override a method, but ended up defining a new one (e.g. because you misspelled a name; in Java, it may also happen because you used the wrong signature, but this isn't an issue in Python - but spelling mistake still is).
Pavel Minaev
+1  A: 

If you want this for documentation purposes only, you can define your own override decorator:

def override(f):
    return f


class MyClass (BaseClass):

    @override
    def method(self):
        pass

This is really nothing but eye-candy, unless you create override(f) in such a way that is actually checks for an override.

But then, this is Python, why write it like it was Java?

Ber