Determine if a function is available in a Python module

后端 未结 3 1294
一生所求
一生所求 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条回答
  •  萌比男神i
    2021-02-01 16:25

    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
    

提交回复
热议问题