3

Is there a way to create hook in Python that run function like WordPress (PHP) do_action(), apply_filters(), add_action() or add_filter()? Or is there a better Python way to do it?

I have found a good example on how to use observer pattern here: http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Observer

3 Answers 3

3

Perhaps Python signals are what you're looking for. You could certainly implement the Observer pattern that way.

Edit: Here's an example of someone implementing the Observer pattern in Python using signals.

Sign up to request clarification or add additional context in comments.

1 Comment

Christian, thanks for your answer. Any examples would be great.
0

This kind of functionality is usually called Signals or Single dispatcher in the Python community.

Signals are widely used in modern Python projects/libraries to reduce coupling‎, but there's no implementation in the Python standard(the signal module can only catch some os signals, it is not designed for general usage). So different projects may implement their own signal system(e.g PyQt) or use a third-party signal/single dispatcher library(e.g Flask, Django). If you are using a Python framework, it is likely that the framework already had a signal system.

People today usually use PyDispatcher(used by Django), or Blinker(used by Flask). They both have high code quality and good documentation. I prefer Blinker personally.

blinker example:

def subscriber(sender):
    print("Got a signal sent by %r" % sender)

ready = signal('ready')
ready.connect(subscriber)

class Processor:
   def __init__(self, name):
       self.name = name
   def go(self):
       ready = signal('ready')
       ready.send(self)
       print("Processing.")
       complete = signal('complete')
       complete.send(self)
   def __repr__(self):
       return '<Processor %s>' % self.name
processor_a = Processor('a')
processor_a.go()

Output:

Got a signal sent by <Processor a>
Processing.

3 Comments

I don't think it need a library. Example change_me = apply_filter("my_hook", change_me ) and we hook to it add_filter("my_hook", "function_to_call" ). apply_filter will call all the functions that hook 'my_hook' and modify the a value.
@zourbuth Python don't have apply_filter and add_filter. You have to implement it. The implementation is not easy.
Yes I know, it was for example. Does that mean harder to create that than PHP?
0

Checkout Decorators in python, the concept is similar to hooks and filters in WordPress but is more powerful.

You can read more about it here: https://www.geeksforgeeks.org/decorators-in-python/ Decorators in Python

Comments

Your Answer

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.