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

what w
whatsapp app
how to pronounce what
what c
what p
what h
whatsapp login

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 object o. How do I check whether it's a str?

To check if o is an instance of str or any subclass of str, use isinstance (this would be the "canonical" way):

if isinstance(o, str):

To check if the type of o is exactly str (exclude subclasses):

if type(o) is str:

The following also works, and can be useful in some cases:

if issubclass(type(o), str):

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

One more note: in this case, if you're using python 2, you may actually want to use:

if isinstance(o, basestring):

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

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

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

What, is classified under pronouns because it replaces a thing or a noun. Quickly send and receive WhatsApp messages right from your computer. Quickly send and receive WhatsApp messages right from your computer. WhatsApp Web.

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.

Mean, Median, Mode, and Range, be, "what for" a.k.a. (the reason for punishment). There's always a reason for a punishment. What definition, (used interrogatively as a request for specific information): What is the matter? See more.

isinstance(o, str) will return True if o is an str or is of a type that inherits from str.

type(o) is str will return True if and only if o is a str. It will return False if o is of a type that inherits from str.

What Part of Speech is “WHAT”, I will do what I can to help you. TranslationsEdit. show ▽what? (interrogative pronoun)  Define what. what synonyms, what pronunciation, what translation, English dictionary definition of what. pron. 1. a. Which thing or which particular one of many: What are you having for dinner?

After the question was asked and answered, type hints were added to Python. Type hints in Python allow types to be checked but in a very different way from statically typed languages. Type hints in Python associate the expected types of arguments with functions as runtime accessible data associated with functions and this allows for types to be checked. Example of type hint syntax:

def foo(i: int):
    return i


In this case we want an error to be triggered for foo('oops') since the annotated type of the argument is int. The added type hint does not cause an error to occur when the script is run normally. However, it adds attributes to the function describing the expected types that other programs can query and use to check for type errors.

One of these other programs that can be used to find the type error is mypy:

mypy script.py
script.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "int"

(You might need to install mypy from your package manager. I don't think it comes with CPython but seems to have some level of "officialness".)

Type checking this way is different from type checking in statically typed compiled languages. Because types are dynamic in Python, type checking must be done at runtime, which imposes a cost -- even on correct programs -- if we insist that it happen at every chance. Explicit type checks may also be more restrictive than needed and cause unnecessary errors (e.g. does the argument really need to be of exactly list type or is anything iterable sufficient?).

The upside of explicit type checking is that it can catch errors earlier and give clearer error messages than duck typing. The exact requirements of a duck type can only be expressed with external documentation (hopefully it's thorough and accurate) and errors from incompatible types can occur far from where they originate.

Python's type hints are meant to offer a compromise where types can be specified and checked but there is no additional cost during usual code execution.

The typing package offers type variables that can be used in type hints to express needed behaviors without requiring particular types. For example, it includes variables such as Iterable and Callable for hints to specify the need for any type with those behaviors.

While type hints are the most Pythonic way to check types, it's often even more Pythonic to not check types at all and rely on duck typing. Type hints are relatively new and the jury is still out on when they're the most Pythonic solution. A relatively uncontroversial but very general comparison: Type hints provide a form of documentation that can be enforced, allow code to generate earlier and easier to understand errors, can catch errors that duck typing can't, and can be checked statically (in an unusual sense but it's still outside of runtime). On the other hand, duck typing has been the Pythonic way for a long time, doesn't impose the cognitive overhead of static typing, is less verbose, and will accept all viable types and then some.

What does "what for" mean and where did it come from?", Medical researchers have been studying everything we know about Covid-19. What have they learned – and is it enough to halt the pandemic? WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.

Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb.

class Bomb:
    def __init__(self):

    def talk(self):

    def explode(self):
        print "BOOM!, The bomb explodes."

class Duck:
    def __init__(self):
    def talk(self):
        print "I am a duck, I will not blow up if you ask me to talk."    

class Kid:
    kids_duck = None

    def __init__(self):
        print "Kid comes around a corner and asks you for money so he could buy a duck."

    def takeDuck(self, duck):
        self.kids_duck = duck
        print "The kid accepts the duck, and happily skips along"

    def doYourThing(self):
        print "The kid tries to get the duck to talk"

myKid = Kid()
myBomb = Bomb()

What does cambridge mean?, what meaning: 1. used to ask for information about people or things: 2. used in questions that show you are…. Learn more. This is the ORIGINAL "What What (In the Butt)" video. The South Park version aired over a year after we made this video. There's been a lot of confusion about this. We can assure you, we are not

what, Sort of: Early Wednesday morning, she released "Oh, What A World 2.0" — a reworked version of a song from 2018's Golden Hour — on her  Seen a font in use and want to know what it is? Upload an image to WhatTheFont to find the closest matches in our database.

Coronavirus: what have scientists learned about Covid-19 so far , The way Illinois finally got the masks it needed was practically the plot to a heist thriller — so we turned it into one for the first of our Quarantine  Find out what your public IPv4 and IPv6 address is revealing about you! My IP address information shows your location; city, region, country, ISP and location on a map.

WHAT, Quickly send and receive WhatsApp messages right from your computer. Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.

  • Well, the canonical approach in Python is to not check the type at all (unless you're debugging). Usually you just try to use it as a string (e.g. concatenate with other strings, print to console, etc.); if you think it might fail, use try/except or hasattr. That said, the accepted answer is the canonical way to do what you generally "shouldn't do" in the Python world. For more info, google "Python duck typing" or read these: voidspace.org.uk/python/articles/duck_typing.shtml stackoverflow.com/questions/610883/…
  • I think Mr. Coombs is overlooking examples like non-JSON serializable classes. If putting a big chunk of data through a function (whose code one can't influence) one might want to convert certain pieces of that data to, for instance, a <str> before passing it. At least that's how I ended up on this page...
  • It seems the most common reason for asking for this is that one wants to distinguish between strings and iterables of strings. This is a tricky question because strings are iterables of strings -- a single-character string is even a sequence of itself (last time I checked -- one probably shouldn't rely on it). But would anyone ever have use for something string-like? Yes. So the answer to "What should I do to distinguish between strings and other iterables of strings?" is properly: "It depends on what you are trying to do". :-D
  • Python type annotations are now a thing. Take a look at mypy
  • str.__subclasses__() only returns the direct subclasses of str, and does not do the same thing as issubclass() or isinstance(). (To do that, you would have to recursively call .__subclasses__().
  • This is a good answer, but I think it really ought to start with a warning that you usually shouldn't be doing this in Python. As it is, it seems to validate the assumption that this is a "canonical thing to do in Python", which it isn't.
  • These are python2 answers. For example, there is no basestring in python3.
  • What's the difference between instance and "exactly"? If type(a) is Object then isn't it also true that isinstance(a, Object). However, if type(a) is SubClassOfObject, then type(a) is Object == False, but isinstance(a, Object) == True. Right?
  • @mavavilj - a is b means a and b are the exact same thing, i.e. references to the same entity in memory. So a and b would have to be the exact same class, not subclasses, as with isinstance(). See for example stackoverflow.com/a/133024/1072212
  • IMHO, the most Pythonic way is to cope with whatever argument which is given. In my code I often cannot know if I recieve an object or an array of objects, and I use type-checking internally to convert a single object to a one-element list.
  • Rather then just trying to use its write method there are times when you want to do this without causing an exception. In this case you could do... if hasattr(ob, "write") and callable(ob.write): Or save some dict access... func = getattr(ob, "write", None) if callable(func): ...
  • Duck typing is about using an library. Type checking is about writing an library. Not the same problem domain.
  • @RickyA, I disagree. Duck typing is about interacting with objects using interfaces with well-known semantics. This can apply either to library code or to the code that uses such a library.
  • @nyuszika7h, In Python3 hasattr only supresses an AttributeError - See: docs.python.org/3.4/library/functions.html#hasattr