What is proper way to require a method to be overridden?

Discussion in 'Python' started by jeremito, Jan 5, 2007.

  1. jeremito

    jeremito Guest

    I am writing a class that is intended to be subclassed. What is the
    proper way to indicate that a sub class must override a method?

    Thanks,
    Jeremy
     
    jeremito, Jan 5, 2007
    #1
    1. Advertising

  2. jeremito

    Thomas Ploch Guest

    jeremito schrieb:
    > I am writing a class that is intended to be subclassed. What is the
    > proper way to indicate that a sub class must override a method?
    >
    > Thanks,
    > Jeremy
    >


    What do you mean by 'indicate'? Writing it to the docstring of the
    class/method? Writing a comment?

    class Foo:
    """
    When inheriting from Foo, method foo must be
    overridden. Otherwise SPAM.
    """
    def foo(self):
    print 'bar'

    class Bar(Foo):
    def __init__(self):
    Foo.__init__(self)

    # Has to be defined to override the base class's method
    # when inheriting from class Foo. Otherwise: SPAM
    def foo(self):
    print 'foo'

    I don't know any other way.

    Thomas
     
    Thomas Ploch, Jan 5, 2007
    #2
    1. Advertising

  3. jeremito

    Robert Kern Guest

    jeremito wrote:
    > I am writing a class that is intended to be subclassed. What is the
    > proper way to indicate that a sub class must override a method?


    raise NotImplementedError

    --
    Robert Kern

    "I have come to believe that the whole world is an enigma, a harmless enigma
    that is made terrible by our own mad attempt to interpret it as though it had
    an underlying truth."
    -- Umberto Eco
     
    Robert Kern, Jan 5, 2007
    #3
  4. At Thursday 4/1/2007 23:52, jeremito wrote:

    >I am writing a class that is intended to be subclassed. What is the
    >proper way to indicate that a sub class must override a method?


    If any subclass *must* override a method, raise NotImplementedError
    in the base class (apart from documenting how your class is supposed
    to be used).


    --
    Gabriel Genellina
    Softlab SRL






    __________________________________________________
    Preguntá. Respondé. Descubrí.
    Todo lo que querías saber, y lo que ni imaginabas,
    está en Yahoo! Respuestas (Beta).
    ¡Probalo ya!
    http://www.yahoo.com.ar/respuestas
     
    Gabriel Genellina, Jan 5, 2007
    #4
  5. jeremito

    Thomas Ploch Guest

    Gabriel Genellina schrieb:
    > At Thursday 4/1/2007 23:52, jeremito wrote:
    >
    >> I am writing a class that is intended to be subclassed. What is the
    >> proper way to indicate that a sub class must override a method?

    >
    > If any subclass *must* override a method, raise NotImplementedError in
    > the base class (apart from documenting how your class is supposed to be
    > used).
    >
    >


    I learn so much from this list. I didn't even know this error existed.

    Thomas
     
    Thomas Ploch, Jan 5, 2007
    #5
  6. jeremito

    jeremito Guest

    Gabriel Genellina wrote:
    > At Thursday 4/1/2007 23:52, jeremito wrote:
    >
    > >I am writing a class that is intended to be subclassed. What is the
    > >proper way to indicate that a sub class must override a method?

    >
    > If any subclass *must* override a method, raise NotImplementedError
    > in the base class (apart from documenting how your class is supposed
    > to be used).
    >
    >
    > --
    > Gabriel Genellina
    > Softlab SRL
    >


    Thanks, that's what I needed. Since I am a complete novice at
    Exceptions, I'll have to learn about it.
    Jeremy
     
    jeremito, Jan 5, 2007
    #6
  7. On 2007-01-05, Thomas Ploch <> wrote:

    >>> I am writing a class that is intended to be subclassed. What
    >>> is the proper way to indicate that a sub class must override a
    >>> method?

    >>
    >> If any subclass *must* override a method, raise
    >> NotImplementedError in the base class (apart from documenting
    >> how your class is supposed to be used).

    >
    > I learn so much from this list. I didn't even know this error existed.


    And remember: even if it didn't, you could have created your
    own:

    ------------------------------foo.py------------------------------
    class NotImplementedError(Exception):
    pass

    def foo():
    print "hi there"
    msg = "there's a penguin on the telly!"
    raise NotImplementedError(msg)
    print "how are you?"

    foo()
    ------------------------------------------------------------------

    $ python foo.py
    hi there
    Traceback (most recent call last):
    File "foo.py", line 10, in ?
    foo()
    File "foo.py", line 7, in foo
    raise NotImplementedError(msg)
    __main__.NotImplementedError: there's a penguin on the telly!


    A few carefully thought-out exceptions can often eliminate the
    need for a lot of messy code.

    --
    Grant Edwards grante Yow! I'll show you MY
    at telex number if you show
    visi.com me YOURS...
     
    Grant Edwards, Jan 5, 2007
    #7
  8. jeremito

    Thomas Ploch Guest

    Grant Edwards schrieb:
    > On 2007-01-05, Thomas Ploch <> wrote:
    >
    >>>> I am writing a class that is intended to be subclassed. What
    >>>> is the proper way to indicate that a sub class must override a
    >>>> method?
    >>> If any subclass *must* override a method, raise
    >>> NotImplementedError in the base class (apart from documenting
    >>> how your class is supposed to be used).

    >> I learn so much from this list. I didn't even know this error existed.

    >
    > And remember: even if it didn't, you could have created your
    > own:


    Erm, it wasn't me who asked. I just wanted to say that I didn't know
    that there is a NotImplementedError. Havn't seen it before.

    :)

    Thomas
     
    Thomas Ploch, Jan 5, 2007
    #8
  9. jeremito

    Carl Banks Guest

    jeremito wrote:
    > I am writing a class that is intended to be subclassed. What is the
    > proper way to indicate that a sub class must override a method?


    You can't (easily).

    If your subclass doesn't override a method, then you'll get a big fat
    AttributeError when someone tries to call it. But this doesn't stop
    someone from defining a subclass that fails to override the method.
    Only when it's called will the error show up. You can, as others have
    noted, define a method that raises NotImplementedError. But this still
    doesn't stop someone from defining a subclass that fails to override
    the method. The error still only occurs when the method is called.

    There are some advantages to using NotImplementedError:

    1. It documents the fact that a method needs to be overridden
    2. It lets tools such as pylint know that this is an abstract method
    3. It results in a more informative error message

    But, in the end, if someone wants to define a class that defiantly
    refuses to declare a method, you can't stop them.


    Carl Banks
     
    Carl Banks, Jan 5, 2007
    #9
  10. On 2007-01-05, Thomas Ploch <> wrote:

    >>> I learn so much from this list. I didn't even know this error
    >>> existed.

    >>
    >> And remember: even if it didn't, you could have created your
    >> own:

    >
    > Erm, it wasn't me who asked. I just wanted to say that I didn't know
    > that there is a NotImplementedError.


    Sorry, I sort of lost track. You can still invent your own
    Exceptions anyway. ;) Just don't do what I do and take the
    lazy way out:

    raise "method not implemented"

    That's considered bad form these days.

    --
    Grant Edwards
     
    Grant Edwards, Jan 5, 2007
    #10
  11. jeremito

    belinda thom Guest

    On Jan 4, 2007, at 7:56 PM, Thomas Ploch wrote:

    > Gabriel Genellina schrieb:
    >> At Thursday 4/1/2007 23:52, jeremito wrote:
    >>
    >>> I am writing a class that is intended to be subclassed. What is the
    >>> proper way to indicate that a sub class must override a method?

    >>
    >> If any subclass *must* override a method, raise
    >> NotImplementedError in
    >> the base class (apart from documenting how your class is supposed
    >> to be
    >> used).
    >>
    >>

    >
    > I learn so much from this list. I didn't even know this error existed.


    Me too.

    I was looking for a definitive list of Python errors, although I
    realize some folks do things like:

    class foo :
    def __init__() :
    <whatever>

    def bar() :
    abstract

    class baz(foo) :
    def __init__() :
    <whatever>

    def bar() :
    <shomething useful>

    This does what you want in that if baz's bar wasn't defined, calling
    this method on a baz instance would give some kind of "variable not
    found error."

    I imagine the NotImplementedError is actually a defined object, but I
    really don't know.

    So, back to my question: is a catalog of standard python errors
    available? I've looked on the python site but had no success.

    Thanks,

    --b
     
    belinda thom, Jan 5, 2007
    #11
  12. jeremito

    belinda thom Guest

    On Jan 4, 2007, at 9:28 PM, Carl Banks wrote:

    > jeremito wrote:
    >> I am writing a class that is intended to be subclassed. What is the
    >> proper way to indicate that a sub class must override a method?

    >
    > You can't (easily).
    >
    > If your subclass doesn't override a method, then you'll get a big fat
    > AttributeError when someone tries to call it. But this doesn't stop
    > someone from defining a subclass that fails to override the method.
    > Only when it's called will the error show up. You can, as others have
    > noted, define a method that raises NotImplementedError. But this
    > still
    > doesn't stop someone from defining a subclass that fails to override
    > the method. The error still only occurs when the method is called.
    >
    > There are some advantages to using NotImplementedError:
    >
    > 1. It documents the fact that a method needs to be overridden
    > 2. It lets tools such as pylint know that this is an abstract method
    > 3. It results in a more informative error message
    >
    > But, in the end, if someone wants to define a class that defiantly
    > refuses to declare a method, you can't stop them.


    This is the con of a dynamic language...
     
    belinda thom, Jan 5, 2007
    #12
  13. jeremito

    Dan Bishop Guest

    On Jan 4, 11:57 pm, belinda thom <> wrote:
    ....
    > So, back to my question: is a catalog of standard python errors
    > available? I've looked on the python site but had no success.


    >>> [name for name in dir(__builtins__) if name.endswith('Error')]

    ['ArithmeticError', 'AssertionError', 'AttributeError', 'EOFError',
    'EnvironmentError', 'FloatingPointError', 'IOError', 'ImportError',
    'IndentationError', 'IndexError', 'KeyError', 'LookupError',
    'MemoryError', 'NameError', 'NotImplementedError', 'OSError',
    'OverflowError', 'ReferenceError', 'RuntimeError', 'StandardError',
    'SyntaxError', 'SystemError', 'TabError', 'TypeError',
    'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
    'UnicodeError', 'UnicodeTranslateError', 'ValueError',
    'ZeroDivisionError']
     
    Dan Bishop, Jan 5, 2007
    #13
  14. jeremito

    Robert Kern Guest

    belinda thom wrote:

    > I imagine the NotImplementedError is actually a defined object, but I
    > really don't know.


    It is.

    > So, back to my question: is a catalog of standard python errors
    > available? I've looked on the python site but had no success.


    http://docs.python.org/lib/module-exceptions.html

    --
    Robert Kern

    "I have come to believe that the whole world is an enigma, a harmless enigma
    that is made terrible by our own mad attempt to interpret it as though it had
    an underlying truth."
    -- Umberto Eco
     
    Robert Kern, Jan 5, 2007
    #14
  15. jeremito

    Paddy Guest

    belinda thom wrote:

    > On Jan 4, 2007, at 9:28 PM, Carl Banks wrote:
    >
    > > jeremito wrote:
    > >> I am writing a class that is intended to be subclassed. What is the
    > >> proper way to indicate that a sub class must override a method?

    > >
    > > You can't (easily).
    > >
    > > If your subclass doesn't override a method, then you'll get a big fat
    > > AttributeError when someone tries to call it. But this doesn't stop
    > > someone from defining a subclass that fails to override the method.
    > > Only when it's called will the error show up. You can, as others have
    > > noted, define a method that raises NotImplementedError. But this
    > > still
    > > doesn't stop someone from defining a subclass that fails to override
    > > the method. The error still only occurs when the method is called.
    > >
    > > There are some advantages to using NotImplementedError:
    > >
    > > 1. It documents the fact that a method needs to be overridden
    > > 2. It lets tools such as pylint know that this is an abstract method
    > > 3. It results in a more informative error message
    > >
    > > But, in the end, if someone wants to define a class that defiantly
    > > refuses to declare a method, you can't stop them.

    >
    > This is the con of a dynamic language...

    In a language that has statements to force the user to over-ride a
    method when a class is sub-classed, what is to stop the lazy
    sub-classer from doing the equivalent of:

    define override_me(self, ...):
    pass

    And so get code through the compiler,, allowing them to 'meet their
    targets'?

    - Paddy.
     
    Paddy, Jan 5, 2007
    #15
  16. jeremito a écrit :
    > I am writing a class that is intended to be subclassed. What is the
    > proper way to indicate that a sub class must override a method?


    class Base(object):
    def method_to_override(self, *args, **kw):
    raise NotImplementedError("You need to override this method")
     
    Bruno Desthuilliers, Jan 5, 2007
    #16
  17. Carl Banks a écrit :
    > jeremito wrote:
    >
    >>I am writing a class that is intended to be subclassed. What is the
    >>proper way to indicate that a sub class must override a method?

    >
    >
    > You can't (easily).
    >
    > If your subclass doesn't override a method, then you'll get a big fat
    > AttributeError when someone tries to call it.


    "override" implies that the method is already defined in one of the
    parent classes. So there's no reason for an AttributeError here...

    (snip)
     
    Bruno Desthuilliers, Jan 5, 2007
    #17
  18. jeremito

    Mark Elston Guest

    * Paddy wrote (on 1/4/2007 10:20 PM):
    > belinda thom wrote:
    >
    >> On Jan 4, 2007, at 9:28 PM, Carl Banks wrote:
    >>
    >>> jeremito wrote:
    >>>> I am writing a class that is intended to be subclassed. What is the
    >>>> proper way to indicate that a sub class must override a method?
    >>> You can't (easily).
    >>>
    >>> If your subclass doesn't override a method, then you'll get a big fat
    >>> AttributeError when someone tries to call it. But this doesn't stop
    >>> someone from defining a subclass that fails to override the method.
    >>> Only when it's called will the error show up. You can, as others have
    >>> noted, define a method that raises NotImplementedError. But this
    >>> still
    >>> doesn't stop someone from defining a subclass that fails to override
    >>> the method. The error still only occurs when the method is called.
    >>>
    >>> There are some advantages to using NotImplementedError:
    >>>
    >>> 1. It documents the fact that a method needs to be overridden
    >>> 2. It lets tools such as pylint know that this is an abstract method
    >>> 3. It results in a more informative error message
    >>>
    >>> But, in the end, if someone wants to define a class that defiantly
    >>> refuses to declare a method, you can't stop them.

    >> This is the con of a dynamic language...

    > In a language that has statements to force the user to over-ride a
    > method when a class is sub-classed, what is to stop the lazy
    > sub-classer from doing the equivalent of:
    >
    > define override_me(self, ...):
    > pass
    >
    > And so get code through the compiler,, allowing them to 'meet their
    > targets'?
    >


    And this *could* be perfectly suitable if the class really doesn't make
    use of the method. (I have seen this in poorly designed super classes
    and interface classes - sigh.)

    > - Paddy.
    >
     
    Mark Elston, Jan 5, 2007
    #18
  19. jeremito

    Patrick Down Guest

    jeremito wrote:
    > I am writing a class that is intended to be subclassed. What is the
    > proper way to indicate that a sub class must override a method?
    >
    > Thanks,
    > Jeremy


    Decorators to the rescue?

    def must_override(f):
    def t(*args):
    raise NotImplementedError("You must override " + f.__name__)
    return t

    class Foo:
    @must_override
    def Bar(x,y): pass

    Foo().Bar()

    Traceback (most recent call last):
    File "testit.py", line 14, in ?
    Foo().Bar()
    File "testit.py", line 5, in t
    raise NotImplementedError("You must override " + f.__name__)
    NotImplementedError: You must override Bar
     
    Patrick Down, Jan 5, 2007
    #19
  20. jeremito

    Fuzzyman Guest

    Carl Banks wrote:
    > jeremito wrote:
    > > I am writing a class that is intended to be subclassed. What is the
    > > proper way to indicate that a sub class must override a method?

    >
    > You can't (easily).
    >


    Well...

    How about not defining it on the base class, but check in the
    constructor that the attribute exists and that it is of type
    FunctionType ?

    Fuzzyman
    http://www.voidspace.org.uk/python/articles.shtml
     
    Fuzzyman, Jan 6, 2007
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Patel
    Replies:
    6
    Views:
    40,721
    Randall R Schulz
    Oct 23, 2003
  2. Patel
    Replies:
    1
    Views:
    433
    Harald Hein
    Oct 23, 2003
  3. Hermann Lichte

    Overridden method doesn't get invoked

    Hermann Lichte, Oct 27, 2006, in forum: C++
    Replies:
    1
    Views:
    334
    Kai-Uwe Bux
    Oct 27, 2006
  4. Replies:
    0
    Views:
    380
  5. Replies:
    2
    Views:
    390
Loading...

Share This Page