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
)
评论列表
文章目录