473,725 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thoughts on using isinstance

In my code I am debating whether or not to validate the types of data
being passed to my functions. For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name , str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things? is it a "heavy"
operation? for example, if I use this in each function validate input
will it slow things down a lot?

just curious how you might handle this type of situation (other than
not validating at all).

thanks

Jan 24 '07 #1
21 3761


On Jan 24, 3:38 pm, "abcd" <codecr...@gmai l.comwrote:
In my code I am debating whether or not to validate the types of data
being passed to my functions. For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name , str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things? is it a "heavy"
operation? for example, if I use this in each function validate input
will it slow things down a lot?

just curious how you might handle this type of situation (other than
not validating at all).

thanks
My opinion is that validation is generally good. However, you have to
make it not too strict.
For example, instead of

print "Hello " + name

you could have written

print "Hello " + str(name)

In this case requirement isinstance() will be too strict. The only
thing you have to check is that hasattr(name, "__str__") and
callable(name._ _str__)

In this case you can have validation, while at the same time enjoy full
flexibility of dynamic typing.

--
Maxim

Jan 24 '07 #2
abcd wrote:
In my code I am debating whether or not to validate the types of data
being passed to my functions. For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name , str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things? is it a "heavy"
operation? for example, if I use this in each function validate input
will it slow things down a lot?

just curious how you might handle this type of situation (other than
not validating at all).

thanks
The "Python way" is to validate by performing the operations you need to
perform and catching any exceptions that result. In the case of your
example, you seem to be saying that you'd rather raise your own
exception (which, by the way, should really be a subclass of Exception,
but we will overlook that) that relying on the interpreter to raise a
ValueError or a TypeError. Is there really any advantage to this? You
increase your code size and add *something* to execution time with
little real purpose.

People coming to Python after C++ or some similar language that allows
or requires parameter type declarations often don't feel comfortable
taking this direction to start with, but it works well for most of us.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
Jan 24 '07 #3
abcd wrote:
In my code I am debating whether or not to validate the types of data
being passed to my functions. For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name , str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things? is it a "heavy"
operation? for example, if I use this in each function validate input
will it slow things down a lot?

just curious how you might handle this type of situation (other than
not validating at all).

thanks
The "Python way" is to validate by performing the operations you need to
perform and catching any exceptions that result. In the case of your
example, you seem to be saying that you'd rather raise your own
exception (which, by the way, should really be a subclass of Exception,
but we will overlook that) that relying on the interpreter to raise a
ValueError or a TypeError. Is there really any advantage to this? You
increase your code size and add *something* to execution time with
little real purpose.

People coming to Python after C++ or some similar language that allows
or requires parameter type declarations often don't feel comfortable
taking this direction to start with, but it works well for most of us.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com

Jan 24 '07 #4
"abcd" <co*******@gmai l.comwrote:
In my code I am debating whether or not to validate the types of data
being passed to my functions. For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name , str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things? is it a "heavy"
operation? for example, if I use this in each function validate input
will it slow things down a lot?

just curious how you might handle this type of situation (other than
not validating at all).
For a start, don't raise strings as exceptions: only use instances of
Exception.

Now consider what your first test does: it throws an error if you pass in
an empty string. Perhaps you do want to check for that, in which case you
will need to test for it and throw an appropriate exception.

The first test also catches values such as None, 0 or []. Do you really
want to throw a different exception for sayHello(0) and sayHello(1)? It
seems a bit pointless, so the first test should just check against an empty
string and not against other false objects which would get caught by the
second test.

Now for the second test. It would probably be useful to say in the
exception which type was involved, not just that it wasn't a string.
An appropriate exception for these would be something like:

TypeError: cannot concatenate 'str' and 'int' objects

since that tells you both the types and the operation that failed. Delete
that second test altogether and you'll get an appropriate exception instead
of a string which hides all the information.

A good rule is if you want to hide exception information from the user do
it when displaying the exception not when raising it. That way you can get
at all the exception information available by changing one place in the
code instead of having to do it everywhere.

So your modified function should look like:

def sayHello(name):
if name=="":
raise ValueError("nam e can't be blank")
print "Hello "+name

(this is slightly different than your original in a few other ways: it will
accept unicode strings so long as they can be encoded in ascii, and its a
function as there isn't much point having a method which doesn't use self.)
Jan 24 '07 #5
The "Python way" is to validate by performing the operations you need to
perform and catching any exceptions that result. In the case of your
example, you seem to be saying that you'd rather raise your own
exception (which, by the way, should really be a subclass of Exception,
but we will overlook that) that relying on the interpreter to raise a
ValueError or a TypeError. Is there really any advantage to this? You
increase your code size and add *something* to execution time with
little real purpose.

People coming to Python after C++ or some similar language that allows
or requires parameter type declarations often don't feel comfortable
taking this direction to start with, but it works well for most of us.

regards
Steve

So instead of validating input I should just try and use the input as
if it was correct, and let python throw the errors?

Jan 24 '07 #6
On 2007-01-24, abcd <co*******@gmai l.comwrote:
In my code I am debating whether or not to validate the types of data
being passed to my functions. For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name , str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things? is it a
"heavy" operation? for example, if I use this in each function
validate input will it slow things down a lot?

just curious how you might handle this type of situation (other
than not validating at all).
Validation of parameters is an excellent idea, but *not*
validation of datatypes. The problem is that sayHello can
function properly with many more objects than just strings, if
you write it differently. The following version accepts any
iterable over strings.

def sayHello(self, name):
it = iter(name)
print "Hello", ''.join(it)

It still lacks validation. But to validate a name you will need
to conceive a set of regular strings that contains every name
you'd like to accept. Names probably aren't worth validating,
although you might reasonably reject a few things, like the empty
string.

--
Neil Cerutti
Jan 24 '07 #7
abcd a écrit :
In my code I am debating whether or not to validate the types of data
being passed to my functions. For example

def sayHello(self, name):
if not name:
rasie "name can't be null"
if not isinstance(name , str):
raise "name must be a string"
print "Hello " + name

Is the use of isinstance a "bad" way of doing things?
Mostly, yes. Python is dynamically typed (well, it's dynamic all the
way...), and fighting against the language is a bad idea.

Also, since the use of an object of non-compatible type would usually
raise an exception (and while we're at it, avoid using strings as
exceptions - better to use some Exception class), you don't actually
gain anything.
just curious how you might handle this type of situation (other than
not validating at all).
There are mostly 2 cases :
1/ you're getting data from the outside world. Here, you have to be
*very* careful, and you usually need more than simple validation. Good
news is that we have modules like FormEncode designed to handle this case.

2/ you're getting 'data' from within your Python program. If you
correctly applied 1/, whatever comes in should be ok - that is, unless
you have a programmer error !-). But then, you'll usually have a nice
exception and traceback (or better unit tests failures), so you can fix
the problem immediatly.

Now there are *a few* corner cases where it makes sens to check what has
been passed to a function - either because there are very strict and
stable requirements here, or because the function can accept different
kinds of objects, but needs to handle them in distinct ways.

MVHO is that the less code the better. As a matter of fact, trying to
'protect' your function, you introduced a syntax error, that would not
have been here if you had just wrote the simplest thing:

def say_hello(who):
print "Hello", who

My 2 cents...
Jan 24 '07 #8
abcd wrote:
>The "Python way" is to validate by performing the operations you need to
perform and catching any exceptions that result. In the case of your
example, you seem to be saying that you'd rather raise your own
exception (which, by the way, should really be a subclass of Exception,
but we will overlook that) that relying on the interpreter to raise a
ValueError or a TypeError. Is there really any advantage to this? You
increase your code size and add *something* to execution time with
little real purpose.

People coming to Python after C++ or some similar language that allows
or requires parameter type declarations often don't feel comfortable
taking this direction to start with, but it works well for most of us.

regards
Steve


So instead of validating input I should just try and use the input as
if it was correct, and let python throw the errors?
Yes. This approach is often referred to as BTAFTP (better to ask
forgiveness than permission), as opposed to the LBYL (look before you
leap) approach that your original email inquired about.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com

Jan 24 '07 #9
Well my example function was simply taking a string and printing, but
most of my cases would be expecting a list, dictionary or some other
custom object. Still propose not to validate the type of data being
passed in?

Thanks.

Jan 24 '07 #10

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

Similar topics

30
2148
by: Stephen Horne | last post by:
Some more looping thoughts - this time on integer for loops... There may be some hint towards PEP284 (integer for loops) in a review of ideas from other languages, but I'm damned if i can figure it out. I spent some time thinking about it and couldn't find anything that would cover the issue. All I came up with was the recognition that some other languages have 'for' and 'foreach' loops. But Python went down the route of using 'for'...
6
2331
by: Michal Vitecek | last post by:
hello, please consider the following situation: under the current directory there's a subdirectory 'package' with two files: __init__.py and module.py ./package: __init__.py module.py
39
3168
by: Marco Aschwanden | last post by:
Hi I don't have to talk about the beauty of Python and its clear and readable syntax... but there are a few things that striked me while learning Python. I have collected those thoughts. I am sure there are many discussions on the "problems" mentioned here. But I had this thoughts without looking into any forums or anything... it is kind of feedback.
2
2596
by: | last post by:
I need to find out dynamically if an object is instance of a Class but I don't know how to use this isinstance buit-in function. I have the object and the name of the class, what should I do? Thanks Niurka
5
2400
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and relevant announcements. If you're interested, drop me a note. But if for some reason you think that this discussion is fine here at the c.l.py, please let me know. ** LONG POST AHEAD **
5
2605
by: Jordan Rastrick | last post by:
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...
5
1496
by: Chris Spencer | last post by:
Before I get too carried away with something that's probably unnecessary, please allow me to throw around some ideas. I've been looking for a method of transparent, scalable, and human-readable object persistence, and I've tried the standard lib's Shelve, Zope's ZODB, Divmod's Axiom, and others. However, while they're all useful, none satisfies all my criteria. So I started writing some toy code of my own: http://paste.plone.org/5227 ...
5
1500
by: Boris Borcic | last post by:
Given the ABC innovation, maybe an infix syntax for isinstance() would be good. Possibilities : - stealing "is" away from object identity. As a motivation, true use cases for testing object identity are rare; forcing the usage of a function or method to test it, would dissuade abuse. - allowing containment tests, ie "x in Number" to invoke isinstance() in the background when the container is of type <type>. My brain is too muddled by...
2
1383
by: dpapathanasiou | last post by:
If I define a dictionary where one or more of the values is also a dictionary, e.g.: my_dict={"a":"string", "b":"string", "c":{"x":"0","y":"1"}, "d":"string"} How can I use the output of type() so I can do one thing if the value is a string, and another if the value is a dictionary? i.e., I'd like to define a loop like this, but I'm not sure of the
0
8752
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
9401
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
9257
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
9116
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
6011
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
4519
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
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
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
2637
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.