example_numpy_calculator.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:typped 作者: abarker 项目源码 文件源码
def define_assignment_operator(parser):
    """Define assignment and reading of simple variables."""

    parser.calculator_symbol_dict = {} # Store symbol dict as a new parser attribute.
    symbol_dict = parser.calculator_symbol_dict

    symbol_dict["pi"] = np.pi # Predefine pi.
    symbol_dict["e"] = np.e # Predefine e.

    # Note that on_ties for identifiers is set to -1, so that when string
    # lengths are equal defined function names will take precedence over generic
    # identifiers (which are only defined as a group regex).
    parser.def_token("k_identifier", r"[a-zA-Z_](?:\w*)", on_ties=-1)
    parser.def_literal("k_identifier", eval_fun=lambda t: symbol_dict.get(t.value, 0.0))

    def eval_assign(t):
        """Evaluate the identifier token `t` and save the value in `symbol_dict`."""
        rhs = t[1].eval_subtree()
        symbol_dict[t[0].value] = rhs
        return rhs

    parser.def_infix_op("k_equals", 5, "right",
                precond_fun=lambda tok, lex: lex.peek(-1).token_label == "k_identifier",
                eval_fun=eval_assign)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号