Python: Making Imports Callable


software engineering

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!

Written by

Abdur-Rahmaan Janhangeer

Chef

Python author of 9+ years having worked for Python companies around the world

Suggested Posts

Python Generators: The In-depth Article You've Always Wanted

Table of contents Why were Python generators introduced? How do Python Generators differ from norma...

Read article

The Zen Of Python: A Most In Depth Article

Note: I wrote a quite complete article on the Zen but for some reason it went down in seo history. I...

Read article

Notes of Get your resources faster, with importlib.resources by Barry Warsaw

Talk notes thepkg/ # is a package since has __init__.py __init__.py a.py b.py data/ ...

Read article
Free Flask Course