On Fri, Oct 22, 2021 at 3:49 AM Abdur-Rahmaan Janhangeer
<[email protected]> wrote:
>
> Greetings list,
>
> Let's say i import module1
>
>
> import module1
>
> can we do
>
>
> module1()
>
> straight out of the box?
>
Yes! It takes a (very) little bit of work though. You have to replace
your module's class with a subclass that has a __call__ method:
# importme.py
import sys, types
class Module(types.ModuleType):
def __call__(self):
print("You called me!")
sys.modules[__name__].__class__ = Module
# other_file.py
import importme
importme()
Other than this change, your module should behave perfectly normally
in every way. Regular attributes, top-level functions, etc, should be
exactly as you'd expect. All you do is add an extra class-level
dunder.
ChrisA
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/CQFFYMUVQP3BK5NT63GO5QOLOQK434IX/
Code of Conduct: http://python.org/psf/codeofconduct/