Is there a way to pass a custom function as a parameter in a class method and have an object call that function? I'm writing a custom logger and would like to do something like this
class Logger:
def __init__(self, ...):
self.logger = logging.getLogger('name')
...
def write(self, writeFunction, message):
self.logger.writeFunction(message) # something like this
self.logger.call(writeFunction, args=[message]) # or something like this in other languages
where writeFunction is something like info(), debug(), etc (I know the example above isn't allowed in python)
Trying to avoid having to pass a log level as a parameter and doing a bunch of if statements to determine which logging function to call
UPDATE: I found that the loggers have a method log() that does what I'm looking for, but what about other objects in general?
1 Answer 1
Yes, you can absolutely pass a callable as a parameter. It would look more like this (adding type annotations to help clarify the usage):
def write(self, write_function: Callable[[str], None], message: str):
write_function(message)
Then to call this function you'd do:
write(self.logger.info, "my message")
The write function would just call whatever function you passed as the parameter (in this case self.logger.info) with the given message. Adding type annotations is useful here because it's easy to get confused about what types are expected in which context, but mypy will help you keep it all straight -- in this case the type annotation tells us that whatever function we pass to write will be called with a single str argument.
writeFunction()