Speed up "from X import A; from X import B; from X import C; ..." #145
Replies: 6 comments 1 reply
-
Forgetting edge cases for a moment (I assume there are many). My initial thought was a cache that holds only the previously loaded module, this is the dumbest implementation (avoiding the lookup in sys.modules even). |
Beta Was this translation helpful? Give feedback.
-
That would seem like a good idea. I haven't actually looked at the code to try to understand what's slowing this down though, there may be a reason there explaining why this is difficult. (Another reason may not be obvious from the code: it's possible that there's other (non-import) code between the first and the second import that might invalidate the cache.) |
Beta Was this translation helpful? Give feedback.
-
I'm just going to note a 3rd style I've seen in some larger projects (it may well a variant on from X import (
A,
B,
C,
...,
Z
) |
Beta Was this translation helpful? Give feedback.
-
@stuaxo this variant is in my experience often used to make the linters happy ... and |
Beta Was this translation helpful? Give feedback.
-
There is no difference in execution speed between
and
(at least assuming we're executing unmarshalled bytecode -- it is the same, as you can tell by experimenting with dis.py.) |
Beta Was this translation helpful? Give feedback.
-
"someone remarked that X is much faster than Y" is a bit vague. Any actual numbers? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Over in Pyston-land someone remarked that this:
is much faster than
We can't easily rewrite the latter as the former, because in edge cases the semantics are different (though maybe Black could take the liberty to do it anyway...?). But we could try to make the latter execute faster -- in theory everything needed is just in
sys.modules['X']
, though in practice there appear to be some caches that are reset betweenfrom X import
statements but that are kept around betweenA, B, ...., Z
. Maybe there's some wiggle room or a quicker way to check for cache invalidation (which is probably rare).Note that
X
could well be a package path likefoo.bar.baz
. Also, ifX
is a package, thenA, B, ..., Z
could be submodules; but ifX
is a module,A...Z
must be variables (or functions, classes, etc.) defined inX
.Beta Was this translation helpful? Give feedback.
All reactions