PythonLambda – adding Python Lambdas to Swift / PythonKit

Hi all, I am interested in using Swift for data science, and have of course started using PythonKit to interface with numpy, pandas etc.

A challenge that one quickly faces when using many Python APIs is their reliance on Python lambdas, and this can quickly become a showstopper.

To fix this, I've built a small library which works together with PythonKit to provide Python lambda functionality to Swift. Here's an example:

Python code: map(lambda(x:x*2), [10,12,14] )

Swift code: PythonLambda {x in x*2} , [10,12,14] )

As a convenience, and to improve the look of the code, the special character 𝝺 is provided as a typealias for PythonLambda. So the above can be written as:

Swift code: 𝝺{x in x*2} , [10,12,14] )

A second example: sum all the rows in a Pandas dataframe:

let summer = 𝝺{(row:PythonObject) in Double(np.sum(row)) ?? 0}

let result = df.apply( summer, axis: 0 )

There are a few limitations to the implementation, in that only certain function shapes are supported (though generally sufficient to cover normal usage of lambdas in Python), see the documentation for details. However, if more complex lambdas are needed, it's possible to create a lambda using Python code directly in Swift:

    let doubler = PythonStringLambda(lambda: "x:x*2")

    // x*2 is interpreted as Python code. Obviously, care is needed!

    df.apply( doubler.pythonObject )

If you're interested, please see the github repo here:

This relies on a forked version of PythonKit to add various features that PythonLambda uses. If people find PythonLambda useful, I will look to get those added to PythonKit.

To use in your own code, add dependencies to the below Swift packages: , branch master , branch py_c_tools

and add at the top of your code

import PythonKit

import PythonLambda

The library has only been tested on macOS (but doesn't rely on system-specific features, so should "in theory" work anywhere PythonKit is supported); and it only works on Python3 installations. It's "beta" at the moment, awaiting feedback from a larger audience!

I'd be very interested in thoughts and feedback.

1 Like
Terms of Service

Privacy Policy

Cookie Policy