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

Is there a way to do some pre-process/post-process every time I call a function in python

I have a number of calls I need to make to functions imported from a package (the package is a shared object file). However I need to do some pre-process / post – process step every time I make a call to a function from this package. Something like this:

import xyz

prepare()
xyz.foo(<args>)
done()

prepare()
xyz.bar(<args>)
done()

prepare()
xyz.foobar()
done()

Is there some way I can ask python to always invoke prepare() before I call a function from xyz module. And also to invoke done() after the call is complete?
Writing prepare and done through my whole code seems redundant and messy. Appreciate your help!

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

>Solution :

This is typically done with a context manager.

import contextlib

@contextlib.contextmanager
def with_preparation():
    prepare()
    yield
    done()

with preparation():
    xyz.foo(<args>)

with preparation():
    xyz.bar(<args>)

with preparation():
    xyz.foobar()

preparation defines a function that returns a context manager. The with statement works by invoking the context manager’s __enter__ method, then executing the body, then ensuring that the context manager’s __exit__ method is invoked before moving on (whether due to an exception being raised or the body completing normally).

contextlib.contextmanager provides a simple way to define a context manager using a generator function, rather than making you define a class with explicit __enter__ and __exit__ methods.

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