Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web.
|
2012-05-03 Python scopes and the CPython bytecode opcodes that they useSince I just got very curious about this, I want to write it down. CPython has four different families of bytecode opcodes for accessing variables, which are used under different circumstances and look in different places. They are:
The first three opcode families look in the obvious places you'd expect. The NAME opcodes are a bit odd and to explain them I need to talk about stack frames briefly. CPython code always runs in the context of a stack frame. Ignoring
implementation details for a moment, stack frames have three namespaces
associated with them; the frame's locals, the
globals, and the builtins. How
the NAME opcodes work is that the
(Technically something like this can also happen with When code is running at the module level, the frame's local namespace is the same as the global (module) namespace, but you can still copy from the builtins namespace to the module namespace. When code is running during class creation, the local namespace is the class to be's namespace and the global namespace is the module namespace: a = 10 print globals() is locals() class A(object): a = a print globals() is locals() This prints (This adds yet another place in CPython that I know of where the left side of an assignment can be in a different namespace than the right side, updating my previous update. One day I will have found them all.) PS: I suspect that this implementation of the NAME opcodes explains
something I noticed a while ago, which is that the C level frame
structure always has a real (I'm not certain if it's ever possible to have a NULL Sidebar: A bonus trivia contest with
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |