Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To get the type of an object, you can use the built-in <a href="http://docs.python.org/3/library/functions.html#type" rel="noreferrer"><code>type()</code></a> function. Passing an object as the only parameter will return the type object of that object:</p> <pre><code>&gt;&gt;&gt; type([]) is list True &gt;&gt;&gt; type({}) is dict True &gt;&gt;&gt; type('') is str True &gt;&gt;&gt; type(0) is int True &gt;&gt;&gt; type({}) &lt;type 'dict'&gt; &gt;&gt;&gt; type([]) &lt;type 'list'&gt; </code></pre> <p>This of course also works for custom types:</p> <pre><code>&gt;&gt;&gt; class Test1 (object): pass &gt;&gt;&gt; class Test2 (Test1): pass &gt;&gt;&gt; a = Test1() &gt;&gt;&gt; b = Test2() &gt;&gt;&gt; type(a) is Test1 True &gt;&gt;&gt; type(b) is Test2 True </code></pre> <p>Note that <code>type()</code> will only return the immediate type of the object, but won’t be able to tell you about type inheritance.</p> <pre><code>&gt;&gt;&gt; type(b) is Test1 False </code></pre> <p>To cover that, you should use the <a href="http://docs.python.org/3/library/functions.html#isinstance" rel="noreferrer"><code>isinstance</code></a> function. This of course also works for built-in types:</p> <pre><code>&gt;&gt;&gt; isinstance(b, Test1) True &gt;&gt;&gt; isinstance(b, Test2) True &gt;&gt;&gt; isinstance(a, Test1) True &gt;&gt;&gt; isinstance(a, Test2) False &gt;&gt;&gt; isinstance([], list) True &gt;&gt;&gt; isinstance({}, dict) True </code></pre> <p><code>isinstance()</code> is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using <code>isinstance()</code> is preferred over <code>type()</code>.</p> <p>The second parameter of <code>isinstance()</code> also accepts a tuple of types, so it’s possible to check for multiple types at once. <code>isinstance</code> will then return true, if the object is of any of those types:</p> <pre><code>&gt;&gt;&gt; isinstance([], (tuple, list, set)) True </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload