Python: Making Imports Callable


snippets

I wanted to do

import module
module()

I thought this did not exist in Python but Chris Angelico, a Python core dev showed me it existed!

# 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()

Mind boggling!