Ge

Generic dual-paradigm hooking mechanism

Hacker News

Generic dual-paradigm hooking mechanism

Hi HN ! I am Alex, a tech enthusiast, I'm excited to show you a major iteration of my library for performing hooking in Python. I redesigned the whole project because it didn't not cover all my needs. I'm happy with the current iteration that I've written tests for and look forward to spending weeks and months using it in my projects. Python has a concept called Decorator [1] which is a function that takes another function and extends the behavior. In the following script, the timeit decorator is used to measure the execution time of the heavy_computation function: import time from functools import wraps def timeit(text): def deco(target): @wraps(target) def wrapper(*args, **kwargs): # execute and measure the target run time start_time = time.perf_counter() result = target(*args, **kwargs) total_time = time.perf_counter() - start_time # print elapsed time print(text.format(total=total_time)) return result return wrapper return deco @timeit(text="Done in {total:.3f} seconds !") def heavy_computation(a, b): time.sleep(2) # doing some heavy computation ! return a*b if __name__ == "__main__": result = heavy_computation(6, 9) print("Result:", result) Output: $ python -m test Done in 2.001 seconds ! Result: 54 Besides benchmarking, there are many other cool things that can be done with the Python decorator. For example, the Flask [2] and Bottle [3] web frameworks implement routing with decorators. While decorators are cool, it's worth mentioning that using a decorator is much more intuitive than writing its code. The code is entirely different depending on whether the decorator takes arguments or not. The following code performs the same task as the previous one, except it is more clear and intuitive: import time from hooking import on_enter def timeit(context, *args, **kwargs): # execute and measure the target run time start_time = time.perf_counter() context.result = context.target(*args, **kwargs) total_time = time.perf_counter() - start_time # print elapsed time text = context.config.get("text") # get 'text' from config data print(text.format(total=total_time)) context.target = None @on_enter(timeit, text="Done in {total:.3f} seconds !") def heavy_computation(a, b): time.sleep(2) # doing some heavy computation ! return a*b if __name__ == "__main__": result = heavy_computation(6, 9) print("Result:", result) Output: $ python -m test Done in 2.001 seconds ! Result: 54 The Hooking library used in the code above uses Python decorators to wrap, augment, and override functions and methods. It is a generic hooking [4] mechanism which is perfect for creating a plug-in mechanism for a project, performing benchmarking and debugging, implementing routing in a web framework, et cetera. Also, it is a dual paradigm hooking mechanism since it supports tight and loose coupling [5]. The previous code uses the tight coupling paradigm, that's why the timeit hook is directly tied to the target function. In loose coupling paradigm, targets functions and methods are tagged using a decorator, and hooks are bound to these tags. So when a target is called, the bound hooks are executed upstream or downstream. This paradigm is served by a class designed for pragmatic access via class methods [6]. This class can be easily subclassed to group tags by theme for example. Here is an example of the loose coupling paradigm: import time from hooking import H @H.tag def heavy_computation(a, b): print("heavy computation...") time.sleep(2) # doing some heavy computation ! return a*b def upstream_hook(context, *args, **kwargs): print("upstream hook...") def downstream_hook(context, *args, **kwargs): print("downstream hook...") # bind upstream_hook and downstream_hook to the "heavy_computation" tag H.wrap("heavy_computation", upstream_hook, downstream_hook) if __name__ == "__main__": result = heavy_computation(6, 9) print("Result:", result) Output: $ python -m test upstream hook... heavy computation... downstream hook... Result: 54 This library is available on PyPI and you can play with the examples [7] which are on the project's README. I would like to know what you think [8] of this project. Your questions, suggestions and criticisms are welcome ! [1] https://peps.python.org/pep-0318/ [2] https://hackersandslackers.com/flask-routes/ [3] http://bottlepy.org/docs/dev/ [4] https://en.wikipedia.org/wiki/Hooking [5] https://en.wikipedia.org/wiki/Coupling_(computer_programming... [6] https://stackoverflow.com/a/38276 [7] https://github.com/pyrustic/hooking#examples [8] http://sl4.org/crocker.html

Share card

Actual performance

4points
Did not reach leaderboard

Launch Intel predictions

Analyze your own launch →
Indie HackersFits the IH revenue-focused audience · Strong signals: supports, para · Missing: reddit linkedin, podcasting, created
96%96% predicted probability of success on Indie Hackers, based on ML models trained on real launch data.
best fitHighest predicted score across all platforms for this description.
Product HuntUnlikely to reach the leaderboard · Strong signals: slack, computer, context · Missing: mac, agents, macos
49%49% predicted probability of success on Product Hunt, based on ML models trained on real launch data.
TrustMRRLess likely to generate early MRR · Strong signals: month, para · Missing: mobile apps, ios, personal
44%44% predicted probability of success on TrustMRR, based on ML models trained on real launch data.
Hacker NewsMay not resonate with HN audience · Strong signals: excited, ide, io · Missing: https docs, just released, exist
40%40% predicted probability of success on Hacker News, based on ML models trained on real launch data.
nativeThis product was originally launched on this platform.
AppSumoMay struggle as an AppSumo deal · Strong signals: intuitive · Missing: plus, platform, reviews
35%35% predicted probability of success on AppSumo, based on ML models trained on real launch data.
Acquire.comPre-revenue stage for this audience · Missing: arr, mrr, revenue
17%17% predicted probability of success on Acquire.com, based on ML models trained on real launch data.
BetaListMay not resonate with beta-testers · Missing: web3, chat, crypto
0%0% predicted probability of success on BetaList, based on ML models trained on real launch data.

Correct prediction on native model

Similar products

I
I made a dual-bootable NixBSD (NixOS and FreeBSD) image46%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

I made a dual-bootable NixBSD (NixOS and FreeBSD) image

Hacker News9
su
sudo_pair – dual control for sudo56%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

sudo_pair – dual control for sudo

Hacker News32
Du
Dual Subtitles for Netflix on Chrome and Firefox (CJK Supported)56%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

Dual Subtitles for Netflix on Chrome and Firefox (CJK Supported)

Hacker News2
Fi
First ever MQTT and XMPP dual-protocol server55%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

First ever MQTT and XMPP dual-protocol server

Hacker News8
Dual Shades
Dual Shades33%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

Keep your subject in color, fade the background to B&W

Product Hunt+116Design Tools
A
A Skeletal Animation System in your browser using dual quaternions48%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

A Skeletal Animation System in your browser using dual quaternions

Hacker News3
Du
DuoRAG – A dual stack RAG that self-evolves47%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

DuoRAG – A dual stack RAG that self-evolves

Hacker News3
We
WeatherRelay, our IoT dual-band weather sensor receiver63%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

WeatherRelay, our IoT dual-band weather sensor receiver

Hacker News3
We
We built the smallest dual-band aircraft tracker76%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

We built the smallest dual-band aircraft tracker

Hacker News95
NS7 Thermal Dual-Vision Dashcam
NS7 Thermal Dual-Vision Dashcam55%Launch Intel prediction score: how likely this product is to succeed on its source platform, based on its name, tagline, and description.

A 24/7 All-Seeing Co-Pilot

Product Hunt+13