Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a function is available in a Python module

Tags:

python

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.

like image 990
David Citron Avatar asked Apr 18 '09 19:04

David Citron


People also ask

How do I see all the functions in a Python module?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

How do you check if a function is in Python?

You should just use hasattr(some_class, "some_function") for more clarity and because sometimes dict is not used, although this still does not check whether you're dealing with a function or not.

Which library function returns the list of all functions in a module?

dir() is a built-in function that also returns the list of all attributes and functions in a module.

How do I explore a Python module?

Use the built-in dir() function to interactively explore Python modules and classes from an interpreter session. The help() built-in lets you browse through the documentation right from your interpreter.


1 Answers

hasattr() is the best choice. Go with that. :)

if hasattr(socket, 'fromfd'):     pass else:     pass 

EDIT: Actually, according to the docs all hasattr is doing is calling getattr and catching the exception. So if you want to cut out the middle man you should go with marcog's answer.

EDIT: I also just realized this question is actually a duplicate. One of the answers there discusses the merits of the two options you have: catching the exception ("easier to ask for forgiveness than permission") or simply checking before hand ("look before you leap"). Honestly, I am more of the latter, but it seems like the Python community leans towards the former school of thought.

like image 143
Paolo Bergantino Avatar answered Oct 08 '22 03:10

Paolo Bergantino