473,761 Members | 2,455 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there a consensus on how to check a polymorphic instance?

hi all,
I'm a newbie Python programmer with a C++ brain inside. I have a
lightweight framework in which I design a base class and expect user to
extend. In other part of the framework, I heavily use the instance of
this base class (or its children class). How can I ensure the instance
IS-A base class instance, since Python is a fully dynamic typing
language?

I searched and found several different ways to do this:

1. In `Text Processing in Python', David Mertz suggests using `hasattr'
to check abilities instead of type checking.

2. In ActiveState's Python Cookbook site, Alex Martelli suggested a
safe and accurate `look before you leap' technique on
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52291

3. In this group, some others suggest using isinstance() builtin
function to check instance.

Now my questions:
1. Is my design speaks native Pythonish? Such design is native in C++
and Java OO style, but I'm not sure about this in Python.

2. As I state in title, is there a consensus on how to check a
polymorphic instance? I find all the three ways above is a little bit
tedious compared with C++ and Java, in which compile-time type checking
ensures the interface protocol, any better ideas in Python?
Any comments will be appreciated.

Jul 18 '05
37 2845
> I come from a very conservative background in software development
and strong checks are deeply rooted in my mind.


So do I, Dan.

I just can't imagine a `wild' object whose interface is valid can
truely do the right things. While in fact, when I typing this word, I
realize we can't ensure the internal protocol will be obeyed even when
the object IS-A base class instance.

Maybe it's time to rethink.

It seems to me the virtue of dynamic langauge is, if it looks like a
cat, it's a cat. But the problem is still there: how do you know what
it looks like before you treat it as a cat? isinstance(), , as Steve
state, is too rigid.

Jul 18 '05 #21
Quoth "Dan Perl" <da*****@rogers .com>:
| "Donn Cave" <do**@u.washing ton.edu> wrote in message
| news:do******** *************** *@gnus01.u.wash ington.edu...
| > I'm very sympathetic to the advantages of static typing
| > (NB, I read here that Python is strongly, though dynamically,
| > typed. It is not statically typed.) Rather than embrace
| > subtype polymorphism through inheritance, however, I see it
| > as evidence that no one has figured out how to make static
| > typing really work with OOP. There has to be a better way
| > to do it.
|
| You're right, I should have said statically typed instead of strongly typed.
|
| But did you really mean "no one has figured out how to make *static* typing
| really work with OOP" or did you mean *dynamic* typing?

Static. I figure dynamic & OOP get along fine -- as Smalltalk showed,
along with I believe Objective C and of course Python. Static typing
and Functional Programming seem to go hand in glove, cf. Haskell type
classes. Static OOP seems to invite inelegant and unsound compromises.

Donn Cave, do**@u.washingt on.edu
Jul 18 '05 #22

"Donn Cave" <do**@drizzle.c om> wrote in message
news:1101273995 .954137@yasure. ..
Quoth "Dan Perl" <da*****@rogers .com>:
| "Donn Cave" <do**@u.washing ton.edu> wrote in message
| news:do******** *************** *@gnus01.u.wash ington.edu...
| > I'm very sympathetic to the advantages of static typing
| > (NB, I read here that Python is strongly, though dynamically,
| > typed. It is not statically typed.) Rather than embrace
| > subtype polymorphism through inheritance, however, I see it
| > as evidence that no one has figured out how to make static
| > typing really work with OOP. There has to be a better way
| > to do it.
|
| You're right, I should have said statically typed instead of strongly
typed.
|
| But did you really mean "no one has figured out how to make *static*
typing
| really work with OOP" or did you mean *dynamic* typing?

Static. I figure dynamic & OOP get along fine -- as Smalltalk showed,
along with I believe Objective C and of course Python. Static typing
and Functional Programming seem to go hand in glove, cf. Haskell type
classes. Static OOP seems to invite inelegant and unsound compromises.
It's hard to argue against Smalltalk. I haven't used it for many years so I
don't remember it but it was THE language of choice for an OOP course I took
oh so many years ago. And I still see it mentioned as a model for OOP. I
never learned Objective C so I cannot argue with that either.
Unfortunately, as much as I am learning to like Python, I don't think I see
it as a picture perfect OOP language. It may be a controversial opinion but
I am not at all satisfied with encapsulation in Python (you cannot hide any
of a class's implementation) .

Can you elaborate on problems that static languages have with OOP? We have
been touching on parametric polymorphism and that is a valid point. I also
see multiple inheritance as being very poorly implemented in C++ and Java to
the point where books on C++ that treat the subject discourage you from
using it and Java has effectively designed it out of the language (you can
implement many interfaces but you can extend only one class). What do you
have in mind?

Dan
Donn Cave, do**@u.washingt on.edu

Jul 18 '05 #23
Donn Cave wrote:
Rather than embrace
subtype polymorphism through inheritance, however, I see it
as evidence that no one has figured out how to make static
typing really work with OOP.


I'm not sure I follow your argument here. Java interfaces provide the
same sort of protocol-based typing as Python does (though of course you
have do declare interfaces everywhere to make them work this way).
Going back to my earlier Python example:
def process_rules(r ules):

.... for rule in rules:
.... print rule.name
....

the corresponding Java might look something like:

public interface Rule {
public Object getName();
}

public class RuleProcessor {
public void processRules(It erable<Rule> rules){
for (Rule rule: rules) {
System.out.prin tln(rule.getNam e())
}
}
}

Note that because Java is statically typed, you have to declare all the
appropriate interfaces: Iterable is in java.lang, and Rule is declared
above. In Python, the interfaces are implied by the use, and left
undeclared.

Of course, you have to declare your interfaces in a suitably generic
manner. I could have written this replacing Iterable<Rule> with
Collection<Rule > or List<Rule>, but Iterable<Rule> is the type that
makes the fewest commitments about the parameter and still allows me to
iterate over the Rule objects. Similarly, I could have written getName
to return a String, but by declaring getName with Object as a return
type, I make only the necessary commitment that getName returns a value.

The annoying thing, of course, is what you do when suddenly *one* use of
a Rule does require, say, a String result of getName:

public class OtherRuleProces sor {
public void processRules(It erable<Rule> rules){
for (Rule rule: rules) {
String[] s = rule.getName(). split('\\s')
}
}
}

Do I now declare a new interface for this Rule and add another
implements clause to all my classes that implement the original Rule as
well? Do I make the original Rule interface less general by changing
the return type from Object to String? It can get nasty rather quickly...

Python, of course, avoids this by not declaring types. =)

Steve
Jul 18 '05 #24
On 23 Nov 2004 19:58:31 -0800, Mike Meng <me******@gmail .com> wrote:
I come from a very conservative background in software development
and strong checks are deeply rooted in my mind.
So do I, Dan.

I just can't imagine a `wild' object whose interface is valid can
truely do the right things. While in fact, when I typing this word, I
realize we can't ensure the internal protocol will be obeyed even when
the object IS-A base class instance.

Maybe it's time to rethink.


I understand, and I found myself using isinstance more often that I
would like to admit. Being trained in OO Pascal & Delphi it comes as
no surprise...
It seems to me the virtue of dynamic langauge is, if it looks like a
cat, it's a cat. But the problem is still there: how do you know what
it looks like before you treat it as a cat? isinstance(), , as Steve
state, is too rigid.


Time for adapt(), I think...

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #25
On 23 Nov 2004 19:58:31 -0800,
"Mike Meng" <me******@gmail .com> wrote:

First off, I have only been following this thread on and off, so if I'm
repeating things, I apologize.
It seems to me the virtue of dynamic langauge is, if it looks like a
cat, it's a cat ...
Google for "duck typing."
... But the problem is still there: how do you know what it looks like
before you treat it as a cat? isinstance(), , as Steve state, is too
rigid.


You don't.

Python also takes a "we're all adults here" philosophy. If your API
specifies "cat," and I pass your function an "InterfaceAdapt er," it's
*my* problem.

If you're truly paranoid, make sure that your arguments at least have
the methods you're going to use:

# write 'foo' to the file-like object x; don't bother if x is not
# sufficiently file-like

def f( x ):
try: x.write
except AttributeError:
pass
else:
x.write( 'foo' )

# this works, too, but doesn't scale well (i.e., if 'foo' is some
# other non-trivial (maybe non-trusted) operation that can raise
# AttributeError) :

def f( x ):
try: x.write( 'foo' )
except AttributeError:
pass

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn.
Jul 18 '05 #26
Mike Meng wrote:
It seems to me the virtue of dynamic langauge is, if it looks like a
cat, it's a cat.
I think this is more accurately expressed as "if it *acts* like
a cat, then you can treat it like a cat". Your version implies
that you really do care what it _is_, which goes back to the
static typing thinking again.
But the problem is still there: how do you know what
it looks like before you treat it as a cat? isinstance(), , as Steve
state, is too rigid.


The argument is that you probably don't really need to know
what it looks like *before* you try to use it, even if you
think you do. The cases where you really do are probably those
Alex Martelli's recipe (mentioned near the start of the thread)
is intended to help. (Specifically, avoiding the situation
where the object implements the required protocol only partially,
but you don't find that out until you've already started using
the object, possibly corrupting it in the process.)

-Peter
Jul 18 '05 #27
In article <s4************ ********@rogers .com>,
"Dan Perl" <da*****@rogers .com> wrote
....
It's hard to argue against Smalltalk. I haven't used it for many years so I
don't remember it but it was THE language of choice for an OOP course I took
oh so many years ago. And I still see it mentioned as a model for OOP. I
never learned Objective C so I cannot argue with that either.
Unfortunately, as much as I am learning to like Python, I don't think I see
it as a picture perfect OOP language. It may be a controversial opinion but
I am not at all satisfied with encapsulation in Python (you cannot hide any
of a class's implementation) . Can you elaborate on problems that static languages have with OOP? We have
been touching on parametric polymorphism and that is a valid point. I also
see multiple inheritance as being very poorly implemented in C++ and Java to
the point where books on C++ that treat the subject discourage you from
using it and Java has effectively designed it out of the language (you can
implement many interfaces but you can extend only one class). What do you
have in mind?


I am really too unschooled in these matters to pursue that.
I have mentioned Haskell a couple of times, and that's my
perspective on static typing. I recommend it as an interesting
exercise: learn Haskell, find out what static typing is about.
It isn't perfect, but it's leagues ahead of C++ etc.

I don't have any beef with multiple inheritance, in fact the
notion of "mix-in" classes might have some potential to be the
basis for a more sound approach to OO.

Donn Cave, do**@u.washingt on.edu
Jul 18 '05 #28
Donn Cave wrote:
I don't have any beef with multiple inheritance, in fact the
notion of "mix-in" classes might have some potential to be the
basis for a more sound approach to OO.


The people that have a beef with multiple inheritance have it because
multiple inheritance can sometimes break encapsulation by forcing the
designer of a class to be aware of changes in the inheritance chain far
above its parents (even when no methods/attributes are added by the
change). A classic reference:

Snyder, Alan. "Encapsulat ion and Inheritance in Object-Oriented
Programming Languages"
http://www-plan.cs.colorado.edu/diwa...ers/snyder.pdf

Python tries to combat some of these problems with a good method
resolution order:

http://www.python.org/2.3/mro.html

I don't make enough use of multiple inheritance to ever have run into
these kinds of problems, but the literature in this area is enormous...

Steve
Jul 18 '05 #29
"Dan Perl" <da*****@rogers .com> writes:
Can you elaborate on problems that static languages have with OOP?


They make dynamic polymorphism impossible.

Which is why most object-oriented C++ programs are dynamically typed;
only the programmer is burdened with the work that the mostly-absent
dynamic type system should be doing.

Dynamic polymorphism crucially requires knowledge of the *run-time*
(dynamic) type of objects, in order to be able to dispatch to the
correct method. In C++ you turn your classes into dynamically typed
ones with the "virtual" keyword, which introduces a vtable and
run-time type identification (RTTI). As long as you are only
interested in calling methods which are declared in some base class,
this dynamic type systems looks almost satisfactory. As soon as you
want to use a method present in the subclass but not in the
superclass, it is up to you to faff around with dynamic_cast and
checking of the resulting pointer; all stuff which a dynamic type
system should be doing for you, but C++ makes you do yourself because
it pretends that your programs are statically typed when, in fact,
they are dynamically typed.
Jul 18 '05 #30

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

Similar topics

20
2227
by: verec | last post by:
One problem I've come accross in designing a specific version of auto_ptr is that I have to disntiguish between "polymorphic" arguments and "plain" ones, because the template has to, internally, cast to void *. Specifically, template <typename T> void f(T * t) { void * p = dynamic_cast<void *>(t) ; } will not compile if T isn't of a class that has somewhere at least
1
2260
by: verec | last post by:
Last week I asked here how I could detect that a T was polymorphic, and received very thoughtful and useful replies that I used straight away. Thanks to all who answered. This week, it turns out that detecting whether T is polymorphic clashes with a new requirement, that T be allowed to not be complete. Last week, this code used to compile:
7
2077
by: James Fortune | last post by:
In response to different users or situations (data context) I transform the appearance and characteristics of Access Forms through code. This seems to fit in with the idea of polymorphism. Do people consider Access Forms to be Polymorphic? James A. Fortune
12
1447
by: Bob | last post by:
Hi, 'Shadowed' properties are not polymorphic. (See thread 'Inheritance and late binding') They should be. Problem: Base class has read only property 'X'. Derived class must have read / write property 'X'. Can't override Base class 'X' because of different structure. So you Shadow the base class 'X' in the derived class. Pass an instance of the derived class to a function.
5
2782
by: FefeOxy | last post by:
Hi, > I'm having a debug assertion error within the file dbgdel.cpp with the expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) I traced the origin of the error and it happened as I tried to delete a polymorphic class as follows:
5
3421
by: Ben Pope | last post by:
Hi all, This is not something I've played around with much, but I'm designing some factories and I want a function like this: template<class T> T* Creator() { return new T; }
2
1625
by: Jan Schäfer | last post by:
Hi all, is there a simple way to find out during runtime if a class of some type is polymorphic? I am writing some serialization functions and need to handle polymorphic and non-polymorphic classes differently. I am sure there are hundreds of workarounds for this, but I am interested if this can be done by some clever function with the help of casting and/or rtti which determines if a class is polymorphic or not. I found a...
3
3912
by: jacek.dziedzic | last post by:
Hello! Suppose I have a class base, with virtual methods and a virtual destructor and a bunch of classes, derived1, derived2, ... which publicly derive from base. I then have a pointer base* foo; which a complicated code allocates as one of derived's and sets up.
3
1635
by: Daniel Kraft | last post by:
Hi, I usually program in C++, but for a special project I do have to code in C (because it may be ported to embedded-like platforms where no C++ compiler exists). I do want to realize some kind of polymorphic behaviour, like this: I have some abstract base "class" Base, that is, a struct containing a vtable of function-pointers and possibly some common fields (but at the
0
9522
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
9336
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
10111
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...
1
9902
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6603
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3866
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
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2738
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.