Skip to content
Advertisement

Python Trigger a function when a function is called

So, I am making a desktop app with PyQt6. I have a stylesheet and I want it to update every time I add something to it. Stylesheet is an array and I have multiple functions adding things to it:

JavaScript

Now, I want to update the stylesheet every time I call one of these functions (or a function in the class as a whole) by calling another function that updates it. But I don’t want to add it manually to every function. Is there a better way of doing this?

JavaScript

Advertisement

Answer

Simple solution: Use function composition.

Instead of calling self.stylesheet.append you could make a helper method, that will call self.stylesheet.append and also call update_stylesheet

JavaScript

More complex solution: Function decorators.

In this case we would make some assertions about what methods the class has present. Using the decorator, we can call the normal method and have extra logic run afterwards. Using the decorator we can hijack a reference to self and call the update_stylesheet method this way.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement