Unlike locals() , globals() documented as updatable (since it returns __dict__ current module). I usually use vars() in the global scope - the same thing in this case - to reduce code duplication:
for v,ar in ('a',x),('b',y): vars()[v]=fn(ar)
For some other objects (e.g. current class / instance), __dict__ members __dict__ also available as syntax variables:
class C: def __init__(self,a,b): vars(self).update(v,locals()[v] for v in 'a','b') do_something(self.a)
Please note, however, that:
- These “syntax links” reduce the code's resiliency — since they are harder to find — and therefore code checking tools like
pylint will probably be broken. - the need to use variables in this way usually means trying to use a region like a
dict : such variables tend to be “homogeneous” in some way, asking them to be used in array operations and, therefore, should probably be combined into a dedicated container instead.
source share