forloops.py 文件源码

python
阅读 26 收藏 0 点赞 0 评论 0

项目:metapensiero.pj 作者: azazel75 项目源码 文件源码
def For_dict(t, x):
    """Special ``for name in dict(expr)`` statement translation.

    It detects the ``dict()`` call and converts it to:

    .. code:: javascript

      var dict_ = expr;
      for (var name in dict_) {
          if (dict_.hasOwnProperty(name)) {
          // ...
          }
      }
    """
    if (isinstance(x.iter, ast.Call) and
        isinstance(x.iter.func, ast.Name) and
        x.iter.func.id == 'dict' and
        len(x.iter.args) <= 2) and (not x.orelse):

        t.unsupported(x, not isinstance(x.target, ast.Name),
                      "Target must be a name")

        name = x.target
        expr = x.iter.args[0]
        body = x.body

        dict_ = t.new_name()

        # if not ``dict(foo, True)`` filter out inherited values
        if not (len(x.iter.args) == 2 and
            isinstance(x.iter.args[1], ast.NameConstant) and
            x.iter.args[1].value):
            body = [
                    JSIfStatement(
                        JSCall(
                            JSAttribute(JSName(dict_), 'hasOwnProperty'),
                            [JSName(name.id)]
                        ),
                        body, None
                    )
                ]
        # set the incoming py_node for the sourcemap
        loop = JSForeachStatement(
            name.id,
            JSName(dict_),
            body
        )
        loop.py_node = x

        return JSStatements(
            JSVarStatement([dict_], [expr], unmovable=True),
            loop
        )
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号