Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

python - semantics of __module__

I'm dynamically defining functions in a module and then updating the module's __all__ and the function's __name__ attribute to match the name it will have inside the module. I was wondering if it is a good idea to update the function's __module__ attribute as well to point to the module the function will reside. The docs say __module__ is:

The name of the module the function was defined in, or None if unavailable.

The code that creates the function resides in a different module which is pretty much unrelated to the module where the function resides. There is no reference to the function in this module.

I've done some poking around on the mailing list but I'm a bit confused as to what the semantics of __module__ are and if I should set it to None or the module that the function resides or the module where the code resides that created the function. Gonna leave it be for now but am interested to see if anyone knows the answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wouldn't do it. Importing functions from one module to another is a common occurrence. The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script. I don't see that it makes much difference whether the definition is via static code or dynamically: If someone wants to read your function's source code, they should look in the module that dynamically creates it.

You could take a look at PEP 3130. Although it was rejected, it might give you more insight into the purpose of __module__ than the single-sentence description found everywhere else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...