What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?
Let\'s say I have an objec
The most Pythonic way to check the type of an object is... not to check it.
Since Python encourages Duck Typing, you should just try...except
to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file
, just try to use its .write()
method!
Of course, sometimes these nice abstractions break down and isinstance(obj, cls)
is what you need. But use sparingly.
You can check for type of a variable using __name__ of a type.
Ex:
>>> a = [1,2,3,4]
>>> b = 1
>>> type(a).__name__
'list'
>>> type(a).__name__ == 'list'
True
>>> type(b).__name__ == 'list'
False
>>> type(b).__name__
'int'
isinstance(o, str)
Link to docs
You can check with the below line to check which character type the given value is:
def chr_type(chrx):
if chrx.isalpha()==True:
return 'alpha'
elif chrx.isdigit()==True:
return 'numeric'
else:
return 'nothing'
chr_type("12)
I think the best way is to typing well your variables. You can do this by using the "typing" library.
Example:
from typing import NewType
UserId = NewType ('UserId', int)
some_id = UserId (524313
)`
See https://docs.python.org/3/library/typing.html
To Hugo:
You probably mean list
rather than array
, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.
Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all
try:
my_sequence.extend(o)
except TypeError:
my_sequence.append(o)
One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.
I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a [ ]
around your single value when you pass it in if need be.
(Though this can cause errors with strings, as they do look like (are) sequences.)