What exactly is a python variable?

Steve D'Aprano steve+python at pearwood.info
Thu Nov 17 07:20:34 EST 2016


On Thu, 17 Nov 2016 10:37 pm, BartC wrote:

> Try:
> 
>   import dis
> 
>   def fn():
>   |   global x
>   |   x=10
> 
>   dis.dis(fn)
> 
> (I don't know how to disassemble code outside a function, not from
> inside the same program. Outside it might be: 'python -m dis file.py')


You can use the byte-code compiler to compile the code first:


For an expression, you can use:

code = compile("x + 1", "", "eval")


The middle argument, shown here as an empty string "", is used for an
optional string identifying the source of the code. E.g. a file name.

The third argument, here shown as "eval", determines the compilation mode.
The eval() function can only evaluate a single expression, so the name of
the mode is the same.

For a single statement, as seen by the interactive interpreter, use:

code = compile("result = x + 1", "", "single")


For multiple statements (as in a module), or a single statement *not* in the
interactive interpreter, use:

code = compile("result = x + 1", "", "exec")

code = compile("""
x = 999
result = x + 1
print(result)
""", "", "exec")

Then once you have your code object, you can disassemble it:

dis.dis(code)

or exec/eval it:

exec(code)
eval(code)  # only if the compilation mode was "eval"


In the most recent versions of Python, dis.dis() will also accept a string:

py> dis.dis('y = x + 1')
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (1)
              6 BINARY_ADD
              7 STORE_NAME               1 (y)
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list