473,394 Members | 1,749 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,394 software developers and data experts.

Is this Pythonic?


Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what
I have in mind:

class Foo: # abstract superclass
def bar(self):
raise Exception, "Implemented by subclass"
def baz(self):
raise Exception, "Implemented by subclass"

class Concrete(Foo):
def bar(self):
#...actual implemtation...
def baz(self):
#...actual implemtation...


--
Email: zen19725 at zen dot co dot uk
Aug 1 '05 #1
12 1444
phil hunt wrote:
Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what
I have in mind:

class Foo: # abstract superclass
def bar(self):
raise Exception, "Implemented by subclass"
def baz(self):
raise Exception, "Implemented by subclass"


Change those to "raise NotImplementedError('blah')" instead and you'll
be taking the more idiomatic approach.

-Peter
Aug 1 '05 #2
phil hunt wrote:
Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what


See http://docs.python.org/lib/module-ex...s.html#l2h-298
(NotImplementedError)
--
Benji York
Aug 1 '05 #3
Peter

To my mind, this kind of setup (interface class, or abstact class) is more
usually used in static languages to benefit polymorphism - but python is
dynamically typed, so in which situations would this setup be useful in a
python program? You see, I expected your post to say that it wouldn't
even be necessary, but you didn't :)

I have spent a little effort training myself not to bother setting up
class hierarchies like this in python, due to the fact that I use Delphi a
lot at work (I do pretty much the code below to let myself know when an
inherited/abstract class method is being called in error).

regards
Caleb

On Mon, 01 Aug 2005 18:52:02 +0200, Peter Hansen <pe***@engcorp.com> wrote:
phil hunt wrote:
Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what I
have in mind:
class Foo: # abstract superclass
def bar(self):
raise Exception, "Implemented by subclass"
def baz(self):
raise Exception, "Implemented by subclass"


Change those to "raise NotImplementedError('blah')" instead and you'll
be taking the more idiomatic approach.

-Peter


Aug 1 '05 #4
Caleb Hattingh a écrit :
Peter

To my mind, this kind of setup (interface class, or abstact class
are two different things.
) is
more usually used in static languages
True.
to benefit polymorphism
This is a good reason to use an interface in Java. C++ has no notion of
'interface', so you have to use abstract classes to achieve the same result.
- but
python is dynamically typed, so in which situations would this setup be
useful in a python program?
Abstract classes ? When you want to factor out common implementation in
a base class and force derived class to implement specific parts. One
common use case is the template method (aka "hollywood", aka "don't call
us, we'll call you") pattern.
You see, I expected your post to say that
it wouldn't even be necessary, but you didn't :)
Implementation inheritance is never "necessary". Nor are OO, modularity,
structured programming, and human-readable programming languages !-)

It's a fact that inheritence being "only" (err... should I say "mostly"
?) an implementation mechanism in dynamic languages, class hierarchies
tends to be much more flat. But this doesn't mean that abstract base
classes are useless.
I have spent a little effort training myself not to bother setting up
class hierarchies like this in python


I had this pattern too.
Aug 1 '05 #5
phil hunt wrote:
Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what
I have in mind:

class Foo: # abstract superclass
def bar(self):
raise Exception, "Implemented by subclass"
def baz(self):
raise Exception, "Implemented by subclass"

class Concrete(Foo):
def bar(self):
#...actual implemtation...
def baz(self):
#...actual implemtation...


Yes, but raise NotImplementedError instead of Exception. Another trick
you can use is to prevent people from instantiating the abstract class:

class Foo:
def __init__(self):
if self.__class__ is Foo:
raise NotImplementedError
...

def bar(self):
raise NotImplementedError

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Everything's gonna be all right / Everything's gonna be okay
-- Sweetbox
Aug 1 '05 #6
On Mon, 01 Aug 2005 12:52:02 -0400, Peter Hansen <pe***@engcorp.com> wrote:
phil hunt wrote:
Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what
I have in mind:

class Foo: # abstract superclass
def bar(self):
raise Exception, "Implemented by subclass"
def baz(self):
raise Exception, "Implemented by subclass"


Change those to "raise NotImplementedError('blah')" instead and you'll
be taking the more idiomatic approach.


Ta

--
Email: zen19725 at zen dot co dot uk
Aug 1 '05 #7
On Mon, 01 Aug 2005 22:01:06 +0200, Caleb Hattingh <ca****@telkomsa.net> wrote:
Peter

To my mind, this kind of setup (interface class, or abstact class) is more
usually used in static languages to benefit polymorphism - but python is
dynamically typed, so in which situations would this setup be useful in a
python program? You see, I expected your post to say that it wouldn't
even be necessary, but you didn't :)
I realise it's not necessary. I just thought it would be nice to
document the interfaces my concrete classes will be using.
I have spent a little effort training myself not to bother setting up
class hierarchies like this in python, due to the fact that I use Delphi a
lot at work (I do pretty much the code below to let myself know when an
inherited/abstract class method is being called in error).


I started doing OO stuff with Smalltalk, where it isn't necessary,
then moved to C++, where it is, and liked it.

--
Email: zen19725 at zen dot co dot uk
Aug 2 '05 #8
On Mon, 01 Aug 2005 14:07:46 -0700, Erik Max Francis <ma*@alcyone.com> wrote:

Yes, but raise NotImplementedError instead of Exception. Another trick
you can use is to prevent people from instantiating the abstract class:

class Foo:
def __init__(self):
if self.__class__ is Foo:
raise NotImplementedError
...

def bar(self):
raise NotImplementedError


That's a clever trick, but it's obvious from the code that the class
is intended to be abstract, so if people are stupid enough to shoot
themselves in the foot by creating an instance, I don't feel like
adding extra code to protect themselves from their stupidity.

--
Email: zen19725 at zen dot co dot uk
Aug 2 '05 #9
phil hunt wrote:
That's a clever trick, but it's obvious from the code that the class
is intended to be abstract, so if people are stupid enough to shoot
themselves in the foot by creating an instance, I don't feel like
adding extra code to protect themselves from their stupidity.


Right. But even if you're not worried about stupidity, it's useful to
have it fail in an explicit way as early as possible, rather than later
on. With that addition, the moment you try to create an instance of an
abstract class, you get an exception. Even if it's just a typo, and not
severe negligence, that helps the problem get fixed sooner, rather than
later.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Morality is a weakness of the mind.
-- Arthur Rimbaud
Aug 2 '05 #10
ze******@zen.co.uk (phil hunt) writes:
Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what
I have in mind:

class Foo: # abstract superclass
def bar(self):
raise Exception, "Implemented by subclass"
def baz(self):
raise Exception, "Implemented by subclass"

class Concrete(Foo):
def bar(self):
#...actual implemtation...
def baz(self):
#...actual implemtation...


Well, I guess you know this, but if Foo contains no implementation at
all, why inherit from it? It would (possibly) be more Pythonic to
define an interface instead, or just use duck typing.

Cheers,
mwh

--
nonono, while we're making wild conjectures about the behavior
of completely irrelevant tasks, we must not also make serious
mistakes, or the data might suddenly become statistically valid.
-- Erik Naggum, comp.lang.lisp
Aug 2 '05 #11
On Tue, 02 Aug 2005 08:31:27 GMT, Michael Hudson <mw*@python.net> wrote:
ze******@zen.co.uk (phil hunt) writes:
Suppose I'm writing an abstract superclass which will have some
concrete subclasses. I want to signal in my code that the subclasses
will implement certan methods. Is this a Pythonic way of doing what
I have in mind:

class Foo: # abstract superclass
def bar(self):
raise Exception, "Implemented by subclass"
def baz(self):
raise Exception, "Implemented by subclass"

class Concrete(Foo):
def bar(self):
#...actual implemtation...
def baz(self):
#...actual implemtation...
Well, I guess you know this, but if Foo contains no implementation at
all, why inherit from it?


(in fact the class I'm using/creating does contain some
implementation)
It would (possibly) be more Pythonic to
define an interface instead,


Does Python have the concept of an interface? When was that added?
--
Email: zen19725 at zen dot co dot uk
Aug 2 '05 #12
ze******@zen.co.uk (phil hunt) writes:
It would (possibly) be more Pythonic to
define an interface instead,


Does Python have the concept of an interface? When was that added?


It doesn't have one included, but there are at least two
implementations, zope.interface and PyProtocols (I'm sure google will
find you more on both of these).

--
... with these conditions cam the realisation that ... nothing
turned a perfectly normal healthy individual into a great political
or military leader better than irreversible brain damage.
-- The Hitch-Hikers Guide to the Galaxy, Episode 11
Aug 2 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Tom Evans | last post by:
My basic question: If I have a specific interface which I know is going to be implemented by a number of classes, but there is no implementation commonality between them, what is the preferred...
1
by: asdf sdf | last post by:
i need some advice. i'm a back end programmer historically, but have been exploring python for webapps and enjoying it. i need to build some simple Win client-server or standalone apps. the...
12
by: Nickolay Kolev | last post by:
Hi all, I would like to find a more pythonic way of solving the following: Having a string consisting of letters only, find out the total sound score of the string. The sound score is...
15
by: Ville Vainio | last post by:
Pythonic Nirvana - towards a true Object Oriented Environment ============================================================= IPython (by Francois Pinard) recently (next release - changes are...
10
by: Bulba! | last post by:
Hello everyone, I'm reading the rows from a CSV file. csv.DictReader puts those rows into dictionaries. The actual files contain old and new translations of software strings. The dictionary...
2
by: Marcus Goldfish | last post by:
I'd like advice/opinions on when it is appropriate to do attribute/property validation in python. I'm coming from a C#/Java background, where of course tons of "wasted" code is devoted to...
11
by: Charles Krug | last post by:
I've a function that needs to maintain an ordered sequence between calls. In C or C++, I'd declare the pointer (or collection object) static at the function scope. What's the Pythonic way to...
4
by: Carl J. Van Arsdall | last post by:
It seems the more I come to learn about Python as a langauge and the way its used I've come across several discussions where people discuss how to do things using an OO model and then how to design...
3
by: jnair | last post by:
My Tead Lead my object counter code seen below is not pythonic class E(object): _count = 0 def __init__(self): E._count += 1 count = property(lambda self: E._count ) def test(): if...
26
by: Frank Samuelson | last post by:
I love Python, and it is one of my 2 favorite languages. I would suggest that Python steal some aspects of the S language. ------------------------------------------------------- 1. Currently...
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: 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: 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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.