InstanceType tests in Python-3.0
steve at REMOVE-THIS-cybersource.com.au
Thu Feb 14 16:47:16 CET 2008
On Thu, 14 Feb 2008 15:26:08 +0000, Robin Becker wrote:
> I'm in the process of porting some code. I have 2.x code that looks like
> t = type(e)
> if t==InstanceType:
> return f0(e)
> elif t in (float,int):
> return f1(e)
> return str(e)
What happens if e is an instance of a subclass of int, or str?
I'd write the above like this:
if isinstance(e, type.InstanceType):
# old-style classes don't exist in Python 3
elif isinstance(e, (float, int)):
Now all you have to do is work out what to do with new-style classes...
> In python 3.0 everything has been unified and people say use attributes
> to tell what should be done in such a branch.
Well, you know what people say about people who listen to everything
What do you mean "everything" has been unified?
What do you mean "use attributes to tell what should be done"?
> However, this is the real world
No, this is SPARTA!!!
(Sorry, I couldn't resist. And I didn't even like the movie.)
> and this code is fairly complex. Originally we had a distinction
> between user defined class instances and those of the builtins like
> float, int, str etc etc. Is there any way for me to tell if an object is
> an instance of a used defined class which can then be tested further
Why do you care if it is a user-defined class or not? What are you
actually trying to accomplish? What's your aim in doing this testing?
More information about the Python-list