Hacker News new | past | comments | ask | show | jobs | submit login
Show HN: Lambdex – Writing more complicated anonymous functions in Python (github.com/hsfzxjy)
2 points by hsfzxjy on Feb 10, 2021 | hide | past | favorite | 1 comment



The package lambdex allows you to write complicated anonymous functions other than the built-in `lambda`s. Take a recursive function that calculates Fibonacci series as an example:

    from lambdex import def_
    def_(lambda n: [
        if_[n <= 0] [
            raise_[ValueError(f'{n} should be positive')]
        ],
        if_[n <= 2] [
            return_[1]
        ],
        return_[callee_(n - 1) + callee_(n - 2)]  # Recursion
    ])(10)  # 55
In the code above, we declare an anonymous function with multiple imperative statements inside, which is more or less similar to the closure in Rust or arrow function in Javascript. There are keywords such as `if_` or `raise_` emulating Python control flows, and brackets `[]` to group statements. Currently, *lambdex* supports nearly all the structures in Python (including the async/await suite), plus several optional language extensions for advanced features.

The "new syntax" requires NO modification on the Python interpreter. Instead it transpiles the ASTs and compiles them to bytecodes at runtime. Even so, lambdex has rather small runtime overhead, since each compiled code object will be cached.

Besides, lambdex provides a formatter for the new syntax, in order to provide better programming experience. The formatter could easily co-operate with other formatters like `yapf`, so that minor changes should be made to enjoy it in an IDE or editor.

Please feel free to try lambdex with your own cases. Discussions and issues are welcomed on Github :-)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: