Skip to content

Instantly share code, notes, and snippets.

@bvpav
Last active November 3, 2022 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvpav/c01de00661fe61cbd031c9a61c0ad600 to your computer and use it in GitHub Desktop.
Save bvpav/c01de00661fe61cbd031c9a61c0ad600 to your computer and use it in GitHub Desktop.
Teenage Mutant Ninja Modules

The Scenery

There are 3 modules: m1.py, m2.py and main.py. We can only change the code of main.py and inside it we want to call a function from m1: m1.m1(). However, hidden deep inside the spaghetti codebase m1 is calling m2.m2() on the top level, so it gets executed every time we import m1. And we don't want that

The Problem

How can we import m1 without m2.m2() getting executed and without altering any code inside m1.py and m2.py?

The Solution

We mutate the m2 module inside main before m1 is imported.

import m2
m2.m2() # well.. this shouldn't be happening
def m1():
print('m1')
def m2():
print('m2')
# We don't want m1 to call m2.m2(), so we mutate it
import m2
m2.m2 = lambda *args, **kwargs: None
import m1
m1.m1()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment