Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python语法结束“;“返回外部函数”;_Python_Parsing_Ebnf - Fatal编程技术网

Python语法结束“;“返回外部函数”;

Python语法结束“;“返回外部函数”;,python,parsing,ebnf,Python,Parsing,Ebnf,我注意到Python语法允许返回语句出现在函数之外,但我真的不明白,为什么?我相信可以指定语法,所以这是不允许的 这是一段Python语法,它允许: single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |

我注意到Python语法允许返回语句出现在函数之外,但我真的不明白,为什么?我相信可以指定语法,所以这是不允许的

这是一段Python语法,它允许:

single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
return_stmt: 'return' [testlist]

解释器也会将此报告为语法错误(“return”在函数外),但如果语法中没有指定,解析器如何检测它呢

首先,中断程序构建AST树。然后,当它通过访问AST树为基本块生成代码时,它会验证return语句是否在函数中

compiler_visit_stmt(struct compiler *c, stmt_ty s)
    ...
    switch (s->kind) {
        ...
        case Return_kind:
            if (c->u->u_ste->ste_type != FunctionBlock)
                return compiler_error(c, "'return' outside function");

正如你所看到的,语言的语义不仅仅是由语法定义的。

我从来没有听说过这一点,但是在你的例子中,函数外有一个return语句吗?根据这个语法,我们有:single\u input=>simple\u stmt=>small\u stmt NEWLINE=>flow\u stmt NEWLINE=>return\u stmt NEWLINE=>return'NEWLINE。由于single_输入是语法的开始符号(正如Python文档中提到的),我们有这样一种说法。你当然是对的,语义不仅仅是由语法定义的,但是它很奇怪,因为在这种情况下它可以。还是我错了?你可以在语法中定义它,但这会使它复杂化(因为函数定义也是一个语句)