InstanceType tests in Python-3.0

Robin Becker robin at reportlab.com
Thu Feb 14 12:21:20 EST 2008


Steven D'Aprano wrote:
> 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
>> this
>>
>> t = type(e)
>> if t==InstanceType:
>>     return f0(e)
>> elif t in (float,int):
>>     return f1(e)
>> else:
>>     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
>     return f0(e)
> elif isinstance(e, (float, int)):
>     return f1(e)
> else:
>     return str(e)
> 
> Now all you have to do is work out what to do with new-style classes...
> 

except that unfortunately python 3.0 doesn't have type.InstanceType and module 
types doesn't have those old style ones any more :(


> 
>> In python 3.0 everything has been unified and people say use attributes
........
> 
> No, this is SPARTA!!!
> 
> (Sorry, I couldn't resist. And I didn't even like the movie.)
> 
> 

nobody expects the Spartacists any more :)

>> and this code is fairly complex. Originally we had a distinction
.......
> 
> 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?
> 
> 
This is a formatting function it either expects primitives like string/number or 
a structured object. Usually an object that has been entered into a lookup table 
or one that needs to be rendered using a formatting function defined on the object.

In the old world (with inquisitions)we could tell the difference between user 
class instances and other types (effectively primitive types). Since I'm trying 
to write out pdf we wanted to treat numerics specially by formatting them with a 
predefined number of decimals (anything else is wasted), but essentially the int 
branch too could be just str(e).
-- 
Robin Becker




More information about the Python-list mailing list