Search code examples
pythoninstancecallable

Dynamically call staticmethod in Python


I have a python object that has various attrs, one of them is check=None.

class MenuItem:
    check: bool = True

During the __init__() process, it parses it's own attrs and looks if they are callable. If so, it calls the function, and replaces it's instance variable with the result of the function:

    def __init__(self):
        self.request = ...
        if callable(self.check):
            self.check = self.check(self.request)

The purpose is to have subclasses that may replace class attrs by lambda functions:

class MainMenuItem(MenuItem):
    check = lambda request: request.user.is_authenticated

So far, so good. But as the calling of instance methods implicitly adds self as first parameter, I would have to write every lambda (or external function) as lambda self, request: ... - external functions must be def check_superuser(self, request): ... - which IMHO looks bad.

Is there a way in Python to call a function from a method "as staticmethod"? Like

if callable(self.check):
    self.check = staticmethod(self.check)(self.request)

(this obviously doesn't work)

Any hint's welcome. Do I completely think wrong?


Solution

  • Is this what you are looking for?

    class A:
        check: bool = True
        def __init__(self):
            self.request = 'request'
            if callable(self.check):
                self.check = self.__class__.check(self.request)
    
    class B(A):
        check = lambda request: len(request)
    
    b = B()
    print(b.check)
    

    outputs 7