Determine if a function is available in a Python module

后端 未结 3 1241
一生所求
一生所求 2021-02-01 15:59

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

3条回答
  •  抹茶落季
    2021-02-01 16:37

    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.

提交回复
热议问题