title: Python: How to cast based on type without needing to import the objects we need to verify type
body: <p>Consider as a matter of an example the following function:</p>
  <pre class="lang-py prettyprint-override"><code>import numpy as np
  
  # module.py
  def func(x):
      if isinstance(x, np.ndarray):
          x = x.tolist()
      assert isinstance(x[0], int)
      # do more stuff...
      return x
  </code></pre>
  <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; x = np.array([1,2,3], np.int16)
  &gt;&gt;&gt; func(x)
  [1, 2, 3]
  </code></pre>
  <p>How can one implement the conditional casting without having to import numpy?</p>
  <p>One way to do this would be to do:</p>
  <pre class="lang-py prettyprint-override"><code>if str(type(x)) == &quot;&lt;class 'numpy.ndarray'&gt;&quot;):
      x = x.tolist()
  ...
  </code></pre>
  <p>but that solution feels fragile (depends on the stability of the <code>__str__</code> method).</p>
  <p>Any less fragile ways to do this?</p>
  <p><em>Appendix to deflect likely (but useless) responses: I know duck typing, <code>hasattr</code>, and don't want to go into details of why I want to avoid the imports in the first place.</em></p>