Is Python's order of evaluation of function arguments and operands deterministic (+ where is it documented)?

后端 未结 2 1713
执念已碎
执念已碎 2020-11-30 13:02

C doesn\'t guarantee any evaluation order so a statement like f(g1()+g2(), g3(), g4()) might execute g1(), g2(), g3(), an

相关标签:
2条回答
  • 2020-11-30 13:14

    https://docs.python.org/3/reference/expressions.html#evaluation-order:

    Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

    In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

    expr1, expr2, expr3, expr4
    (expr1, expr2, expr3, expr4)
    {expr1: expr2, expr3: expr4}
    expr1 + expr2 * (expr3 - expr4)
    expr1(expr2, expr3, *expr4, **expr5)
    expr3, expr4 = expr1, expr2
    

    The same is true in Python 2.

    0 讨论(0)
  • 2020-11-30 13:26

    Yes, left to right evaluation order is guaranteed, with the exception of assignments. That's documented here (py2, py3):

    Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

    In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

    expr1, expr2, expr3, expr4
    (expr1, expr2, expr3, expr4)
    {expr1: expr2, expr3: expr4}
    expr1 + expr2 * (expr3 - expr4)
    expr1(expr2, expr3, *expr4, **expr5)
    expr3, expr4 = expr1, expr2
    

    If the language were not making some choice about this, the evaluation of one argument could mutate another argument and result in unspecified behaviour, so all implementations of Python must follow this spec.

    0 讨论(0)
提交回复
热议问题