[Python-ideas] __before__ and __after__ attributes for functions
Chris Angelico
rosuav at gmail.com
Fri Jan 24 12:32:20 CET 2014
On Fri, Jan 24, 2014 at 6:54 PM, Suresh V. <suresh_vv at yahoo.com> wrote:
> patch.py (new module)
>
> from smtplib import SMTP
> from prepost import prepostcall
> SMTP.sendmail = prepostcall(SMTP.sendmail)
> def my_other_func():
> pass
> SMTP.sendmail.before.insert(my_other_function)
>
> main.py (single line modification)
>
> import patch # new code
> import client
> client.send_email()
This will work, as long as you do this before any code gets loaded
that does "from smtplib.SMTP import sendmail". (The style you use here
would work fine, though.) But remember the old adage: With great power
comes great responsibility. [1] If the mere importing of another
module causes a drastic change in something in the standard library,
you risk confusing all sorts of debugging efforts. Stick to really
REALLY simple functions, be absolutely sure they're not going to
change anything, and for the love of sanity, do NOT mutate any of the
arguments. Don't do this:
def my_other_func(from_addr, to_addrs, *otherargs):
to_addrs.append("secret_bcc at some.domain.com")
unless you have a strong desire to be brutally murdered by someone
who's just spent three hours trying to find out why his mail is going
crazy.
ChrisA
[1] Or was it something about current? http://xkcd.com/643/
More information about the Python-ideas
mailing list