Determine if a function is available in a Python module
<p>I am working on some Python socket code that's using the <a href="http://docs.python.org/library/socket.html#socket.fromfd" rel="nofollow"><code>socket.fromfd()</code></a> function.</p>

<p>However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.</p>

<p><strong>What's the best way to determine if a method is defined at runtime?</strong> Is the following sufficient or is there a better idiom?</p>

<pre><code>if 'fromfd' in dir(socket):
    sock = socket.fromfd(...)
else:
    sock = socket.socket(...)
</code></pre>

<p>I'm slightly concerned that the documentation for <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow"><code>dir()</code></a> seems to discourage its use. Would <a href="http://docs.python.org/library/functions.html#getattr" rel="nofollow"><code>getattr()</code></a> be a better choice, as in:</p>

<pre><code>if getattr(socket, 'fromfd', None) is not None:
    sock = socket.fromfd(...)
else:
    sock = socket.socket(...)
</code></pre>

<p>Thoughts?</p>

<p><strong>EDIT</strong> As <a href="http://stackoverflow.com/questions/763971/determine-if-a-function-is-available-in-a-python-module/763975#763975">Paolo</a> pointed out, this question is <a href="http://stackoverflow.com/questions/610883">nearly a duplicate</a> of a question about determining attribute presence. However, since the terminology used is disjoint (lk's <em>"object has an attribute"</em> vs my <em>"module has a function"</em>) it may be helpful to preserve this question for searchability unless the two can be combined.</p>
