3

Given a module mymodule with an __init__.py file how can I define a functions of mymodule from another function within that file?

__init__.py code outline:

def a():
    THISMODULE.__dict__["b"] = lambda: print("this is not weird")

a()
b() # Expect "this is not weird" output

mymodule comes as a replacement for anothermodule and I want to make the code change as simple as replacing import anothermodule as thething with import mymodule as thething. Since I don't implement all the functions of anothermodule just yet, I would like to send the user a notification about it instead of crashing with "not defined".

y.selivonchyk
  • 7,824
  • 6
  • 47
  • 71

1 Answers1

1

__name__ is a module attribute set by the import machinery, which evaluates to the name of the current module. Adding this to the top of your file:

import sys

THISMODULE = sys.modules[__name__]

And the rest of what you already have should work correctly.

wim
  • 302,178
  • 90
  • 548
  • 690