为什么从compile(my_func)和my_func .__ code__获得不同的代码对象?

时间:2019-04-05 21:54:42

标签: python python-3.x

首先,我在CodeReview上提出了一个问题:Automating Initial Server Setup with Ubuntu 18.04。但是,然后,我尝试了另一种方法,并通过compile()my_func.__code__获得了不同的代码对象字段值。他们不应该一样吗?如果没有,我在哪里可以了解compile__code__之间的区别?

# Function for exploring
def my_add(a,b):
    first = a
    second = b

    return first + second

# Print all code object fields
def print_co_obj_fields(code_obj):
    # Iterating through all instance attributes
    # and calling all having the 'co_' prefix
    for name in dir(code_obj):
        if name.startswith('co_'):
            co_field = getattr(code_obj, name)
            print(f'{name:<20} = {co_field}')

### Making the code object for 'my_add' function
# First approach
code_obj_compile = compile('my_add', os.path.realpath(__file__), 'exec')

# Second approach
code_obj_dunder = my_add.__code__

print("=" * 60)
print("code_obj_compile output")
print("=" * 60)
print_co_obj_fields(code_obj_compile)

print("=" * 60)
print("code_obj_dunder output")
print("=" * 60)

print_co_obj_fields(code_obj_dunder)

输出-部分不同(co_codeco_argcount等):

============================================================
code_obj_compile output
============================================================
co_argcount          = 0 
co_cellvars          = ()
co_code              = b'e\x00\x01\x00d\x00S\x00'
co_consts            = (None,)
co_filename          = /home/minimax/learning_python/oop/source.py
co_firstlineno       = 1 
co_flags             = 64
co_freevars          = ()
co_kwonlyargcount    = 0 
co_lnotab            = b'' 
co_name              = <module>
co_names             = ('my_add',)
co_nlocals           = 0 
co_stacksize         = 1 
co_varnames          = ()
============================================================
code_obj_dunder output
============================================================
co_argcount          = 2
co_cellvars          = ()
co_code              = b'|\x00}\x02|\x01}\x03|\x02|\x03\x17\x00S\x00'
co_consts            = (None,)
co_filename          = ./source.py
co_firstlineno       = 21
co_flags             = 67
co_freevars          = ()
co_kwonlyargcount    = 0 
co_lnotab            = b'\x00\x01\x04\x01\x04\x02'
co_name              = my_add
co_names             = ()
co_nlocals           = 4 
co_stacksize         = 2 
co_varnames          = ('a', 'b', 'first', 'second')

0 个答案:

没有答案