<p dir="auto">This came up in Dask (<a class="issue-link js-issue-link" data-error-text="Failed to load title" data-id="399380819" data-permission-text="Title is private" data-url="https://github.com/dask/dask/issues/4387" data-hovercard-type="pull_request" data-hovercard-url="/dask/dask/pull/4387/hovercard" href="https://github.com/dask/dask/pull/4387">dask/dask#4387</a>). We have an object (<code class="notranslate">dask.delayed.Delayed</code>) that duck-types method/attribute access to build a graph from user code. Unfortunately this means that when <code class="notranslate">np.dtype</code> tries to get the <code class="notranslate">dtype</code> attribute it succeeds but doesn't return a valid dtype (it returns another delayed object). This leads to recursion and eventually a segfault.</p>
<p dir="auto">I'm able to reproduce his without dask as follows:</p>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="import numpy as np

class ShouldHaveNoDtype(object):
    &quot;&quot;&quot;This class happens to have a dtype attribute, but it doesn't actually
    meet the interface&quot;&quot;&quot;
    @property
    def dtype(self):
        &quot;&quot;&quot;Has the attribute, but doesn't return a dtype, leading to recursion&quot;&quot;&quot;
        return self


x = ShouldHaveNoDtype()
np.dtype(x)"><pre class="notranslate"><span class="pl-k">import</span> <span class="pl-s1">numpy</span> <span class="pl-k">as</span> <span class="pl-s1">np</span>

<span class="pl-k">class</span> <span class="pl-v">ShouldHaveNoDtype</span>(<span class="pl-s1">object</span>):
    <span class="pl-s">"""This class happens to have a dtype attribute, but it doesn't actually</span>
<span class="pl-s">    meet the interface"""</span>
    <span class="pl-en">@<span class="pl-s1">property</span></span>
    <span class="pl-k">def</span> <span class="pl-en">dtype</span>(<span class="pl-s1">self</span>):
        <span class="pl-s">"""Has the attribute, but doesn't return a dtype, leading to recursion"""</span>
        <span class="pl-k">return</span> <span class="pl-s1">self</span>


<span class="pl-s1">x</span> <span class="pl-c1">=</span> <span class="pl-v">ShouldHaveNoDtype</span>()
<span class="pl-s1">np</span>.<span class="pl-en">dtype</span>(<span class="pl-s1">x</span>)</pre></div>
<p dir="auto">The following code crashes numpy (latest master):</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="import numpy as np
class crashnumpy(object):
    @property
    def dtype(self):
        return self
np.array([1], dtype=crashnumpy())"><pre class="notranslate"><code class="notranslate">import numpy as np
class crashnumpy(object):
    @property
    def dtype(self):
        return self
np.array([1], dtype=crashnumpy())
</code></pre></div>