PyCodeObject中的co_flags

//Include/code.h

/* Masks for co_flags above */
   #define CO_OPTIMIZED    0x0001
   #define CO_NEWLOCALS    0x0002
   #define CO_VARARGS  0x0004
   #define CO_VARKEYWORDS  0x0008
   #define CO_NESTED       0x0010
   #define CO_GENERATOR    0x0020
   #define CO_NOFREE       0x0040
   #define CO_FUTURE_DIVISION       0x2000
   #define CO_FUTURE_ABSOLUTE_IMPORT 0x4000 
   #define CO_FUTURE_WITH_STATEMENT  0x8000
   #define CO_FUTURE_PRINT_FUNCTION  0x10000
   #define CO_FUTURE_UNICODE_LITERALS 0x20000
  • CO_OPTIMIZED:
  • CO_NEWLOCALS:
  • CO_VARARGS:是否使用了扩展位置参数
  • CO_VARKEYWORDS:是否使用了扩展关键字参数
  • CO_NESTED:
  • CO_GENERATOR:是否是一个生成器
  • CO_NOFREE:是否有free或者cell变量(闭包)
>>> import dis
>>> def f():
...     print("hello")
...
>>> dis.show_code(f)
Name:              f
Filename:          <stdin>
Argument count:    0
Kw-only arguments: 0
Number of locals:  0
Stack size:        2
Flags:             OPTIMIZED, NEWLOCALS, NOFREE
Constants:
   0: None
   1: 'hello'
Names:
   0: print
>>>
>>> def g(a,b,*args):
...     print("hello")
...
>>> dis.show_code(g)
Name:              g
Filename:          <stdin>
Argument count:    2
Kw-only arguments: 0
Number of locals:  3
Stack size:        2
Flags:             OPTIMIZED, NEWLOCALS, VARARGS, NOFREE
Constants:
   0: None
   1: 'hello'
Names:
   0: print
Variable names:
   0: a
   1: b
   2: args
>>>
>>> def h(a,b):
...     va = "hello"
...     def k():
...             print(va)
...     return k
...
>>> dis.show_code(h)
Name:              h
Filename:          <stdin>
Argument count:    2
Kw-only arguments: 0
Number of locals:  3
Stack size:        3
Flags:             OPTIMIZED, NEWLOCALS
Constants:
   0: None
   1: 'hello'
   2: <code object k at 0x0074C4D0, file "<stdin>", line 3>
   3: 'h.<locals>.k'
Variable names:
   0: a
   1: b
   2: k
Cell variables:
   0: va
>>>