Skip to main content

Library for generating python-expressions

Project description

UnEval

UnEval is a microlibrary for generating python-expressions, which can be converted to runnable pythoncode.

Some use cases of this library are:

I have the intention to build something on top of this later that converts python expressions to linear programming constraints.

Usage

Firstly, the building blocks can be used to generate expressions. Secondly, these expressions can be converted.

Building blocks

Factory AST-class Example
quote ast.Name quote('a') or quote.a (shortcut)
if_ ast.IfExpr if_(quote.x >= 0, quote.x, -quote.x)
for_ ast.GenExpr for_(quote.x * quote.x, (quote.x, quote.range(5)))
lambda_ ast.Lambda lambda_([quote.x], quote.x * quote.x)

Converters

Converter Target Remark
str String Convert to readable python
to_expression Expression Parse existing string
to_ast AST-node Generates AST-node
to_code Code-object Compiles the expression

Examples

# Create variables
x, y = quote.x, quote.y  # Shortcut for quote("x"), quote("y")

# Manipulate
z = x*x + y*y
d = z.abs() + x.pow(3) - y.sin(x)

# Convert
print(z)  # x * x + y * y
print(ast.dump(to_ast(z)))  # BinOp(left=BinOp(left=Name(id='x', ctx=Load()), op=Mult(), right=Name(id='x', ctx=Load())), op=Add(), right=BinOp(left=Name(id='y', ctx=Load()), op=Mult(), right=Name(id='y', ctx=Load())))
print(eval(to_code(z), {"x": 3, "y": 4}))  # 25

These ideas can be used to create alternative syntax for lambda-functions:

from uneval import *


def f_x(expr: Expression):
  """Create a lambda with parameter x."""
  return eval(to_code(lambda_([quote.x], expr)))


square = f_x(x * x)  # Same as lambda x: x * x
print(square(5))  # => 25

Similar work

Libraries that implement something similar:

  • Macropy has quasiquote.
  • Polars - Writing col.x creates something like this Expression-object.
  • SymPy - Symbolic manipulation, but its representation is different from Python.
  • pulp - Can build objectives and constraints for solving linear programming problems.
  • sqlalchemy - Generates properties based on a schema.
  • latexify - Converts python to SQL.

Other:

Useful references:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

uneval-0.0.1-py3-none-any.whl (9.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page