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 Module.
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 register(extension:):
interpreter.register(extension: my_module.self)
Module structs are initialized whetever they are imported or not and are re-initialized when Interpreter.clearState is called but they are created as real Python modules at import time by pyto_runtime.SwiftLoader. The pyto_runtime.SwiftFinder meta path finder is what finds the Swift extensions.
Executing¶
The execute(module:) function is executed when a module is imported and receives the module object.
func execute(module: Object) throws {
module.foo = try interpreter.object("Bar")
}
Registering Members¶
There are 5 default Member types which can be registered in members:
Registering a method looks like this:
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 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 args and kwargs.
By providing a Signature, you can limit the arguments that can be passed and also have access to ArgumentParser.arg and ArgumentParser.parse.
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
)