.. _swift-extensions: Extensions ========== PytoRuntime provides an API for exposing Swift code to Python modules. Unlike Python shared extensions shipped as separate binaries, these can be loaded into any Python version. Creating a module ----------------- This is the basic structure of a :swift:symbol:`Module`. .. code-block:: swift import PytoRuntime struct my_module: Module { var name: String { "my_module" } var doc: String? { "An example module." } var members: [any Member] { // ... } } It can now be registered using :swift:symbol:`Interpreter.register(extension:)`: .. code-block:: swift interpreter.register(extension: my_module.self) Module structs are initialized whetever they are imported or not and are re-initialized when :swift:symbol:`Interpreter.clearState` is called but they are created as real Python modules at import time by :py:class:`pyto_runtime.SwiftLoader`. The :py:class:`pyto_runtime.SwiftFinder` meta path finder is what finds the Swift extensions. Executing --------- The :swift:symbol:`Module.execute(module:)` function is executed when a module is imported and receives the module object. .. code-block:: swift func execute(module: Object) throws { module.foo = try interpreter.object("Bar") } Registering Members ------------------- There are 5 default :swift:symbol:`Member` types which can be registered in :swift:symbol:`Module.members`: - :swift:symbol:`Module` - :swift:symbol:`Class` - :swift:symbol:`Method` - :swift:symbol:`Attribute` - :swift:symbol:`Property` Registering a method looks like this: .. code-block:: swift func my_function(module: Object, argumentParser: ArgumentParser) throws -> (any Parsable)? { return "Hello World!" } var members: [any Member] { Method( name: "my_function", doc: "Example of a Swift function exposed to Python", body: my_function ) } See also :swift:symbol:`MethodBody`. Now let's say we want to take arguments. The default signature for methods is ``(*args, **kwargs)`` and you can get the arguments through :swift:symbol:`ArgumentParser.args` and :swift:symbol:`ArgumentParser.kwargs`. By providing a :swift:symbol:`Signature`, you can limit the arguments that can be passed and also have access to :swift:symbol:`ArgumentParser.arg` and :swift:symbol:`ArgumentParser.parse`. .. code-block:: swift func my_function(module: Object, argumentParser: ArgumentParser) throws -> (any Parsable)? { let (name, print): (String, Bool) = try argumentParser.parse() let string = "Hello \(name)!" if print { Swift.print(string) } return string } Method( name: "my_function", doc: "Example of a Swift function exposed to Python", signature: { .positionalOrKeyword("string", annotation: interpreter.builtins.str) .positionalOrKeyword("print", annotation: interpreter.builtins.bool, default: false) .returns(interpreter.builtins.None) }, body: my_function )