Reputation: 2945
I am reading Python source codes, and I find this code in Python-2.7.10/Lib/multiprocessing/managers.py.
I just wondering what's the usage of % (meth, meth) in dic
here, because I think %
will first associate the string, and exec
always returns None
def MakeProxyType(name, exposed, _cache={}):
'''
Return an proxy type whose methods are given by `exposed`
'''
exposed = tuple(exposed)
try:
return _cache[(name, exposed)]
except KeyError:
pass
dic = {}
for meth in exposed:
exec '''def %s(self, *args, **kwds):
return self._callmethod(%r, args, kwds)''' % (meth, meth) in dic
ProxyType = type(name, (BaseProxy,), dic)
ProxyType._exposed_ = exposed
_cache[(name, exposed)] = ProxyType
return ProxyType
Upvotes: 0
Views: 37
Reputation: 169298
You can rephrase it as
code = '''def %s(self, *args, **kwds):
return self._callmethod(%r, args, kwds)''' % (meth, meth)
exec code in dic
which in turn uses the exec ... in ...
form:
In all cases, if the optional parts [
in ...
] are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are given as globals and locals, the code will be executed as if it were embedded in a class definition.
That is, the code will be executed within the to-be-created proxy type's class variable dictionary.
Upvotes: 3