Adding __future__ imports to every module at runtime

Hi,

I’ve been looking around a while trying to find a way to activate specific __future__ imports to all files used by my app at runtime, without having to modify my files.

My old usecase was going from 2-to-3 on various codebases faster, but currently it is to test out the effect of from __future__ import annotations. Generally it will just be for testing and experimenting quickly, but I could also imagine adding it for a specific application repo that only have very specific ways of being run, for example in a container.

I don’t think there is any CLI flag or environment variable to help me out, but would this thing be possible to do by using a custom import loader?

Yes, it is possible to do. For example, using the simplest example my ideas package (see Improving function as a keyword — ideas 0.0.17 documentation), you’d simply need something like:

def transform_source(source, **kwargs):
    return "from __future__ import annotations\n" + source

Since ideas does more than you’d need to, you could probably extract the relevant parts and include them in a few simple additional functions in your own code.

1 Like

Thanks @aroberge ! That’s wonderful, simpler than I’d imagined!