inspect_util.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import inspect
  2. def is_cython(obj):
  3. """Check if an object is a Cython function or method"""
  4. # TODO(suo): We could split these into two functions, one for Cython
  5. # functions and another for Cython methods.
  6. # TODO(suo): There doesn't appear to be a Cython function 'type' we can
  7. # check against via isinstance. Please correct me if I'm wrong.
  8. def check_cython(x):
  9. return type(x).__name__ == "cython_function_or_method"
  10. # Check if function or method, respectively
  11. return check_cython(obj) or (
  12. hasattr(obj, "__func__") and check_cython(obj.__func__)
  13. )
  14. def is_function_or_method(obj):
  15. """Check if an object is a function or method.
  16. Args:
  17. obj: The Python object in question.
  18. Returns:
  19. True if the object is an function or method.
  20. """
  21. return inspect.isfunction(obj) or inspect.ismethod(obj) or is_cython(obj)
  22. def is_class_method(f):
  23. """Returns whether the given method is a class_method."""
  24. return hasattr(f, "__self__") and f.__self__ is not None
  25. def is_static_method(cls, f_name):
  26. """Returns whether the class has a static method with the given name.
  27. Args:
  28. cls: The Python class (i.e. object of type `type`) to
  29. search for the method in.
  30. f_name: The name of the method to look up in this class
  31. and check whether or not it is static.
  32. """
  33. for base_cls in inspect.getmro(cls):
  34. if f_name in base_cls.__dict__:
  35. return isinstance(base_cls.__dict__[f_name], staticmethod)
  36. return False