Mutability of the **kwargs argument in Python

别说谁变了你拦得住时间么 提交于 2019-11-27 07:41:58

问题


Consider a case where I change the kwargs dict inside a method:

def print_arg(**kwargs):
    print kwargs.pop('key')

If I call the method pop_arg with a dictionary like this:

mydict = {'key':'value'}
print_arg(**mydict)

will mydict be changed by this call?

I am also interested in a more detailed explanation of the underlying method calling mechanism that lets mydict change or not.


回答1:


Let's see:

import dis
dis.dis(lambda: print_arg(**{'key': 'value'}))

 

  6           0 LOAD_GLOBAL              0 (print_arg)
              3 BUILD_MAP                1
              6 LOAD_CONST               1 ('value')
              9 LOAD_CONST               2 ('key')
             12 STORE_MAP           
             13 CALL_FUNCTION_KW         0
             16 RETURN_VALUE        

 

Let's find what CALL_FUNCTION_KW does (ceval.c):

    case CALL_FUNCTION_VAR:
    case CALL_FUNCTION_KW:
    case CALL_FUNCTION_VAR_KW:
    {

        // ... 

        x = ext_do_call(func, &sp, flags, na, nk);

        // ...

 

static PyObject *
ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
{
    int nstar = 0;
    PyObject *callargs = NULL;
    PyObject *stararg = NULL;
    PyObject *kwdict = NULL;
    PyObject *result = NULL;

    if (flags & CALL_FLAG_KW) {                     // if ** is involved
        kwdict = EXT_POP(*pp_stack);        // get the dict passed with **      
        if (!PyDict_Check(kwdict)) {
            PyObject *d; 
            d = PyDict_New();                       // make a NEW dict
            if (d == NULL)
                goto ext_call_fail;
            if (PyDict_Update(d, kwdict) != 0) {    // update it with old
                // .. fail ..
                goto ext_call_fail;
            }
            Py_DECREF(kwdict);   
            kwdict = d;              // kwdict is now the new dict
        }
    }

    ....  
    result = PyObject_Call(func, callargs, kwdict);  // call with new dict



回答2:


No, mydict won't be changed. kwargs get unpacked into a new dictionary.

Consider the case where you have:

def print_arg(key=1,**kwargs):
    print key
    print kwargs

print_arg(**{'key':2,'foo':3,'bar':4})

In this case, it's obvious that kwargs is a different dict than you pass in because when it gets unpacked, it's missing the 'key' key.




回答3:


@mgilson's answer is correct. But you should also be aware about the shallow copy.

def print_arg(**kwargs):
    print kwargs.pop('key')
    kwargs['list'].pop()  # will affect the original
    kwargs['dict'].pop('a') #will affect the original

mydict = {'key':'value', 'list':[2,3,4,5] ,'dict': { 'a':1,'b':2 }}
print_arg(**mydict)
print (mydict)  # Output : {'dict': {'b': 2}, 'list': [2, 3, 4], 'key': 'value'}

http://codepad.org/diz38tWF



来源:https://stackoverflow.com/questions/16039280/mutability-of-the-kwargs-argument-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!