[New-bugs-announce] [issue42202] Optimize function annotation

Inada Naoki report at bugs.python.org
Fri Oct 30 02:47:15 EDT 2020


New submission from Inada Naoki <songofacandy at gmail.com>:

Look this example:

code:

```
# code
def foo(x: int, /, y, *, z: float) -> Hoge:
    pass

# dis
 2          12 LOAD_CONST               2 ('int')
            14 LOAD_CONST               3 ('float')
            16 LOAD_CONST               4 ('Hoge')
            18 LOAD_CONST               5 (('x', 'z', 'return'))
            20 BUILD_CONST_KEY_MAP      3
            22 LOAD_CONST               6 (<code object foo at ...>)
            24 LOAD_CONST               7 ('foo')
            26 MAKE_FUNCTION            4 (annotations)
            28 STORE_NAME               2 (foo) 
```

Four `LOAD_CONST` and `BUILD_CONST_KEY_MAP` are used to generate annotation dict. This makes program load slow and eat more memory.

Annotation information can be stored in some compact form. And creating annotation dict can be postponed to when `func.__annotation__` is accessed.

Ideas for the compact form:

1. Tuple.
   In above example, `('int', None, 'float', 'Hoge')` can be used. None means no annotation for the 'y' parameter.

2. Serialize into str or bytes.
   JSON like format can be used, like `x:int,z:float;Hoge`. Compact. But the string/bytes has lower chance to be shared with other constants in same module.

----------
components: Interpreter Core
messages: 379923
nosy: methane
priority: normal
severity: normal
status: open
title: Optimize function annotation
type: resource usage
versions: Python 3.10

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42202>
_______________________________________


More information about the New-bugs-announce mailing list