0

Is there any way to check if a method is decorated with @staticmethod? I need some function is_static_method(func) with does the following:

class MyClass:
    @staticmethod
    def a(x: int) -> int:
        return x
    
    def b(self, x: int) -> int:
        return x

def c(x: int) -> int:
    return c

m = MyClass()
is_static_method(m.a)  # True
is_static_method(m.b)  # False
is_static_method(c)  # False

So how does the function is_static_method would look like?

DarkMath
  • 1,089
  • 2
  • 15
  • 29
  • You can call the static method like this: `MyClass.a` – Raymond Reddington Aug 18 '20 at 11:54
  • https://stackoverflow.com/questions/8727059/python-check-if-method-is-static – pask Aug 18 '20 at 11:56
  • @ZavenZareyan I know, but that doesn't makes it easier to code the function `is_static_method`. – DarkMath Aug 18 '20 at 11:56
  • Out of interest, why is this something you need to check programmatically? – deceze Aug 18 '20 at 11:56
  • @pask This does not help me, because it is alsy very difficult to access the class in which the method is definded. @deceze I'm writing decorators that do some type checking and they don't work together with `@staticmethod` which is a desireable use case. – DarkMath Aug 18 '20 at 11:59
  • If the duplicate doesn't work for you, you should update the question to detail why exactly it doesn't… – deceze Aug 18 '20 at 12:16
  • You could try to access the source code `inspect.getsource(m.a)` and check if its a static function. – pask Aug 18 '20 at 12:16
  • 1
    @DarkMath So in fact you are asking two questions: (1) how do I get the defining class of a method? (2) how do I identify a staticmethod? For (2), see [this answer](https://stackoverflow.com/a/25959545/984421). – ekhumoro Aug 18 '20 at 12:17

0 Answers0