[Python-ideas] making a module callable
Ethan Furman
ethan at stoneleaf.us
Wed Nov 20 21:23:14 CET 2013
On 11/20/2013 12:14 PM, Eric Snow wrote:
>
> Sticking something into sys.modules to replace the currently executing
> module is indeed a hack. The import system accommodates this not by
> design (unless someone is willing to come forward and admit guilt
> <wink>) but mostly as an incidental implementation artifact of the
> import machinery from many releases ago. [1]
Actually, it is intentional. An excerpt from https://mail.python.org/pipermail/python-ideas/2012-May/014969.html
> There is actually a hack that is occasionally used and recommended:
> a module can define a class with the desired functionality, and then
> at the end, replace itself in sys.modules with an instance of that
> class (or with the class, if you insist, but that's generally less
> useful). E.g.:
>
> # module foo.py
>
> import sys
>
> class Foo:
> def funct1(self, <args>): <code>
> def funct2(self, <args>): <code>
>
> sys.modules[__name__] = Foo()
>
> This works because the import machinery is actively enabling this
> hack, and as its final step pulls the actual module out of
> sys.modules, after loading it. (This is no accident. The hack was
> proposed long ago and we decided we liked enough to support it in
> the import machinery.)
--
~Ethan~
More information about the Python-ideas
mailing list