[Python-ideas] __before__ and __after__ attributes for functions

Antoine Pitrou solipsis at pitrou.net
Thu Jan 23 16:08:36 CET 2014


On Thu, 23 Jan 2014 14:01:50 +0530
"Suresh V." <suresh_vv at yahoo.com> wrote:
> Nicely done :-)
> 
> "foo" may come from a library or something, so rather than a decorator 
> we may have to monkey patch it. Unless there is a nicer solution.
> 
> Will functools be a good place for something like this?

If you think this is interesting (for contract-based programming
perhaps?), I suggest it should first go into a library uploaded in
PyPI, so people can play with it and you refine the API.

Note that you could tweak Chris' implementation to be able to write
instead:

@prepostcall
def foo(x,y,z):
    return x*y+z

@foo.before
def foo_precond(x, y, z):
    print("Pre-call")

@foo.after
def foo_postcond(x, y, y):
    # XXX should the "after" function also receive the return value?
    print("Post-call")


Regards

Antoine.




More information about the Python-ideas mailing list