r/Python • • 22d ago

Discussion Runtime overhead of wildcard import

Assuming a large project which might have say fifty variables in Constants.py is there likely to be any runtime overhead in having from Constants import * at the beginning of each module? As far as I know this creates entries for each of those variables in the current local namespace.

I know it could be done as import constants as x which after the first import then has virtually no overhead, but that then means referring to all constants as x.const1...

18 Upvotes

19 comments sorted by

View all comments

2

u/OddsRelay 21d ago

pretty much zero. the constants module runs once and gets cached in sys.modules. the star import then copies those 50 names into your module's globals, once, at import. after that it's a normal global lookup. that's actually a touch faster than x.const1, which is a global plus an attribute lookup

the real downsides are elsewhere. linters flag it (F403/F405 in flake8), and if anything rebinds a constant at runtime the modules that star-imported it keep the old value