简体   繁体   中英

Explain locals() and exactly how it works

Could someone please explain how this little piece of code works?

info = {}
info.update(locals())
info.pop('self', None)
info.pop('info', None)

I am assuming, and please correct me if I am wrong, but it gets all the variables in the current function and puts them in the dict and removes self and the dict it got put in, correct? Is there anything other than self and the dict I might not want going into there?

Would there be anything wrong with just JSON serializing that dict and posting it?

This probably comes from the Django template and the locals trick . The idea is to populate a number of variables inside a function, and use locals() to pass them on to a template. It saves the effort of creating a new dictionary with all those variables.

Specifically, your code creates a dictionary of all the local variables and removes self (the class object parameter) and info (the variable that was just created). All other local variables are returned.

You could then JSON serialize the data, as long as the data can be serialized. DateTime variables must be converted to a string first, for example.

The code creates a new dictionary called 'info' and assigns all of your local python variables to it. NOTE: These are pointers to the same objects in your local environment, so that if you modify a list or dictionary in info it will be changed in your environment as well (this may or may not be the desired behavior).

locals() Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

info.pop('self', None) and info.pop('info', None) will remove 'self' and 'info', respectively, from your new info dictionary. If they are not present, they return None . Note that info.pop('self') would return a KeyError if 'self' was not in the dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM