On Sat, 10 Aug 2013 20:00:58 +0200, Xavi wrote:

> Now I have one doubt, I use 'is' to compare basic types in python 3, for
> example .-
> 
> v = []
> if type(v) is list:
>      print('Is list...')

No, do not do this. This is unnecessarily restrictive.

> Because I think it is more clear and faster than .- 

Clear? Maybe. Clear, but does the wrong thing. Using type rejects 
subclasses, which is normally a bad idea. Using isinstance accepts 
subclasses, which is what we nearly always should do.

As for being faster -- who cares? The difference between calling type and 
calling isinstance is about 0.02 microseconds on my slow computer. You 
should not try to optimize things which are so unimportant.

The first rule of optimization: Don't do it.
For experts only: Don't do it yet.

Until you have profiled your application, and discovered calling 
isinstance is the bottleneck making your application too slow, you are 
wasting your time trying to guess what will make it go faster.



> type(v) == [].__class__

You should not do that either. Names starting and ending with double-
underscore are reserved for Python. They are not quite private 
implementation details, but you almost never need to use them directly.

Why keep a dog and then bark yourself? Python will check __class__ for 
you, when and if needed. That is not your job. It is very rare to need to 
use __dunder__ attributes by hand.

> ... or ... isinstance(v, list)

That's the right solution, 99.9% of the time.

Actually, 99% of the time you should not call isinstance at all, but just 
catch any errors that occur; or better still, only catch them if you can 
do something about it. Otherwise, just allow the exception to propagate 
to the caller, who may catch it. Calling isinstance should be rare; 
calling type to check for an exact class even rarer.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to