Stylistic question about inheritance

A

Andrew Koenig

Suppose I want to define a class hierarchy that represents expressions, for
use in a compiler or something similar.

We might imagine various kinds of expressions, classified by their top-level
operator (if any). So, an expression might be a primary (which, in turn,
might be a variable or a constant), a unary expression (i.e. the result of
applying a unary operator to an expression), a binary expression, and so on.

If I were solving such a problem in C++, I would define a base class for all
expressions, then derive the various kinds of expression classes from that
base class. However, I would not anticipate ever creating objects of the
base class, so I would make it abstract.

In Python, I can imagine doing the same thing:

class Expr(object):
pass

class UnaryExpr(Expr):
# ...

class BinaryExpr(Expr):
# ...

and so on. However, although I don't have a choice in C++ about having a
base class--you can't use dynamic binding without it--in Python I do have
that choice. That is, I don't need to have the base class at all unless I
want to have some operations that are common to all derived classes.

Of course, there are reasons to have a base class anyway. For example, I
might want it so that type queries such as isinstance(foo, Expr) work. My
question is: Are there other reasons to create a base class when I don't
really need it right now?
 
C

Carl Banks

Andrew Koenig wrote:
[snip]
Of course, there are reasons to have a base class anyway. For example, I
might want it so that type queries such as isinstance(foo, Expr) work. My
question is: Are there other reasons to create a base class when I don't
really need it right now?

Well, Python seems to get along fine without the ability to do
isinstance(foo,file_like_object); probably better off in the end for
it. So I'd say you should generally not do it. Inheritence is for
when different classes need to share functionality.
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

Andrew said:
Of course, there are reasons to have a base class anyway. For example, I
might want it so that type queries such as isinstance(foo, Expr) work. My
question is: Are there other reasons to create a base class when I don't
really need it right now?

You would normally try to avoid type queries, and rely on virtual
methods instead, if possible. It seems likely for the application
that code can be shared across different subclasses, for example,
you might be able to define

def Expr:
def __str__(self):
return '%s(%s)' % (self.__class__.__name__,
", ".join(map(str, self.operands()))

requiring you only to implement .operands() in the subclasses.

If you can anticipate such common code, it is easier to add
a base class right away. If you cannot think of a specific
use case, there is little point in having a common base class.

Regards,
Martin
 
L

Lonnie Princehouse

If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes. Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...

I usually skip the inheritance and make everything an instance of the
same class, e.g.

class ASTNode(object): ...

class Stmt(ASTNode): ...
class Expr(ASTNode): ...
class UnaryExpr(ASTNode): ...
class BinaryExpr(ASTNode): ...

or you could dynamically generate classes with inheritance based on a
grammar definition
 
A

Andrew Koenig

Well, Python seems to get along fine without the ability to do
isinstance(foo,file_like_object); probably better off in the end for
it. So I'd say you should generally not do it. Inheritence is for
when different classes need to share functionality.

That's really the question: Is it for when they need to share
functionality, or when they are conceptually related in ways that might lead
to shared functionality later?
 
A

Andrew Koenig

You would normally try to avoid type queries, and rely on virtual
methods instead, if possible.

Of course.
It seems likely for the application
that code can be shared across different subclasses, for example,
you might be able to define

def Expr:
def __str__(self):
return '%s(%s)' % (self.__class__.__name__,
", ".join(map(str, self.operands()))

requiring you only to implement .operands() in the subclasses.
Indeed.

If you can anticipate such common code, it is easier to add
a base class right away. If you cannot think of a specific
use case, there is little point in having a common base class.

So, for example, you don't think it's worth including the base class as a
way of indicating future intent?
 
A

Andrew Koenig

If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes. Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...

Understood. I was using expression trees as a contrived example, and really
want to know about the Python community's stylistic preferences for defing
such hierarchies that don't absolutely need a root.
I usually skip the inheritance and make everything an instance of the
same class, e.g.

class ASTNode(object): ...

class Stmt(ASTNode): ...
class Expr(ASTNode): ...
class UnaryExpr(ASTNode): ...
class BinaryExpr(ASTNode): ...

Eh? There's still inheritance here: Everything is derived from ASTNode. I
understand that there is a separate design issue whether to make the
hierarchy deep or shallow, but it's still a hierarchy.
 
I

Irmen de Jong

Andrew said:
Understood. I was using expression trees as a contrived example, and really
want to know about the Python community's stylistic preferences for defing
such hierarchies that don't absolutely need a root.

I have used empty or near-empty base classes to be some sort of
class 'tag' for the derived classes.
Much like Java's Serializable interface; it adds nothing on
a functional level but you can check if a class has a 'tag'
by checking if it is an instance of the base class.
I don't know if this is good style in Python but I tend
to use it sometimes (probably because I do Java at work ;-)

--Irmen
 
S

Stefan Seefeld

Andrew said:
Of course, there are reasons to have a base class anyway. For example, I
might want it so that type queries such as isinstance(foo, Expr) work. My
question is: Are there other reasons to create a base class when I don't
really need it right now?

Coming from C++ myself, I still prefer to use inheritance even if Python
doesn't force me to do it. It's simply a matter of mapping the conceptual
model to the actual design/implementation, if ever possible.

Regards,
Stefan
 
D

Donn Cave

"Andrew Koenig said:
That's really the question: Is it for when they need to share
functionality, or when they are conceptually related in ways that might lead
to shared functionality later?

No -- inheritance is for implementation, not to express conceptual
relationship.

Donn Cave, (e-mail address removed)
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

Andrew said:
So, for example, you don't think it's worth including the base class as a
way of indicating future intent?

No. In this respect, I believe in XP: refactor when the need comes up,
but not before.

Regards,
Martin
 
S

Steven Bethard

Andrew said:
That's really the question: Is it for when they need to share
functionality, or when they are conceptually related in ways that might lead
to shared functionality later?

I've typically only done the former. But I've definitely extracted
common ancestors later when I did find that two different classes should
share functionality.

STeVe
 
B

Bengt Richter

Of course.


So, for example, you don't think it's worth including the base class as a
way of indicating future intent?
If the intent is pretty sure of implementation, I guess it will save some
editing to include it at the start (unless you intended to define old-style classes
and factor the base class inheritance revisions into some global metaclass hack later
(not even really sure that's reliably possible, but pretty sure it would not be the
best style ;-) BTW 2.5 may let you mod classes by prefixing a decorator instead of
editing the first line. Not sure about the style/semantics tradeoffs there.

Regards,
Bengt Richter
 
L

Lonnie Princehouse

Well, that's true, but I meant to convey that no grammatical entity is
the base class of another entity, so it's a flat inheritance tree in
that respect. ASTNode would not be something that the parser would
know anything about.

I guess that's sort of moot if your expression trees are just a
contrived example; in that case, I'd say that how deep you want your
inheritance hierarchy to be depends entirely on how your program wants
to use it.
 
M

Michele Simionato

Koenig:
want to know about the Python community's stylistic
preferences for defing
such hierarchies that don't absolutely need a root.

I don't know if there is an official style guide or a Guido's
prononcement on the issue. Personally
I found such hierarchies attractive in the past, but
recently I realized that they look better on the paper
than in practice. A non-needed class just adds cognitive
burden to the maintainer. Also, I don't like to use
isinstance if I can avoid it. Finally, It is always easy to
refactor later and to add a base class
if there is a real need for it.
Paraphrasing Occam, I would say "don't multiply base classes without
necessity" ;)


Michele Simionato
 
I

Ivan Van Laningham

Hi All--

Michele said:
recently I realized that they look better on the paper
than in practice. A non-needed class just adds cognitive
burden to the maintainer.

Agreed. Too many classes make me think I'm back trying to figure out
what the )(*#@$ those guys were thinking making 200 twelve-line ASP
classes. Ya think there's a hard-wired limit past which your brain
melts?
Paraphrasing Occam, I would say "don't multiply base classes without
necessity" ;)

+1 QOTW

Metta,
Ivan
----------------------------------------------
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps: Cu Chi, Class of '70
Author: Teach Yourself Python in 24 Hours
 
S

Steve Holden

Andrew said:
Of course.




So, for example, you don't think it's worth including the base class as a
way of indicating future intent?
The obvious XP response to the question is "You aren't going to need
it". If you already have the intent then basically you appear to be
saying "I *am* going to need it".

Since you say that almost as an integral feature of the specification
I'm not sure I understand why you asked the question in the first place
- unless it's really an anthropological inquiry.

regards
Steve
 
G

Guy Bolton King

Andrew Koenig said:
Understood. I was using expression trees as a contrived example, and really
want to know about the Python community's stylistic preferences for defing
such hierarchies that don't absolutely need a root.

Oddly enough, I've just been pondering the same question (albeit for
Perl, but the same reasoning applies). The only cases I've found
useful thus far are:

- implementation inheritance (in the case of default methods in a
callback interface class):

class CallbackInterface:

def handleEvent(self, event):
"""Handle an event"""
pass

def handleSignal(self, signal):
"""Handle a signal"""
pass

This also helps to document what's expected of callback classes,
even though they don't _have_ to inherit CallbackInterface
(enforcing this through isinstance() in the calling class would be
rude).

- hierarchies of exception classes (allowing one to catch general
classes of exceptions, since except implicitly uses isinstance(),
rather than a specific class). Of course, Python already has a
hierarchy of exceptions. I had to implement my own for Perl.

From a brief skim of http://www.python.org/moin/PythonThreeDotOh it
looks like interfaces _may_ be added to Python 3.0, but they sound
more like (IIRC) ML's signatures and C++'s Standard Library
requirements i.e. a requirement that the class implements certain
functions, rather than a requirement to inherit from a particular base
class.

Guy.
 

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

Forum statistics

Threads
474,232
Messages
2,571,168
Members
47,803
Latest member
ShaunaSode

Latest Threads

Top