Is it always safe to modify the `**kwargs` dictionary?

后端 未结 3 797
刺人心
刺人心 2021-01-31 13:45

Using the Python function syntax def f(**kwargs), in the function a keyword argument dictionary kwargs is created, and dictionaries are mutable, so the

3条回答
  •  走了就别回头了
    2021-01-31 14:31

    For Python-level code, the kwargs dict inside a function will always be a new dict.

    For C extensions, though, watch out. The C API version of kwargs will sometimes pass a dict through directly. In previous versions, it would even pass dict subclasses through directly, leading to the bug (now fixed) where

    '{a}'.format(**collections.defaultdict(int))
    

    would produce '0' instead of raising a KeyError.

    If you ever have to write C extensions, possibly including Cython, don't try to modify the kwargs equivalent, and watch out for dict subclasses on old Python versions.

提交回复
热议问题