Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use __getattribute__ to run a pre-command hook and continue

I want to set a class state variable before running any class methods every time I call a method; is there a way to use __getattribute__ to run a pre-command hook and continue on to the attr specified? Would I have to use a metaclass, for example?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To do this using __getattribute__ you could do something like this.

import inspect

class A:
    def __getattribute__(self, attrname):
        attr = super().__getattribute__(attrname)
        if inspect.ismethod(attr):
            # Do state stuff
        return attr
        

Instead of using __getattribute__ you could also create a decorator function that does the state stuff you want to do, and add that to each method you want it to apply to.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading