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

J

jeremito

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
 
T

Thomas Ploch

jeremito said:
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
 
R

Robert Kern

jeremito said:
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
 
G

Gabriel Genellina

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
 
T

Thomas Ploch

Gabriel said:
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
 
J

jeremito

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

Thanks, that's what I needed. Since I am a complete novice at
Exceptions, I'll have to learn about it.
Jeremy
 
G

Grant Edwards

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.
 
T

Thomas Ploch

Grant said:
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
 
C

Carl Banks

jeremito said:
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
 
G

Grant Edwards

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.
 
B

belinda thom

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
 
B

belinda thom

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...
 
D

Dan Bishop

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']
 
R

Robert Kern

belinda said:
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
 
P

Paddy

belinda said:
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.
 
B

Bruno Desthuilliers

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")
 
B

Bruno Desthuilliers

Carl Banks a écrit :
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)
 
M

Mark Elston

* Paddy wrote (on 1/4/2007 10:20 PM):
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.)
 
P

Patrick Down

jeremito said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top