4 ms·
That's not how imports work in python at all. Imports are super imperative operations that first tries to find it in sys.modules, otherwise executes the module
by boxed 2y ago
That's not how imports work in python at all.
Imports are super imperative operations that first tries to find it in sys.modules, otherwise executes the module and puts the resulting dict in sys.modules. Then it grabs the symbols you asked for and shoves all those symbols into the global dict for the module.
It does have to walk the locals and the globals scopes (there are ONLY exactly two scopes in Python!) to find the function, that's true.
- winrid 2y ago> It does have to walk the locals and the globals scopes right, this is what I meant.
- winrid 2y agoAlso I imagine the dict lookup for the module is the slow part? So declaring in local scope just removes a dict lookup? I am by no means a python expert :) I just use it occasionally.
- dfox 2y ago15+ years ago many people would tell you that you should do “from foo import bar” instead of “import foo” to save the overhead inherent in referencing “bar” as “foo.bar”. Well, as almost everything in Python is in the end an dict, the dict implementation is ridiculously optimized (and in some counter-intuitive ways), so if you care about that overhead you probably should not be using (C)Python in the first place. This “everything is a dict” is also a part of why removing GIL is not as straightforward as it would seem.
- winrid 2y agoActually even on a modern CPU that property lookup does add another ~10% penalty. Granted it's like a .1 second difference out of a second runtime for 10m iterations, but it's measurable! Although I wouldn't be using python on those data sizes usually :)
- hansvm 2y agoTIL. Apparently `nonlocal` and closures are implemented with copies, at least for my copy of dis.dis().