<div><span class="gmail_quote">On 10/29/07, <b class="gmail_sendername">Kent Johnson</b> <<a href="mailto:kent37@tds.net">kent37@tds.net</a>> wrote:</span><blockquote class="gmail_quote" style="margin:0;margin-left:0.8ex;border-left:1px #ccc solid;padding-left:1ex">
Aditya Lal wrote:<br>> or use types module<br>><br>> import types<br>><br>> if type(n) == types.IntType or type(n) == types.LongType :<br>> blah!<br><br>A few notes:<br>- If you look at types.py, you find
<br>IntType = int<br>LongType = long<br><br>and so on for all the built-in types, so there is no need or advantage<br>to importing types vs<br> if type(n) == int<br><br>- Common Python practice is to prefer the least restrictive type check
<br>possible. For Dick's specific case it doesn't matter, but I generally<br>use isinstance() instead of checking for a specific type. The difference<br>is that isinstance() is true for subtypes as well as the named type. You
<br>can also pass a tuple of types to isinstance() so you can say<br> if isinstance(n, (int, long))<br><br>Kent<br><br></blockquote></div><div><br class="webkit-block-placeholder"></div>I completely agree that the check " type(n) == int " is very intuitive and simple. Its just that there are many more types that the basic ones and 'types' module provide a "consistent" way for checking for types. As an example - consider a function :
<div><br class="webkit-block-placeholder"></div><div>def execMyFun( f ) :</div><div> if type(f) == types.GeneratorType :</div><div> return f.next()</div><div> elif type(f) == types.FunctionType :</div><div> return f()
</div><div> else :</div><div> raise Exception("Invalid type for f : " + type(f) )</div><div><div><div><br class="webkit-block-placeholder"></div><div>Here types module came to the rescue which otherwise I would have written using exception handling.
<i>Well ! if you have a cleaner solution do let me know.</i></div><div><br> </div><div>BTW, isinstance is cool :) as it checks for all subclasses as well - didn't think of that.</div><div><br> </div><div>--</div><div>
Aditya
</div></div></div>