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?
self) when dispatching to the "real" lambda function? Also, consider using named functions instead of lambdas. For one thing, you can@decoratethem.MenuItemthecheckvariable becomes callable?check=lambda request: request.user.is_superuser. @J_H: this is way to complicated for this approach. Meanwhile @Antony Hatchkins has answered it already - this is what I sought. Thanks all.