Greetings list, Let's say i import module1 import module1 can we do module1() straight out of the box? If not i propose something like if __name__ == '__main__': __file__.callable = True Kind Regards, Abdur-Rahmaan Janhangeer about <https://compileralchemy.github.io/> | blog <https://www.pythonkitchen.com> github <https://github.com/Abdur-RahmaanJ> Mauritius
Sorry not if name == main, basically if module is being imported: __file__.callable = True Kind Regards, Abdur-Rahmaan Janhangeer about <https://compileralchemy.github.io/> | blog <https://www.pythonkitchen.com> github <https://github.com/Abdur-RahmaanJ> Mauritius
On Fri, Oct 22, 2021 at 3:49 AM Abdur-Rahmaan Janhangeer <arj.python@gmail.com> 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
Just amazing!!! Noted it down https://www.pythonkitchen.com/python-making-imports-callable/ Kind Regards, Abdur-Rahmaan Janhangeer about <https://compileralchemy.github.io/> | blog <https://www.pythonkitchen.com> github <https://github.com/Abdur-RahmaanJ> Mauritius
participants (2)
-
Abdur-Rahmaan Janhangeer
-
Chris Angelico