zourbuth
zourbuth

Reputation: 908

Create hooks in Python like WordPress?

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

Upvotes: 3

Views: 1522

Answers (3)

Santosh S Kumar
Santosh S Kumar

Reputation: 479

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

Upvotes: 0

Leonardo.Z
Leonardo.Z

Reputation: 9801

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.

Upvotes: 0

Christian Ternus
Christian Ternus

Reputation: 8492

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.

Upvotes: 3

Related Questions