code
先上代码,今天要解释的是下面这个代码,位置在sqlalchemy/util/langhelpers.py
def public_factory(target, location):
"""Produce a wrapping function for the given cls or classmethod.
Rationale here is so that the __init__ method of the
class can serve as documentation for the function.
"""
if isinstance(target, type):
fn = target.__init__
callable_ = target
doc = "Construct a new :class:`.%s` object. \n\n"\
"This constructor is mirrored as a public API function; see :func:`~%s` "\
"for a full usage and argument description." % (
target.__name__, location, )
else:
fn = callable_ = target
doc = "This function is mirrored; see :func:`~%s` "\
"for a description of arguments." % location
location_name = location.split(".")[-1]
spec = compat.inspect_getfullargspec(fn)
del spec[0][0]
metadata = format_argspec_plus(spec, grouped=False)
metadata['name'] = location_name
code = """\
def %(name)s(%(args)s):
return cls(%(apply_kw)s)
""" % metadata
env = {
'cls': callable_, 'symbol': symbol}
exec(code, env)

本文通过阅读sqlalchemy源码,探讨了使用declarative方式执行executemany的过程,分析了如何创建mapper对象,以及为何使用public_factory函数来暴露类的init方法。此外,文章还揭示了exec函数在动态生成函数对象中的作用,以及在处理code字符串时的细节。
&spm=1001.2101.3001.5002&articleId=54585402&d=1&t=3&u=e80fed6470b343878e8356771f7ac9a3)
609

被折叠的 条评论
为什么被折叠?



