
tjreedy at udel
Aug 10, 2013, 12:46 PM
Post #8 of 31
(51 views)
Permalink
|
On 8/10/2013 2:00 PM, Xavi wrote: > Hello, > > El 10/08/2013 18:40, Tim Chase escribió: >> Generally, if you are using the "is" operator to compare against >> anything other than None, you're doing it wrong. There are exceptions >> to this, but it takes knowing the particulars. > > 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...') > > Because I think it is more clear and faster than .- > type(v) == [].__class__ ... or ... isinstance(v, list) > > Is this correct? It depends on the context. If one is writing a test for a function that is defined as returning a list, such as the builtin function *sorted*, then 'is list' would be correct. When one knows the type, as in your toy snippet, 'is list' is nonsensical. In a more typical situation, as when testing the argument to a function in the body of a function, then 'isinstance(arg, list)' is almost certainly more correct (but often still not best) as the function should usually accept at least any list subclass instance. def popslice(lis, start, stop=None, step=0): if not isinstance(lis, list): raise TypeError("Can only popslice a list") if stop is None: # here is where is *should* be used start, stop = 0, start ret = lis[start:stop:step] del lis[start:stop:step] return ret lis = list(range(10)) print(popslice(lis, 2, 9, 2), lis) >>> [2, 4, 6, 8] [0, 1, 3, 5, 7, 9] However, why exclude a mutable sequence that support slices but is not specifically a list? def popslice(seq, start, stop=None, step=0): if stop is None: # here is where is *should* be used start, stop = 0, start ret = seq[start:stop:step] del seq[start:stop:step] return ret Bad inputs will raise TypeErrors. TypeError: 'int' object is not subscriptable TypeError: 'tuple' object doesn't support item deletion It this is not good enough, wrap the body in try: ... except TypeError as e: raise TypeError("your custom message here") -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
|