Reputation: 174485
I was recently tasked with migrating a bunch of existing python 2.7 scripts to python 3.x, and noticed a statement in one of the scripts that I don't quite understand:
if isinstance(some_variable, (list,)):
# ...
At first I thought the (,)
syntax might be a way to express a partially typed tuple, but that doesn't seem to be the case:
>>> isinstance(([],123), (list,))
False
Looking at the calling code, I found that the only argument values ever passed as some_variable
were lists, so I tested:
>>> isinstance([], (list,))
True
So why would you use (list,)
instead of just list
with isinstance()
?
I suspect that there might be other (list-like?) types for which the call to isinstance()
would return True
, but I don't have the requisite python experience to think of what it be :)
Upvotes: 0
Views: 86
Reputation: 24049
This is (list,)
tuple with one element and like this list
and for your example :
>>> isinstance(([],123), (list,))
False
>>> isinstance(([],123), (tuple,))
True
>>> isinstance(([],123), tuple)
True
if you want check isinstance
do with map
like below:
>>> list(map(lambda x : isinstance(x , (list,)), ([],123)))
[True, False]
>>> all(map(lambda x : isinstance(x , (list,)), ([],123)))
False
>>> any(map(lambda x : isinstance(x , (list,)), ([],123)))
True
Upvotes: 1
Reputation: 23815
isinstance can get a type OR a tuple of types as the second argument.
(list,)
is a tuple with 1 entry only. In the case that you have only one type to compare against you dont have to use tuple
Upvotes: 3