473,387 Members | 1,859 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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

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
22 6454
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
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
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
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

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

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

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

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
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
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
* 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
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

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

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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Dalan | last post by:
I have created a table and form for allowing the input of a unique customer number (not an ID autonumber number) which a customer would enter once after installing the database. I'm using DLookup...
2
by: James Radke | last post by:
Hello, I have a web application that contains class 'X' (note that this is one class of many contained in the application). Now, we need to create a pc based windows application which will use...
7
by: Amanda | last post by:
User is going to be transferring items out of combobox to listbox and vice versa keeping ascending and desending order respectively at all time. If user selects the last item in combobox, the...
5
by: Ed Jensen | last post by:
I'm really enjoying using the Python interactive interpreter to learn more about the language. It's fantastic you can get method help right in there as well. It saves a lot of time. With that...
4
by: ambikasd | last post by:
Hi, Can anyone tell me what is dynamic method dispatch? And in what scenario it is usefull?
3
by: gsspriya07 | last post by:
what is the method used for string comparison
13
by: Hussein B | last post by:
Hi, I'm familiar with static method concept, but what is the class method? how it does differ from static method? when to use it? -- class M: def method(cls, x): pass method =...
5
by: thisismykindabyte | last post by:
Hello, I was wondering if anyone could refer me to a good website that details what exactly makes up the GET and POST methods of a HttpRequest/Response class? Basically, I am trying to figure...
0
by: nick belshaw | last post by:
using PyGtk - no problems. I can draw onto an Image using a PixBuf, Drawable etc pixbuf = image.get_pixbuf() drawable = pixbuf.render_pixmap_and_mask()...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.