Skip to content

Conversation

@Skyline-23
Copy link

This pull request introduces a new way to call Python functions from Swift that surfaces Python exceptions as Swift errors, rather than trapping. This allows developers to handle Python errors using Swift's try/catch mechanism, making error handling more robust and idiomatic in Swift. The changes include a new wrapper type, an extension property for easier access, and corresponding unit tests.

New error-handling callable support:

  • Added a throwingCallable property to PythonObject, which returns a ThrowingDynamicCallable wrapper. This allows users to opt-in to error handling via try/catch when calling Python functions from Swift.
  • Introduced the ThrowingDynamicCallable struct, a dynamic-callable wrapper around PythonObject that throws Swift errors when Python exceptions are raised, instead of trapping. This struct provides several dynamicallyCall methods for calling Python functions with positional or keyword arguments.

Testing:

  • Added a new test, testThrowingCallableWrapper, to verify that throwingCallable correctly returns results for valid calls and throws Swift errors for Python exceptions, including checking the exception type.

Replace `try!` with do/catch in PythonObject.dynamicallyCall methods.
Previously, any Python exception raised during dynamic calls would
trigger swift_unexpectedError → SIGTRAP, crashing the app.

Now returns Python.None with assertionFailure (debug-only) instead
of fatal crash in release builds.

Affected methods:
- dynamicallyCall(withArguments:)
- dynamicallyCall(withKeywordArguments:) (both overloads)
Add `safeCallable` property to PythonObject that returns Python.None
on Python exceptions instead of crashing.

Follows the existing `throwingCallable` pattern, providing an opt-in
safe path without changing default behavior.

Usage: obj.safeCallable(args...) → returns Python.None on error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant