What's the Canonical Way to Check For Type in Python

What's the canonical way to check for type in Python?

Use isinstance to check if o is an instance of str or any subclass of str:

if isinstance(o, str):

To check if the type of o is exactly str, excluding subclasses of str:

if type(o) is str:

Another alternative to the above:

if issubclass(type(o), str):

See Built-in Functions in the Python Library Reference for relevant information.



Checking for strings in Python 2

For Python 2, this is a better way to check if o is a string:

if isinstance(o, basestring):

because this will also catch Unicode strings. unicode is not a subclass of str; whereas, both str and unicode are subclasses of basestring. In Python 3, basestring no longer exists since there's a strict separation of strings (str) and binary data (bytes).

Alternatively, isinstance accepts a tuple of classes. This will return True if o is an instance of any subclass of any of (str, unicode):

if isinstance(o, (str, unicode)):

what is the canonical way to check the type of input?

It up to you to convert your input to whatever you need.

But, you can guess like this:

import sys

p = raw_input("Enter input")

if p.lower() in ("true", "yes", "t", "y"):
p = True
elif p.lower() in ("false", "no", "f", "n"):
p = False
else:
try:
p = int(p)
except ValueError:
try:
p = float(p)
except ValueError:
p = p.decode(sys.getfilesystemencoding()

This support bool, int, float and unicode.

Notes:

  • Python has no char type: use a string of length 1,
  • This int function can parse int values but also long values and even very long values,
  • The float type in Python has a precision of a double (which doesn't exist in Python).

See also: Parse String to Float or Int

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

What is the best (idiomatic) way to check the type of a Python variable?

What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping instead of dict as per the ABC PEP.

def value_list(x):
if isinstance(x, dict):
return list(set(x.values()))
elif isinstance(x, basestring):
return [x]
else:
return None


Related Topics



Leave a reply



Submit