Code Objects / Variable Names

Francis Avila francisgavila at yahoo.com
Wed Jan 7 09:10:07 EST 2004


F. Schaefer wrote in message ...
>PROBLEM:
>
>  How can you know what variables are involved in a code object.
>
>  It is not possible to execute the code object simply into a
>  dictionary and then watch the defined variables. This is
>  because these code objects only contain conditions, that
>  read out variables.

This seems a strange requirement.  Perhaps you could elaborate on what
you're doing and we could suggest alternative approaches?  One *rarely*
needs to pass around raw code objects in Python, and both producing and
executing them is considerably slower than just about any other construct
you could use (not that it matters much).

>EXAMPLE:
>
>  For the following (compiled) condition
>
>          (door == "ajar"   and   alternator == "off") || time > 25
>
>  I need to extract, that the variables 'door', 'alternator' and 'time'
>  are involved.


>>> cobj = compile('(door == "ajar"   and   alternator == "off") or time >
25', '<stdin>', 'exec')
>>> dir(cobj)
['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__str__', 'co_argcount', 'co_cellvars',
'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags',
'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals',
'co_stacksize', 'co_varnames']
>>> cobj.co_names
('door', 'alternator', 'time')

See "Code objects" under "Internal Types" in section 3.2, "Standard Type
Hierarchy," of the Python Language Reference Manual.

>>> import dis #just for fun.
>>> dis.disco(cobj)
  1           0 LOAD_NAME                0 (door)
              3 LOAD_CONST               0 ('ajar')
              6 COMPARE_OP               2 (==)
              9 JUMP_IF_FALSE           10 (to 22)
             12 POP_TOP
             13 LOAD_NAME                1 (alternator)
             16 LOAD_CONST               1 ('off')
             19 COMPARE_OP               2 (==)
        >>   22 JUMP_IF_TRUE            10 (to 35)
             25 POP_TOP
             26 LOAD_NAME                2 (time)
             29 LOAD_CONST               2 (25)
             32 COMPARE_OP               4 (>)
        >>   35 POP_TOP
             36 LOAD_CONST               3 (None)
             39 RETURN_VALUE

--
Francis Avila




More information about the Python-list mailing list