473,396 Members | 1,866 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

sufficiently pythonic code for testing type of function

I wrote this for someone else to take an object and list of types,
then check if obj is one of those types, raising an error otherwise.

Is it enough to rely on side effects or absence thereof, or should I
put return True in here somewhere?

def test_obj_type(obj, types):
for type in types:
if isinstance(obj, type):
break
else:
raise ValueError, 'object is not in %s' % types

-- Theerasak
Oct 11 '06 #1
15 1216
Theerasak Photha wrote:
I wrote this for someone else to take an object and list of types,
then check if obj is one of those types, raising an error otherwise.

Is it enough to rely on side effects or absence thereof, or should I
put return True in here somewhere?

def test_obj_type(obj, types):
for type in types:
if isinstance(obj, type):
break
else:
raise ValueError, 'object is not in %s' % types
Hello Theerasak,

To answer your question: Either (a) return True if OK, False if not OK
or (b) make it like an assertion: raise an exception if not OK, do
nothing if OK. Returning True from the above function would be a rather
strange hybrid.

However:

1. if isinstance(obj, types[1] is true, but isinstance(obj, types[0])
is false, this would appear to raise ValueError. Is the indentation of
the else and raise what you intended?

2. In any case, since Python 2.2, no loop is necessary:

def test_obj_type(obj, types):
if not isinstance(obj, types):
raise ValueError, 'object is not in %s' % (types, )

If you don't want the assertion style, your "someone else" can call
isinstance directly.

3. And please notice the change in the raise line; if types is a tuple
of two or more items, the % operator treats it specially. As coded, you
would get this exception:
"TypeError: not all arguments converted during string formatting"

HTH,
John

Oct 11 '06 #2
Theerasak Photha wrote:
I wrote this for someone else to take an object and list of types,
then check if obj is one of those types,
This is already what isinstance(obj, tuple_of_types) does.
raising an error otherwise.

Is it enough to rely on side effects or absence thereof, or should I
put return True in here somewhere?
What for ?
def test_obj_type(obj, types):
for type in types:
if isinstance(obj, type):
break
else:
raise ValueError, 'object is not in %s' % types


def checkinstanceof(obj, types):
if not isinstance(obj, types):
raise ValueError('object is not an instance of %s' % str(types))
Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?
-- Theerasak

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Oct 11 '06 #3
On 10/11/06, Bruno Desthuilliers <on***@xiludom.growrote:
Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?
Perhaps:

try:
for attribute in ['foo', 'bar', '__baz__']:
getattr(mystery_object, '__%s__' % attribute)
except AttributeError:
# Do sumthin bout it

Is it wrong to 're-raise' an exception with application-specific
details within an except clause?

-- Theerasak
Oct 11 '06 #4
Theerasak Photha wrote:
>Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?

Perhaps:

try:
for attribute in ['foo', 'bar', '__baz__']:
getattr(mystery_object, '__%s__' % attribute)
except AttributeError:
# Do sumthin bout it

Is it wrong to 're-raise' an exception with application-specific
details within an except clause?
nope, as long as the new exception is provides more accurate information
about what actually happened. something like

try:
do something
except ValueError:
raise RuntimeError("the frobnitz failed to catch the kitten")

can be a lot better than a 30-level traceback that ends with a line
looking something like

fnut.index(gah)

on the other hand, things like this are all too common:

try:
do something
except:
raise Exception("something happened")

also, checking for __method__ is, in general, not the right way to check
if an object implements a given interface. some types use C-level slots
or alternative hooks to provide functionality, and such things are not
always visible from the outside (Python knows how to use them, though).

so if you can, try doing the operation instead, and catch error (if you
really need to check first, use an idempotent operation, if available).

</F>

Oct 11 '06 #5
On 10/11/06, Fredrik Lundh <fr*****@pythonware.comwrote:
can be a lot better than a 30-level traceback that ends with a line
looking something like

fnut.index(gah)
Despite long experience with Perl, I am not a big follower of the
"goose_level: blah" method of error reporting...
also, checking for __method__ is, in general, not the right way to check
if an object implements a given interface.
I had a vague feeling it might not be a Right Thing(tm).
<flame-proof-underwear>I kind of miss
responds_to?</flame-proof-underwear>
so if you can, try doing the operation instead, and catch error (if you
really need to check first, use an idempotent operation, if available).
I'll do that as soon as my green noggin figures out what 'idempotent' means.

Serves me right for being a liberal arts weenie:
http://www.c2.com/cgi/wiki?ThaiLanguage

-- Theerasak
Oct 11 '06 #6
Theerasak Photha wrote:
I'll do that as soon as my green noggin figures out what 'idempotent' means.
"Acting as if used only once, even if used multiple times", to quote
the first explanation I saw on the google result page.

and from the irony department, googling for "indempotent" provides an
even clearer explanation: "Refers to an operation that produces the same
results no matter how many times it is performed."

</F>

Oct 11 '06 #7
Theerasak Photha wrote:
On 10/11/06, Fredrik Lundh <fr*****@pythonware.comwrote:
>can be a lot better than a 30-level traceback that ends with a line
looking something like

fnut.index(gah)

Despite long experience with Perl, I am not a big follower of the
"goose_level: blah" method of error reporting...
>also, checking for __method__ is, in general, not the right way to check
if an object implements a given interface.

I had a vague feeling it might not be a Right Thing(tm).
<flame-proof-underwear>I kind of miss
responds_to?</flame-proof-underwear>
getattr(obj, name[,default]) is your friend. Remember that methods are
just callable attributes.
>so if you can, try doing the operation instead, and catch error (if you
really need to check first, use an idempotent operation, if available).

I'll do that as soon as my green noggin figures out what 'idempotent'
means.
idempotent -no side effects.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Oct 11 '06 #8
On 2006-10-11, Bruno Desthuilliers <on***@xiludom.growrote:
>
Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?
one possible answer: Use ZopeInterfaces
(and ask objects 'do you implement interface X' rather than 'are you type Y')

Not sure what options you have when dealing with builtin data types however.
Albert
Oct 11 '06 #9
A.T.Hofkamp wrote:
On 2006-10-11, Bruno Desthuilliers <on***@xiludom.growrote:
>Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?

one possible answer: Use ZopeInterfaces
(and ask objects 'do you implement interface X' rather than 'are you type Y')

Not sure what options you have when dealing with builtin data types however.
This was mostly a rethorical question...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Oct 11 '06 #10

Theerasak Photha a écrit :
On 10/11/06, Bruno Desthuilliers <on***@xiludom.growrote:
Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?

Perhaps:

try:
for attribute in ['foo', 'bar', '__baz__']:
getattr(mystery_object, '__%s__' % attribute)
except AttributeError:
# Do sumthin bout it
Isn't this a case of useless overcomplexification ? Since you end up
raising an exception, why not just assume the object is ok and let
Python raise the exception for you if it is not ? From the client code
POV, it doesn't make much difference !-)

Is it wrong to 're-raise' an exception with application-specific
details within an except clause?
Nope - as long as you provide more details (or more helpful details)
*and* do not loose/mask/whatever useful infos from the original
exception.

Oct 11 '06 #11
On 2006-10-11, Bruno Desthuilliers <on***@xiludom.growrote:
A.T.Hofkamp wrote:
>On 2006-10-11, Bruno Desthuilliers <on***@xiludom.growrote:
>>Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?

one possible answer: Use ZopeInterfaces
(and ask objects 'do you implement interface X' rather than 'are you type Y')

Not sure what options you have when dealing with builtin data types however.

This was mostly a rethorical question...
And even for rethorical questions, Python already provides a solution.. :-)

Albert
Oct 12 '06 #12
On 10/11/06, Bruno Desthuilliers <on***@xiludom.growrote:
Theerasak Photha wrote:
On 10/11/06, Fredrik Lundh <fr*****@pythonware.comwrote:
can be a lot better than a 30-level traceback that ends with a line
looking something like

fnut.index(gah)
Despite long experience with Perl, I am not a big follower of the
"goose_level: blah" method of error reporting...
also, checking for __method__ is, in general, not the right way to check
if an object implements a given interface.
I had a vague feeling it might not be a Right Thing(tm).
<flame-proof-underwear>I kind of miss
responds_to?</flame-proof-underwear>

getattr(obj, name[,default]) is your friend. Remember that methods are
just callable attributes.
I am familiar with getattr from the Introspection material in Dive
into Python of course.

Earlier in the thread we decided that using getattr is the Wrong
Way(tm) to decide whether an object has such and such operation
(respond_to?) because implementation details can hide this.

So I learned the best thing to do is Suck It And See (an electrical
joke, not a penis joke, BION) aka EAFP.

I just found out Ruby isn't much better in this regard:

class Foo
def self.method_missing(meth, *args)
puts meth
end
end

Foo.bar()
puts Foo.respond_to?(:bar)

===>
bar
false

WTF?

-- Theerasak
Oct 13 '06 #13
Bruno Desthuilliers wrote:
... idempotent -no side effects.
Nope. idempotent: f(f(x)) = f(x)
That is, after doing it once, repeating it won't hurt.

--Scott David Daniels
sc***********@acm.org
Oct 13 '06 #14
Scott David Daniels wrote:
Nope. idempotent: f(f(x)) = f(x)
That is, after doing it once, repeating it won't hurt.
http://en.wikipedia.org/wiki/Idempot...ter_science%29

</F>

Oct 13 '06 #15
Fredrik Lundh wrote:
Scott David Daniels wrote:
>Nope. idempotent: f(f(x)) = f(x)
That is, after doing it once, repeating it won't hurt.

http://en.wikipedia.org/wiki/Idempot...ter_science%29

</F>
Thank you (Scott and Fredrik) for the correction.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Oct 16 '06 #16

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

Similar topics

15
by: Ville Vainio | last post by:
Pythonic Nirvana - towards a true Object Oriented Environment ============================================================= IPython (by Francois Pinard) recently (next release - changes are...
6
by: Alan G Isaac | last post by:
Given a list of functions, it seems there must be a Pythonic approach to composition. Something like def compose(fns): return lambda x: reduce(lambda f,g: f(g),fns)(x) This will not work...
8
by: Nick Coghlan | last post by:
Time for another random syntax idea. . . So, I was tinkering in the interactive interpreter, and came up with the following one-size-fits-most default argument hack: Py> x = 1 Py> def...
3
by: Ben | last post by:
Hi There I am doing some unit testing at the moment, and the majority of the leg work involves taking two objects (expected vs actual) and verifying that their properties are equal. The objects...
3
by: David MacKay | last post by:
Dear Greater Py, <motivation note="reading this bit is optional"> I am writing a command-line reader for python. I'm trying to write something with the same brevity as perl's one-liner ...
4
by: Carl J. Van Arsdall | last post by:
It seems the more I come to learn about Python as a langauge and the way its used I've come across several discussions where people discuss how to do things using an OO model and then how to design...
5
by: akameswaran | last post by:
Disclaimer - I recognize this is not a practical exercise. There are many implementations around that would do the job better, more efficiently (Meaning in C) or whatever. I caught some thread...
16
by: Andy Dingley | last post by:
I'm trying to write rot13, but to do it in a better and more Pythonic style than I'm currrently using. What would you reckon to the following pretty ugly thing? How would you improve it? In...
13
by: problem. | last post by:
#include <stdio.h> #include <stdlib.h> int main(void) { int a, b; float result = 0.0f; char symbol = '\0'; int loop = 0;
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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...

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.