Interacting with Python Objects

In Getting Started, we saw how to run code asynchronously. But Interpreter, and the Object class also provide APIs to interact synchronously with Python objects.

Evaluating

Evaluating an expression can be done with evaluate(expr:):

try interpreter.evaluate("2+2") // 4

Executing

The Interpreter.execute(code:) function makes it possible to run code in a new globals dictionary and return it:

let namespace = try interpreter.exec(code: "foo = 'bar'")
namespace["foo"] // "bar"

Importing

Importing a module can be done with import(module:). It accepts a full module name.

try interpreter.import(module: "sys")

There is also the builtins property for quick access to the builtins module.

Using Objects

The functions described earlier return values of type Object. This class manages Python objects: it automatically increment and decrement their reference count. Properties can be dynamically accessed, it implements subscipting and operators. Functions take any Swift value conforming to Parsable and throw Exception in case of exception.

let sys = try interpreter.import(module: "sys")
try sys.stdout?.write?("Hello World!")

As you can see, dynamic members of Object are all optionals. You can also make them non optional by wrapping them in init(_:) which will throw an unhandled error when the parameter is nil.

try Object(sys.stdout.write)("Hello World!")

To pass keyword arguments:

try Object(interpreter.builtins.print)("Hello World", kwargs: ["file": sys.stderr])

Conversion

Python functions return Object values. To parse them to Swift values, use Object.parse. See Parsable for more information.

let version: String = try Object(sys.version).parse()
version // 3.14.0 ...

Objects conform to CustomStringConvertible, so you can put them in strings:

"\(try Object(sys.version))" // 3.14.0 ...

You can also compare two Python values, or a Python value with a Parsable value. If the comparaison fails between two Python values, it will return whetever the pointers are the same.

let helloWorld = try Object(interpreter.builtins.str)("Hello World")
"Hello World" == helloWorld // true