Nikita Tchayka Nikita Tchayka - 3 months ago 7
Python Question

Is it possible to make all modules import a module implicitly?

I love the type hinting from Python 3, but I'm really tired of writing

from typing import *
in all the modules that I write.

Is it possible to wrap my app in a module, or anything, and implicitly import the module in all of my app modules?

Answer

You could hijack the builtins module and put what you need there. That would make the code harder to maintain, as it would be harder to figure where these globals are coming from, or if they are accidentally clobbered. To be clear, it's possible, but I recommend not doing this.

The main module would need to do something like this at the top. If it's not the first thing to happen in the program then other modules won't work properly. Import order shouldn't make a difference, so if someone messes with this and it break the program then it will be hard to figure out why.

import typing # I assume you meant typing, not types
import builtins
vars(builtins).update({k: getattr(typing, k) for k in typing.__all__})

# Any module could do this without having to import anything
def f(x: T) -> T:
    return x