I am working on some Python socket code that's using the socket.fromfd()
function.
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.
What's the best way to determine if a method is defined at runtime? Is the following sufficient or is there a better idiom?
if 'fromfd' in dir(socket):
sock = socket.fromfd(...)
else:
sock = socket.socket(...)
I'm slightly concerned that the documentation for dir()
seems to discourage its use. Would getattr()
be a better choice, as in:
if getattr(socket, 'fromfd', None) is not None:
sock = socket.fromfd(...)
else:
sock = socket.socket(...)
Thoughts?
EDIT As Paolo pointed out, this question is nearly a duplicate of a question about determining attribute presence. However, since the terminology used is disjoint (lk's "object has an attribute" vs my "module has a function") it may be helpful to preserve this question for searchability unless the two can be combined.