By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,009 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

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

P: n/a
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

Jan 5 '07 #1
Share this Question
Share on Google+
22 Replies


P: n/a
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
Jan 5 '07 #2

P: n/a
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

Jan 5 '07 #3

P: n/a
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

Jan 5 '07 #4

P: n/a
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
Jan 5 '07 #5

P: n/a

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

Jan 5 '07 #6

P: n/a
On 2007-01-05, Thomas Ploch <Th**********@gmx.netwrote:
>>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...
Jan 5 '07 #7

P: n/a
Grant Edwards schrieb:
On 2007-01-05, Thomas Ploch <Th**********@gmx.netwrote:
>>>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
Jan 5 '07 #8

P: n/a
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

Jan 5 '07 #9

P: n/a
On 2007-01-05, Thomas Ploch <Th**********@gmx.netwrote:
>>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
gr****@visi.com

Jan 5 '07 #10

P: n/a

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

Jan 5 '07 #11

P: n/a

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...
Jan 5 '07 #12

P: n/a
On Jan 4, 11:57 pm, belinda thom <b...@cs.hmc.eduwrote:
....
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']

Jan 5 '07 #13

P: n/a
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

Jan 5 '07 #14

P: n/a

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.

Jan 5 '07 #15

P: n/a
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")
Jan 5 '07 #16

P: n/a
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)
Jan 5 '07 #17

P: n/a
* 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.
Jan 5 '07 #18

P: n/a
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

Jan 6 '07 #19

P: n/a

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

Jan 6 '07 #20

P: n/a

Fuzzyman wrote:
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 ?
That still delays the check until the object is created.

You'd have to use metaclass programming to check this during class
creation time.
Carl Banks

Jan 6 '07 #21

P: n/a
Patrick Down 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?

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
I'd think twice before using a decorator. This just seems less clear
to read than simply raising NotImplementedError, and the traceback
points into the decorator instead of the function that you really care
about.

Jan 6 '07 #22

P: n/a
Patrick Down 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?
(snip)
Decorators to the rescue?
(snip convoluted code)

What a strange idea...
Jan 6 '07 #23

This discussion thread is closed

Replies have been disabled for this discussion.