2

这是我用 transcrypt -b -n -m (version 3.6.84) 转码的 python 代码:

def test_1():
    console.log('before assert')
    assert False, "False fails"
    console.log('we should not see that if assert fails as expected')


def test_2():
    console.log('before assert')
    try:
        assert False, "False fails"
    except AssertionError as exception:
        console.log('we should see that since we catch the assertion error')
    console.log('after assert')

当我在浏览器控制台中运行 test_1/test_2 时,我得到了一个奇怪的行为:

> mymodule.test_1()
before assert
we should not see that if assert fails as expected
<- undefined
> mymodule.test_2()
before assert
after assert
<- undefined

为什么 assert 不会引发异常?

4

1 回答 1

2

来自问题 482的回答:

您需要 -da 开关来激活断言:

转码 -b -n -m -da

我已经测试过:

def test_1():
    console.log('before assert')
    assert False, "False fails"
    console.log('we should not see that if assert fails as expected')

def test_2():
    console.log('before assert')
    try:
        assert False, "False fails"
    except AssertionError as exception:
        console.log('we should see that since we catch the assertion error')
    console.log('after assert')

try:    
    test_1()
except AssertionError as exception:
    console.log('we should see this')

test_2()

它打印:

before assert
we should see this
before assert
we should see that since we catch the assertion error
after assert

Transcrypt 中的许多东西都是可选的,以防止生成的 JavaScript 膨胀。一些功能由命令行开关控制:

http://www.transcrypt.org/docs/html/installation_use.html#available-command-line-switches

一些特性(也)由编译指示(编译器指令)控制:

http://www.transcrypt.org/docs/html/special_facilities.html#the-pragma-mechanism

于 2018-02-14T18:35:23.833 回答