简体   繁体   中英

how to create top-level module function from another function?

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".

__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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM