javascript - 如何使 Transcrypt 编译为对象而不是字典?

标签 javascript python dictionary object transcrypt

我正在尝试使用 Transcrypt 的 fetch API。

来源:

headers = {
    "Access-Control-Request-Method": "GET",
    "Access-Control-Request-Headers": "origin, x-requested-with",
    "Origin": "https://bar.com/"
}

args = {
    "method":"OPTIONS",
    "headers":headers
}

fetch("https://foo.com/",args).then(
    lambda response: print(response),
    lambda err: print(err)
)

编译为:

var headers = dict ({'Access-Control-Request-Method': 'GET', 'Access-Control-Request-Headers': 'origin, x-requested-with', 'Origin': 'https://bar.com/'});
        var args = dict ({'method': 'OPTIONS', 'headers': headers});
        fetch ('https://foo.com/', args).then ((function __lambda__ (response) {
            return print (response);
        }), (function __lambda__ (err) {
            return print (err);
        }));

打印:

TypeError: Failed to execute 'fetch' on 'Window': Iterator is not an object.

如果我从编译的代码中删除 dict,它就会运行。

如何编译为正确的 Javascript 对象而不是 dict?

最佳答案

现在知道了。

事实证明:

https://www.transcrypt.org/docs/html/special_facilities.html#create-bare-javascript-objects-and-iterate-over-their-attributes-from-python-pragma-jsiter-and-pragma-nojsiter

Normally a Python {...} literal is compiled to dict ({...}) to include the special attributes and methods of a Python dict, including e.g. an iterator. When pragma ('jsiter') is active, a Python {...} literal is compiled to a bare {...}, without special attributes or methods. To still be able to iterate over the attributes of such a bare JavaScript object from Python, when pragma ('jsiter') is active, a Python for ... in ... is literally translated to a JavaScript for (var ... in ...). The main use case for this pragma is conveniently looping through class attributes in the new method of a metaclass. As a more flexible, but less convenient alternative, pragma ('js', '{}', '''...''') can be used.

所以代码应该是:

__pragma__('jsiter')

headers = {
    "Access-Control-Request-Method": "GET",
    "Access-Control-Request-Headers": "origin, x-requested-with",
    "Origin": "https://bar.com/"
}

args = {
    "method":"OPTIONS",
    "headers":headers
}

__pragma__('nojsiter')

关于javascript - 如何使 Transcrypt 编译为对象而不是字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50427012/

相关文章:

javascript - 导航子菜单在页面加载时未最小化

javascript - 窗口绑定(bind) POPSTATE

python - 使用可变对象的副本作为字典键

c# - MSBuild 任务中的哈希表/字典参数

javascript - 不允许粘贴任何非字母数字字符

javascript - 包含单独的 HTML,其中包含 <head> 中的代码

jquery - 如何抓取通过按钮锁定的数据?

python - 如何对 Python 程序输出的所有文本进行编码?

c++ - 如何返回一个int和一个字符串?

swift - 具有字典参数的 Realm 中的谓词