sqlalchemy源码阅读(1)

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

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)
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值