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.
-
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.
Paolo Bergantino : I don't see how this answer deserves a downvote... :/bobince : I'd prefer hasattr over getattr just for readability's sake! -
Or simply use a try..except block:
try: sock = socket.fromfd(...) except AttributeError: sock = socket.socket(...)
Paolo Bergantino : I believe that would throw an AttributeError if it doesn't exist, not a NameError -
hasattr(obj, 'attributename') is probably a better one. hasattr will try to access the attribute, and if it's not there, it'll return false.
It's possible to have dynamic methods in python, i.e. methods that are created when you try to access them. They would not be in dir(...). However hasattr would check for it.
>>> class C(object): ... def __init__(self): ... pass ... def mymethod1(self): ... print "In #1" ... def __getattr__(self, name): ... if name == 'mymethod2': ... def func(): ... print "In my super meta #2" ... return func ... else: ... raise AttributeError ... >>> c = C() >>> 'mymethod1' in dir(c) True >>> hasattr(c, 'mymethod1') True >>> c.mymethod1() In #1 >>> 'mymethod2' in dir(c) False >>> hasattr(c, 'mymethod2') True >>> c.mymethod2() In my super meta #2
0 comments:
Post a Comment