0

I wanted to have the option to pass my arguments to a function in a concise manner. So instead of passing all arguments directly, I include them as parameters function definiton and pass all such arguments as Common_Args. Then I do the following

       for key, value in Common_args.items():
            if key in locals():
                globals()[key] = value

Here is the problem. Even though the control goes inside the if condition(checked with debugger), the parameter's value do not change, but it should, right? Guides have confirmed that this should work, and if I run single statements in my debugger, the value of the variable does change.


My function definition in more detail is

def plotLFPData1Channel(plotHandles=None, channelString="", stimulus_list=None, folderName=None, analysisType=None,
                        timeVals=None, plotColor=None, blRange=None, stRange=None, referenceChannelString=None,
                        badTrialNameStr=None, useCommonBadTrialsFlag=None ,*,Common_args=None):
    # first we have to unpack common args
    if Common_args is not None:
        for key, value in Common_args.items():
            if key in locals():
                globals()[key] = value

and I call the function like so

result=plotLFPData1Channel(plotHandles=ax.flatten(), channelString=analogChannelString, stimulus_list=stimValsToUse,analysisType=analysisType,Common_args=commonArgs)

with commonArgs={"folderName":folderName , "timeVals":timeVals, "plotColor":plotColor, "blRange":blRange, "stRange":stRange, "referenceChannelString":referenceChannelString, "badTrialNameStr":badTrialNameStr, "useCommonBadTrialsFlag":useCommonBadTrialsFlag}

  • You are creating/modifying a *global* variable with the same name as the local one, but the local one keeps its value, so I don't see anything surprising here. The whole thing, though, is a bit... strange. Why not simply call your function with `plot...(**commonArgs)`?? – Thierry Lathuille Jul 19 '22 at 11:05
  • Even with locals()[key]=value there is no change. How do I use **kwargs to achieve this? Basically common Args are the arguments that generally don't change between runs, so I don't want the function call to look big . – Sudhanshu Bharadwaj Jul 19 '22 at 11:17
  • [The doc for locals](https://docs.python.org/3/library/functions.html#locals) explicitely states:"The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter." - so don't try that, it doesn't work. For the rest, https://stackoverflow.com/questions/1769403/what-is-the-purpose-and-use-of-kwargs, https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters ... – Thierry Lathuille Jul 19 '22 at 11:20

0 Answers0