How does one monkey patch a function in python?

It may help to think of how Python namespaces work: they’re essentially dictionaries. So when you do this:

from a_package.baz import do_something_expensive
do_something_expensive = lambda: 'Something really cheap.'

think of it like this:

do_something_expensive = a_package.baz['do_something_expensive']
do_something_expensive = lambda: 'Something really cheap.'

Hopefully you can realize why this doesn’t work then 🙂 Once you import a name into a namespace, the value of the name in the namespace you imported from is irrelevant. You’re only modifying the value of do_something_expensive in the local module’s namespace, or in a_package.baz’s namespace, above. But because bar imports do_something_expensive directly, rather than referencing it from the module namespace, you need to write to its namespace:

import bar
bar.do_something_expensive = lambda: 'Something really cheap.'

Leave a Comment