Interacting with Python Objects =============================== In :doc:`getting-started`, we saw how to run code asynchronously. But :swift:symbol:`Interpreter`, and the :swift:symbol:`Object` class also provide APIs to interact synchronously with Python objects. Evaluating ---------- Evaluating an expression can be done with :swift:symbol:`Interpreter.evaluate(expr:)`: .. code-block:: swift try interpreter.evaluate("2+2") // 4 Executing --------- The :swift:symbol:`Interpreter.execute(code:)` function makes it possible to run code in a new globals dictionary and return it: .. code-block:: swift let namespace = try interpreter.exec(code: "foo = 'bar'") namespace["foo"] // "bar" Importing --------- Importing a module can be done with :swift:symbol:`Interpreter.import(module:)`. It accepts a full module name. .. code-block:: swift try interpreter.import(module: "sys") There is also the :swift:symbol:`Interpreter.builtins` property for quick access to the ``builtins`` module. Using Objects ------------- The functions described earlier return values of type :swift:symbol:`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 :swift:symbol:`Parsable` and throw :swift:symbol:`Exception` in case of exception. .. code-block:: swift let sys = try interpreter.import(module: "sys") try sys.stdout?.write?("Hello World!") As you can see, dynamic members of :swift:symbol:`Object` are all optionals. You can also make them non optional by wrapping them in :swift:symbol:`Object.init(_:)` which will throw an :swift:symbol:`Interpreter.Error.unhandled` error when the parameter is ``nil``. .. code-block:: swift try Object(sys.stdout.write)("Hello World!") To pass keyword arguments: .. code-block:: swift try Object(interpreter.builtins.print)("Hello World", kwargs: ["file": sys.stderr]) Conversion ---------- Python functions return :swift:symbol:`Object` values. To parse them to Swift values, use :swift:symbol:`Object.parse`. See :swift:symbol:`Parsable` for more information. .. code-block:: swift let version: String = try Object(sys.version).parse() version // 3.14.0 ... Objects conform to ``CustomStringConvertible``, so you can put them in strings: .. code-block:: swift "\(try Object(sys.version))" // 3.14.0 ... You can also compare two Python values, or a Python value with a :swift:symbol:`Parsable` value. If the comparaison fails between two Python values, it will return whetever the pointers are the same. .. code-block:: let helloWorld = try Object(interpreter.builtins.str)("Hello World") "Hello World" == helloWorld // true