Package: polarify
polarIFy: Simplifying conditional Polars Expressions with Python 🐍 🐻‍❄️Welcome topolarIFy, a Python function decorator that simplifies the way you write logical statements for Polars. With polarIFy, you can use Python's language structures likeif / elif / elsestatements and transform them intopl.when(..).then(..).otherwise(..)statements. This makes your code more readable and less cumbersome to write. 🎉🎯 UsagepolarIFy can automatically transform Python functions usingif / elif / elsestatements into Polars expressions.Basic TransformationHere's an example:@polarifydefsignum(x:pl.Expr)->pl.Expr:s=0ifx>0:s=1elifx<0:s=-1returnsThis gets transformed into:defsignum(x:pl.Expr)->pl.Expr:returnpl.when(x>0).then(1).otherwise(pl.when(x<0).then(-1).otherwise(0))Handling Multiple StatementspolarIFy can also handle multiple statements like:@polarifydefmultiple_if_statement(x:pl.Expr)->pl.Expr:a=1ifx>0else5b=2ifx<0else2returna+bwhich becomes:defmultiple_if_statement(x):returnpl.when(x>0).then(1).otherwise(5)+pl.when(x<0).then(2).otherwise(2)Handling Nested StatementsAdditionally, it can handle nested statements:@polarifydefnested_if_else(x:pl.Expr)->pl.Expr:ifx>0:ifx>1:s=2else:s=1elifx<0:s=-1else:s=0returnswhich becomes:defnested_if_else(x:pl.Expr)->pl.Expr:returnpl.when(x>0).then(pl.when(x>1).then(2).otherwise(1)).otherwise(pl.when(x<0).then(-1).otherwise(0))So you can still write readable row-wise python code while the@polarifydecorator transforms it into a function that works with efficient polars expressions.Using apolarifyd functionimportpolarsasplfrompolarifyimportpolarify@polarifydefcomplicated_operation(x:pl.Expr)->pl.Expr:k=0c=2ifx>0:k=1c=0ifx<10:c=1elifx<0:k=-1returnk*cdf=pl.DataFrame({"x":[-1,1,5,10]})result=df.select(pl.col("x"),complicated_operation(pl.col("x")))print(result)# shape: (4, 2)# ┌─────┬─────────┐# │ x   ┆ literal │# │ --- ┆ ---     │# │ i64 ┆ i32     │# ╞═════╪═════════╡# │ -1  ┆ -2      │# │ 1   ┆ 1       │# │ 5   ┆ 1       │# │ 10  ┆ 0       │# └─────┴─────────┘Displaying the transpiled polars expressionYou can also display the transpiled polars expression by calling thetransform_func_to_new_sourcemethod:frompolarifyimporttransform_func_to_new_sourcedefsignum(x):s=0ifx>0:s=1elifx<0:s=-1returnsprint(f"Original function:\n{inspect.getsource(signum)}")# Original function:# def signum(x):#     s = 0#     if x > 0:#         s = 1#     elif x < 0:#         s = -1#     return sprint(f"Transformed function:\n{transform_func_to_new_source(signum)}")# Transformed function:# def signum_polarified(x):#     import polars as pl#     return pl.when(x > 0).then(1).otherwise(pl.when(x < 0).then(-1).otherwise(0))TODO: complicated example with nested functions⚙️ How It WorkspolarIFy achieves this by parsing the AST (Abstract Syntax Tree) of the function and transforming the body into a Polars expression by inlining the different branches.
To get a more detailed understanding of what's happening under the hood, check out ourblog postexplaining how polarify works!💿 Installationcondacondainstall-cconda-forgepolarify# or micromambamicromambainstall-cconda-forgepolarify# or pixipixiaddpolarifypippipinstallpolarify⚠️ LimitationspolarIFy is still in an early stage of development and doesn't support the full Python language. Here's a list of the currently supported and unsupported operations:Supported operationsif / else / elifstatementsbinary operations (like+,==,>,&,|, ...)unary operations (like~,-,not, ...) (TODO)assignments (likex = 1)polars expressions (likepl.col("x"), TODO)side-effect free functions that return a polars expression (can be generated by@polarify) (TODO)Unsupported operationsforloopswhileloopsbreakstatements:=walrus operatormatch ... casestatements (TODO)functions with side-effects (print,pl.write_csv, ...)🚀 BenchmarksTODO: Add some benchmarks📥 Development installationpixiinstall
pixirunpostinstall
pixiruntest