Note that there are some explanatory texts on larger screens.

plurals
  1. PODetermine if a function is available in a Python module
    primarykey
    data
    text
    <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 noreferrer"><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 noreferrer"><code>dir()</code></a> seems to discourage its use. Would <a href="http://docs.python.org/library/functions.html#getattr" rel="nofollow noreferrer"><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="https://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="https://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>
    singulars
    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.
 

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