3 ms·
I feel like I should understand this but I don't: What names are looked up by name vs. by number in CPython? That is, I think local variables and constants are
by chubot 10y ago
I feel like I should understand this but I don't: What names are looked up by name vs. by number in CPython?
That is, I think local variables and constants are looked up by a small integer which the CPython compiler produces by stack analysis.
But any globals must be looked up by name: functions, classes, modules, global variables. And methods on classes, attributes on classes.
I'd be interested to get clarity on that, and any pointers to relevant code/docs. Is this addressed in the videos? I have looked through the CPython source a lot, and even patched it, but the lookups are a little hard to follow. I've played with the "dis" module and code objects.
EDIT: Answering my own question, it seems like I was confused about the index into co_names, which is a small integer into a list of strings, and then the lookup of that string. So it's a 2-step process?
- xapata 10y agoYou can find out by using dis and checking what is load_fast, load_const or load_global. Attribute lookups are always just that as far as I know. The dot operator has a bunch of paths.
- chubot 10y agoYes thanks, I think that is right... LOAD_FAST and LOAD_CONST are by number, and used for local variables and constants. LOAD_NAME, LOAD_ATTR, and LOAD_GLOBAL are all lookups by name, and are used for everything else: globals, object attributes and methods, modules, etc. It seems that if Python had a static module system, all the lookups by name could be compiled down into lookups by number. https://docs.python.org/3/library/dis.html#python-bytecode-instructions https://docs.python.org/3/library/dis.html#python-bytecode-i...
- xapata 10y agoI'm not clear on the status of PEP 509, but it could/should make LOAD_NAME and LOAD_GLOBAL approach the speed of LOAD_FAST. It'll set a flag on the globals dict (or any dict?) that trips when the dict is mutated. Non-mutated dicts can have fast repeated lookups. https://www.python.org/dev/peps/pep-0509/ https://www.python.org/dev/peps/pep-0509/ Dictionaries got some sweet upgrades for v3.6.