elijah.run

Dynamic Dispatch in Python

đŸĻ Hey want tO see a nEat PYtHoN triCK?

def f(name: str):
    print("hiya {}".format(name))

locals()["f"]("Spongebob")

🐮 Oh cool, does that use the string "f" to find--

đŸĻ DoEs It FiNd ThE fUnCtIoN "f" aNd CaLl iT?? yEaH It DoEs.

$ python script.py
hiya Spongebob

🐮 Oh that's neat. I didn't know you could do that with Python--

đŸĻ whaTEveR i dON't cArE wHaT YOU tHinK.

🐮 You asked me --

đŸĻ I sAiD sHuT uP. i'M dOiNg HoT gIrL sHiT.

🐮 Are you ok? You're yelling a lot about Python again--

# shut up

def test_patrick(context: TestContext):
    # do thing

def test_crabs(context: TestContext):
    # do other thing

context = TestContext()
tests = []
for t in locals():
    if t.startswith("test_"):
        tests.append(t)
for test in tests:
    test(context)

🐮 Oh so you could...

đŸĻ ...

🐮 Are you going to interrupt me?

đŸĻ Not yet.

🐮 Ok... you could search your scope and find a bunch of functions with a name and common interface--

đŸĻ AND CALL THEM! DYNAMIC DISPATCH!!

🐮 That's nice.

đŸĻ YEAH IT IS COOL!

Tags: #python