473,671 Members | 2,208 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is isinstance always "considered harmful"?

Hi everyone,

Just a little issue that I've come across in Python where I'd be
interested to read the thoughts and opinions of the great thinkers and
programmers who frequent this newsgroup.

I've read arguments, here and elsewhere, to the effect that in Python
isinstance should be avoided like the plague, except in a few very
specific and narrow circumstances. Roughly speaking, due in part to
Python's dynamic nature its better to concern yourself only with the
interface an object provides, and not whether it happens to inherit
from a given base class.

The problem is, sometimes theres more thats important to what a method
does than just correct behaviour.

Specifically, consider the case of Linked Lists vs the array based
random access model Python uses for its lists. Given the ease of using
Python's inbuilt list type, I'm not sure if theres much call for Linked
Lists in the language - I don't even know if they are used anywhere in
the standard library (I had assumed the deque class was implemented
with a linked list, but a friend of mine pointed out circular arrays
are an equally likely possibility, and I even saw an elegant cookbook
recipe the other day that uses a Dictionary.)

Well, whats the difference between the two data structures? If you
consider only the interface, nothing - they provide exactly the same
service, sequential storage and access to data elements. However, any
programmer who passed Data Structures and Algorithms 101 knows theres a
critical difference between the performance of the various operations a
programmer might want to carry out, and you should choose one over
the other based on which operations you expect to be most common in
whatever problem youre solving.

Hiding the implementation is a great principle, but this is a case
where the underlying implementation really matters. The difference
between an 0(1) and 0(n) algorithm is not a matter of 'fine tuning' or
an issue of 'premature optimization'; its a critical design parameter.

So to get back to the original point of the post ;) Say you're writing,
in Python, the extend() method for a Linked List version of python's
builtin list. Its really important to know what kind of iterable youre
being passed in - because if its another Linked list, and you know it,
you can connect the two in 0(1) time; whereas any other arbitrary
iterable is going to take 0(n), as you're just going to have to append
the items one by one. Is this a case where use of isinstance, to see
exactly what kind of Iterable you have, can be justified?

def extend(self, elems):
if isinstance(elem s, LinkedList):
# Point last to first
else:
for elem in elems: self.append(ele m)
From memory this is the way its done in Java's collection API, or at

least it was the last time I looked at the source.

There are other solutions I can think of - perhaps the least hideous is
factoring out the 0(1), "point last to first" code in a seperated
method, __linkedExtend( ) or something, and then do something similar to
the above by using an exception, like this:

def extend(self, elems):
try:
self.__linkedEx tend(elems)
catch NotALinkedListE rror:
for elem in elems: self.append(ele m)

I dont know, I don't really like this (although it is more BAFP than
the first version, so maybe that makes it more Pythonic?). To me,
instanceof seems like the infimum of all possible evils in this case.

It'd be nice if I'd seen the source code for Python's builtin list to
see if any of these kind of considerations are taken into account there
(ultra fast array copying in C when extend is called on another list,
perhaps)? Luckily, one of the great gifts of Python is I can indeed
look at the source for the entire langauge at any time I want. So I'm
going to go read it (my first time, how exciting!), and in the
meantime, I'll let replies start accumulating froma whole lot of
people who are a lot smarter and more experience in Python than myself
:)

Several-weeks-in-and-still-liking-Python-better-than-any-other-previously-learned-language-ly
yours,
Jordan Rastrick

Jul 19 '05 #1
5 2598
Jordan Rastrick wrote:
Say you're writing, in Python, the extend() method for a Linked List
version of python's builtin list. Its really important to know what
kind of iterable youre being passed in - because if its another
Linked list, and you know it, you can connect the two in 0(1) time;
whereas any other arbitrary iterable is going to take 0(n), as you're
just going to have to append the items one by one. Is this a case
where use of isinstance, to see exactly what kind of Iterable you
have, can be justified?

def extend(self, elems):
if isinstance(elem s, LinkedList):
# Point last to first
else:
for elem in elems: self.append(ele m)


Regardless of the various issues surrounding isinstance(), you have a
difference in functionality. Since you're just storing a reference in
the case of another LinkedList instead of copying it, mutating the
LinkedList will be different from mutating another iterable type which
has been passed to extend:
linkedlist1 = LinkedList()
list1 = [1, 2, 3]
linkedlist2 = LinkedList([4, 5, 6])
linkedlist1.ext end(list1)
linkedlist1.ext end(linkedlist2 )
linkedlist1 LinkedList([1, 2, 3, 4, 5, 6]) list1.append(4)
linkedlist1 # Notice how there's still only one 4 LinkedList([1, 2, 3, 4, 5, 6]) linkedlist2.app end(7)
linkedlist1 # Notice how there's now a 7

LinkedList([1, 2, 3, 4, 5, 6, 7])
Jul 19 '05 #2

"Jordan Rastrick" <jr*******@stud ent.usyd.edu.au > wrote in message
news:11******** *************@o 13g2000cwo.goog legroups.com...
I've read arguments, here and elsewhere, to the effect that in Python
isinstance should be avoided like the plague, except in a few very
specific and narrow circumstances.
Putting it like this is rather extreme.
Roughly speaking, due in part to
Python's dynamic nature its better to concern yourself only with the
interface an object provides, and not whether it happens to inherit
from a given base class.


To my mind, your example of using isinstance to select a better (such as
speedier) subalgorithm for a special case is not just fine, but good
programming. (Selecting a subalgorithm that works more robustly is also a
good reason for special casing.) It is an internal matter whose externally
visible effect is to improve performance.

Using isinstance to unnecessarily narrow the domain is quite different. It
has the externally visible effect of degrading performance (to a nullity)
for arguments that the user might reasonably want to work.

Terry J. Reedy

Jul 19 '05 #3
On Sun, 15 May 2005 14:31:21 -0400, "Terry Reedy" <tj*****@udel.e du> wrote:

"Jordan Rastrick" <jr*******@stud ent.usyd.edu.au > wrote in message
news:11******* **************@ o13g2000cwo.goo glegroups.com.. .
I've read arguments, here and elsewhere, to the effect that in Python
isinstance should be avoided like the plague, except in a few very
specific and narrow circumstances.
Putting it like this is rather extreme.
Roughly speaking, due in part to
Python's dynamic nature its better to concern yourself only with the
interface an object provides, and not whether it happens to inherit
from a given base class.


To my mind, your example of using isinstance to select a better (such as
speedier) subalgorithm for a special case is not just fine, but good
programming. (Selecting a subalgorithm that works more robustly is also a
good reason for special casing.) It is an internal matter whose externally
visible effect is to improve performance.

I agree, but I am also a little uncomfortable about such performance tuning,
unless the assumptions it depends on are prominently documented or even
validated with an assert or explicit warning. Otherwise the next version
of the interpreter or a library module could change the optimal decision,
and a bad optimization decision could be locked in for the new version.

Maybe there should be another testable condition like __debug__ except for
testing (e.g. __testing__ ;-) which could be used to introduce temporary
alternative code (such as alternate optimization decisions) so that system
tests could be used to validate locking in one decision or another for a
new system version being tested.

For trivial personally maintained code, a one-line version check with a
reminder exception to re-visit the optimization or whatever decision
(and revise the version check for next time) could cheaply prevent hidden
lock-in of bad optimization etc.

Using isinstance to unnecessarily narrow the domain is quite different. It
has the externally visible effect of degrading performance (to a nullity)
for arguments that the user might reasonably want to work.

Agreed, but the key thing there is to define "unnecessar ily" ;-)

Regards,
Bengt Richter
Jul 19 '05 #4

Leif K-Brooks wrote:
Regardless of the various issues surrounding isinstance(), you have a
difference in functionality. Since you're just storing a reference in
the case of another LinkedList instead of copying it, mutating the
LinkedList will be different from mutating another iterable type which has been passed to extend:


Oops, didn't think of that. Good point.
linkedlist1 = LinkedList()
list1 = [1, 2, 3]
linkedlist2 = LinkedList([4, 5, 6])
linkedlist1.ext end(list1)
linkedlist1.ext end(linkedlist2 )
linkedlist1 LinkedList([1, 2, 3, 4, 5, 6]) list1.append(4)
linkedlist1 # Notice how there's still only one 4 LinkedList([1, 2, 3, 4, 5, 6]) linkedlist2.app end(7)
linkedlist1 # Notice how there's now a 7

LinkedList([1, 2, 3, 4, 5, 6, 7])


Out of curiousity, is this code real? Where does the LinkedList() class
come from?

Jul 19 '05 #5
Thanks for the replies, everyone. As is usual when reading
comp.lang.pytho n, I got some invaluable exposure to new ideas (multiple
dispatching in particular seems to fill a gap I've felt in OO
programming in the past.)

I'm starting to think this newsgroup is in its own right an excellent
reason to get into Python - the fact its an awesome language is just an
added bouns ;-)

Jul 19 '05 #6

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

Similar topics

49
2834
by: Ville Vainio | last post by:
I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville Vainio http://www.students.tut.fi/~vainio24
7
1414
by: Keith Wilby | last post by:
Is is possible to turn this message off? It currently pops up every time my app is opened. Using XP Pro if that's relevant. Thanks.
6
2014
by: kobu.selva | last post by:
I was recently part of a little debate on the issue of whether constants and string literals are considered "data objects" in C. I'm more confused now than before. I was always under the understanding that only "named" storage areas(from the standard) were data objects. Since constants and string literals don't have lvalues, they can't be data objects. Yet, I was shown the first page of chapter 2 in K&R2, which states that variables...
9
2484
by: Javaman59 | last post by:
I saw in a recent post the :: operator used to reach the global namespace, as in global::MyNamespace I hadn't seen this before, so looked it up in MSDN, which explained it nicely. My question is, do "global" and "::" always go together? Is there any other use for these operators, than as a pair? TIA,
3
1208
by: Tom Padilla | last post by:
I am making a map generator and for some bizarre reason I have a variable that will not come in scope. Code snippet: void placeContinents(int NumberOfContinents) { for(int Loop = 0; Loop < NumberOfContinents; Loop++) {
77
4002
by: M.B | last post by:
Guys, Need some of your opinion on an oft beaten track We have an option of using "goto" in C language, but most testbooks (even K&R) advice against use of it. My personal experience was that goto sometimes makes program some more cleaner and easy to understand and also quite useful (in error handling cases). So why goto is outlawed from civilized c programmers community. is there any technical inefficiency in that.
37
2207
by: mdh | last post by:
In one of the answers to a K&R exercise, the first couple of lines are: enum loop { NO, YES}; enum loop okloop=YES; I get the first line, but not the second. Sorry about the LOL question. Thanks in advance
6
1742
by: OriginalBrownster | last post by:
Hi there... I'm still pretty new to turbogears. but i have gotten pretty familiar with it i'm just trying to clear something up, i'm having a difficult time using \ when declaring a string expression such as tempname="\"..it says that the line is single qouted.
1
1280
by: soalvajavab1 | last post by:
I export an access table using Oracle ODBC driver to Oracle schema, it add character " to table name and all its column names like this "ff_to_oracle" ( ID VARCHAR2(20), "empid" VARCHAR2(20), "empname" VARCHAR2(50), "empdept" VARCHAR2(20), "create_date" DATE
0
8820
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...
1
8598
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
8670
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
7433
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6223
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5695
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
4406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2810
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
2
2051
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.