1

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?

asked May 8, 2020 at 3:17
2
  • You can just call it like writeFunction() Commented May 8, 2020 at 3:19
  • writeFunction is a member function of self.logger Commented May 8, 2020 at 3:21

1 Answer 1

2

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.

answered May 8, 2020 at 3:32
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.