473,748 Members | 3,107 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Abstract Base Classes

Howdy all,

Okay, so Guido doesn't like Abstract Base Classes[0], and interfaces
are the way of the future[1]. But they're not here now, and I
understand ABCs better.

I want my modules to (sometimes) define an abstract base exception
class, that all other exceptions in that module inherit from.

class FooException(Ex ception):
""" Base class for all FooModule exceptions """

class FooBadFilename( FooException):
""" Raised when a bad filename is used in a foo """

class FooUnknownBar(F ooException, KeyError):
""" Raised when an unknown bar is used with a foo """

However, there should never be an exception raised of class
FooException, and in fact I want that to cause an appropriate error to
be raised from the module.

Normally, I'd pick some key part of the functionality of the class,
and cause that to raise NotImplementedE rror. It's then the
responsibility of subclasses to override that.

However, in the case of exceptions, I don't want to override *any*
functionality; everything should be provided by the base classes. It'd
be messy to have to override something in every subclass just to
ensure the abstraction of the module base exception.

I've tried doing this in the __init__():

class FooException(Ex ception):
""" Base class for all FooModule exceptions """
def __init__(self):
raise NotImplementedE rror, \
"%s is an abstract class for exceptions" % self.__class__

When I use this, I discovered to my horror that the subclasses were
calling FooException.__ init__ -- which I though wasn't supposed to
happen in Python!

It's also rather semantically weird, to my eye.

Can I do something tricky with checking base classes in the
FooException.__ init__() ?
[0] Although he's apparently been quoted earlier as saying he did.
He's changed his mind[1] since then.

[1] <URL:http://www.artima.com/weblogs/viewpost.jsp?th read=92662>

--
\ "The shortest distance between two points is under |
`\ construction." -- Noelie Alito |
_o__) |
Ben Finney
Nov 11 '05 #1
6 1840
Ben Finney <bi************ ****@benfinney. id.au> writes:
I've tried doing this in the __init__():

class FooException(Ex ception):
""" Base class for all FooModule exceptions """
def __init__(self):
raise NotImplementedE rror, \
"%s is an abstract class for exceptions" % self.__class__

When I use this, I discovered to my horror that the subclasses were
calling FooException.__ init__ -- which I though wasn't supposed to
happen in Python!
It's also rather semantically weird, to my eye.
Calling __init__ is handled just like any other method (this is a good
thing), so if your subclasses fail to define __init__, the version in
the superclass gets called. If it were otherwise, every class would
have to declare __init__ just to call super(cls, self).__init__.
Can I do something tricky with checking base classes in the
FooException.__ init__() ?


Untested:

class FooException(Ex ception):
def __init__(self):
if self.__class__ == FooException:
raise NotImplementedE rror,
"FooExcepti on is an abstract class for exceptions"

Personally, I find this unpythonic. FooException doesn't contribute
anything, and has no real reason for existing. If Python did static
type checking, it would make sense, but python doesn't, so it doesn't.

If you hadn't referenced interfaces, I'd suspect you might be planing
on catching all FooExceptions in a try:/except:. I'm not sure you'll
be able to list an interace in an except clause when they come to
exist, though.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 11 '05 #2
Mike Meyer <mw*@mired.or g> wrote:
class FooException(Ex ception):
def __init__(self):
if self.__class__ == FooException:
raise NotImplementedE rror,
"FooExcepti on is an abstract class for exceptions"
Shall try this when I get the chance. Thanks.
Personally, I find this unpythonic. FooException doesn't contribute
anything, and has no real reason for existing.


The purpose is to be able to specify an 'except FooException:' in some
user of that module; this allows exceptions from that particular
module to be handled differently, if necessary. (And so on for a
hierarchy of modules in a package, if that's warranted.)

--
\ "A cynic is a man who knows the price of everything and the |
`\ value of nothing." -- Oscar Wilde |
_o__) |
Ben Finney
Nov 11 '05 #3
Ben Finney wrote:
Howdy all,

Okay, so Guido doesn't like Abstract Base Classes[0], and interfaces
are the way of the future[1]. But they're not here now, and I
understand ABCs better. This is a very interesting discussion - not all of it understandable to me.

Are interfaces really in our future?

I found the contributions of "steffen" particularly appealing.
Interfaces seem to add another level of complexity without significant
benefit.

Colin W.
I want my modules to (sometimes) define an abstract base exception
class, that all other exceptions in that module inherit from.

class FooException(Ex ception):
""" Base class for all FooModule exceptions """

class FooBadFilename( FooException):
""" Raised when a bad filename is used in a foo """

class FooUnknownBar(F ooException, KeyError):
""" Raised when an unknown bar is used with a foo """

However, there should never be an exception raised of class
FooException, and in fact I want that to cause an appropriate error to
be raised from the module.

Normally, I'd pick some key part of the functionality of the class,
and cause that to raise NotImplementedE rror. It's then the
responsibility of subclasses to override that.

However, in the case of exceptions, I don't want to override *any*
functionality; everything should be provided by the base classes. It'd
be messy to have to override something in every subclass just to
ensure the abstraction of the module base exception.

I've tried doing this in the __init__():

class FooException(Ex ception):
""" Base class for all FooModule exceptions """
def __init__(self):
raise NotImplementedE rror, \
"%s is an abstract class for exceptions" % self.__class__

When I use this, I discovered to my horror that the subclasses were
calling FooException.__ init__ -- which I though wasn't supposed to
happen in Python!

It's also rather semantically weird, to my eye.

Can I do something tricky with checking base classes in the
FooException.__ init__() ?
[0] Although he's apparently been quoted earlier as saying he did.
He's changed his mind[1] since then.

[1] <URL:http://www.artima.com/weblogs/viewpost.jsp?th read=92662>

Nov 11 '05 #4
Ben Finney <bi************ ****@benfinney. id.au> wrote:
I want my modules to (sometimes) define an abstract base exception
class, that all other exceptions in that module inherit from.


Not a whole lot of feedback on this, so here's the implementation I
decided upon.

class FooException(Ex ception):
""" Base class for all exceptions in this module """
def __init__(self):
if self.__class__ is EnumException:
raise NotImplementedE rror, \
"%s is an abstract class for subclassing" % self.__class__

class FooBarTypeError (TypeError, FooException):
""" Raised when the foo gets a bad bar """

class FooDontDoThatEr ror(AssertionEr ror, FooException):
""" Raised when the foo is asked to do the wrong thing """
This allows the exceptions for the module to behave similarly to their
leftmost base exception; but because they all inherit from the
abstract base class exception for the module, it also allows for this
idiom:

import foo

try:
foo.do_stuff(ba r)
except FooException, e:
special_error_h andler(e)
Any more comment on this technique? Any other significant use cases
for abstract base classes?

--
\ "For man, as for flower and beast and bird, the supreme triumph |
`\ is to be most vividly, most perfectly alive" -- D.H. Lawrence. |
_o__) |
Ben Finney
Nov 22 '05 #5
Ben Finney <bi************ ****@benfinney. id.au> wrote:
I want my modules to (sometimes) define an abstract base exception
class, that all other exceptions in that module inherit from.


[re-posting with the implementation properly foo-ified]

Not a whole lot of feedback on this, so here's the implementation I
decided upon.

class FooException(Ex ception):
""" Base class for all exceptions in this module """
def __init__(self):
if self.__class__ is FooException:
raise NotImplementedE rror, \
"%s is an abstract class for subclassing" % self.__class__

class FooBarTypeError (TypeError, FooException):
""" Raised when the foo gets a bad bar """

class FooDontDoThatEr ror(AssertionEr ror, FooException):
""" Raised when the foo is asked to do the wrong thing """
This allows the exceptions for the module to behave similarly to their
leftmost base exception; but because they all inherit from the
abstract base class exception for the module, it also allows for this
idiom:

import foo

try:
foo.do_stuff(ba r)
except FooException, e:
special_error_h andler(e)
Any more comment on this technique? Any other significant use cases
for abstract base classes?

--
\ "For man, as for flower and beast and bird, the supreme triumph |
`\ is to be most vividly, most perfectly alive" -- D.H. Lawrence. |
_o__) |
Ben Finney
Nov 22 '05 #6
Ben Finney wrote:
Ben Finney <bi************ ****@benfinney. id.au> wrote:
I want my modules to (sometimes) define an abstract base exception
class, that all other exceptions in that module inherit from.

[re-posting with the implementation properly foo-ified]


Isn't the proper Python idiom to use Monty Python
concepts, e.g. spam, vikings, parrots, after dinner
mints (wafer thin or otherwise), gumby, etc.?

As well as being Pythonic, it annoys the Lisp, Perl and
C developers even more than ... sarcasm.

*wink*
Not a whole lot of feedback on this, so here's the implementation I
decided upon.


[snip]

Seems good to me.
--
Steven.

Nov 22 '05 #7

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

Similar topics

2
9605
by: Dave Veeneman | last post by:
Is is legal to declare abstract members in non-abstract classes? How about non-abstract members in abstract classes? I am writing a base class with three derived classes. The base class will define the behavior for most, but not all of its members. The derived classes will define the behavior for the remaining members (the undefined members). I'd like to force the derived classes to implement the undefined members in the base class. I...
4
3553
by: Chuck Bowling | last post by:
I am using CodeDOM to generate source files. The classes being generated have a const string member. This member is referenced in an abstract base class but declared in the inheriting class. I can't declare the string in the abstract class because it would require initialization. Is there a way to require that any class inheriting from the base class contain this string without a specific declaration in the base class? I tried putting a...
18
3781
by: Bradley | last post by:
I'm trying to determine if there's a general rule for when an Interface should used vs. an Abstract Class. Is there any design advantage to using one or the other? Brad
9
5200
by: Sean Kirkpatrick | last post by:
To my eye, there doesn't seem to be a whole lot of difference between the two of them from a functional point of view. Can someone give me a good explanation of why one vs the other? Sean
7
4472
by: jason | last post by:
In the microsoft starter kit Time Tracker application, the data access layer code consist of three cs files. DataAccessHelper.cs DataAcess.cs SQLDataAccessLayer.cs DataAcccessHelper appears to be checking that the correct data type is used DataAcess sets an abstract class and methods
2
2268
by: talkingpidgin | last post by:
I am trying to figure out why it is not conventional to use protected constructors in abstract classes since the only time they should be called is by the constructors of it's derived classes. Is it simply because it's not strictly necessary since an abstract class can't be instantiated anyways? It just seems like it would be clearer to make the ctor protected so I figured there must be some reason for it. Also I am trying to put...
0
2832
by: emin.shopper | last post by:
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass magic, I wrote the following module. It is mainly useful as a light weight tool to help programmers catch mistakes at definition time (e.g., forgetting to implement a method required by the given interface). This is handy when unit tests or...
2
2967
by: Zytan | last post by:
I know that WebRequest.GetResponse can throw WebException from internet tutorials. However in the MSDN docs: http://msdn2.microsoft.com/en-us/library/system.net.webrequest.getresponse.aspx It only lists NotImplementedException in the Exceptions section. (Note that it does mention WebException in the Remarks section, but who knows if this is always the case for such classes, and thus perhaps they can't be trusted to always list these, and...
4
6569
by: David Zha0 | last post by:
Hi, "when we call a virtual method, the runtime will check the instance who called the method and then choose the suitable override method, this may causes the performance drop down", is this right? And, why not use "new" instead of using "virtual"? And the last question, what is the differences between a abstract method and a interface?
5
3018
by: =?Utf-8?B?UmljaA==?= | last post by:
Greetings, I am actually a VB.Net guy, but I have worked somewhat with C++ and C#. I just want to ask about the relationship between Abstract Classes and Interfaces. My first question is if C# even has Iinterfaces. I took some Java programming classes and Interfaces are a main staple of Java. And in VB.Net I use interfaces for setting up definitions of classes. I am guessing that Abstract classes in C# do the same thing as...
0
8987
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9534
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9366
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9241
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4597
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.