Skip to content

Use @_disfavoredOverload to enable more ergonomic syntax for PythonFunction #54

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion PythonKit/Python.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1606,7 +1606,7 @@ final class PyFunction {
precondition(callingConvention == calledConvention,
"Called PyFunction with convention \(calledConvention), but expected \(callingConvention)")
}

func callAsFunction(_ argumentsTuple: PythonObject) throws -> PythonConvertible {
checkConvention(.varArgs)
let callSwiftFunction = unsafeBitCast(self.callSwiftFunction, to: VarArgsFunction.self)
Expand All @@ -1624,6 +1624,7 @@ public struct PythonFunction {
/// Called directly by the Python C API
private var function: PyFunction

@_disfavoredOverload
public init(_ fn: @escaping (PythonObject) throws -> PythonConvertible) {
function = PyFunction { argumentsAsTuple in
return try fn(argumentsAsTuple[0])
Expand Down Expand Up @@ -1826,6 +1827,7 @@ struct PyMethodDef {
public struct PythonInstanceMethod {
private var function: PythonFunction

@_disfavoredOverload
public init(_ fn: @escaping (PythonObject) throws -> PythonConvertible) {
function = PythonFunction(fn)
}
Expand Down
54 changes: 28 additions & 26 deletions Tests/PythonKitTests/PythonFunctionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ class PythonFunctionTests: XCTestCase {
return
}

let pythonAdd = PythonFunction { (args: [PythonObject]) in
let pythonAdd = PythonFunction { args in
let lhs = args[0]
let rhs = args[1]
return lhs + rhs
}.pythonObject

let pythonSum = pythonAdd(2, 3)
XCTAssertNotNil(Double(pythonSum))
XCTAssertEqual(pythonSum, 5)
Expand Down Expand Up @@ -54,35 +54,33 @@ class PythonFunctionTests: XCTestCase {
return
}

let constructor = PythonInstanceMethod { (args: [PythonObject]) in
let constructor = PythonInstanceMethod { args in
let `self` = args[0]
let arg = args[1]
`self`.constructor_arg = arg
`self`.constructor_arg = args[1]
return Python.None
}

// Instead of calling `print`, use this to test what would be output.
var printOutput: String?


// Example of function using an alternative syntax for `args`.
let displayMethod = PythonInstanceMethod { (args: [PythonObject]) in
// let `self` = params[0]
let arg = args[1]
printOutput = String(arg)
// let `self` = args[0]
printOutput = String(args[1])
return Python.None
}

let classMethodOriginal = PythonInstanceMethod { (args: [PythonObject]) in
// let cls = params[0]
let arg = args[1]
printOutput = String(arg)

let classMethodOriginal = PythonInstanceMethod { args in
// let cls = args[0]
printOutput = String(args[1])
return Python.None
}

// Did not explicitly convert `constructor` or `displayMethod` to
// PythonObject. This is intentional, as the `PythonClass` initializer
// should take any `PythonConvertible` and not just `PythonObject`.
let classMethod = Python.classmethod(classMethodOriginal.pythonObject)

let Geeks = PythonClass("Geeks", members: [
// Constructor
"__init__": constructor,
Expand All @@ -100,10 +98,10 @@ class PythonFunctionTests: XCTestCase {
XCTAssertEqual(obj.constructor_arg, "constructor argument")
XCTAssertEqual(obj.string_attribute, "Geeks 4 geeks!")
XCTAssertEqual(obj.int_attribute, 1706256)

obj.func_arg("Geeks for Geeks")
XCTAssertEqual(printOutput, "Geeks for Geeks")

Geeks.class_func("Class Dynamically Created!")
XCTAssertEqual(printOutput, "Class Dynamically Created!")
}
Expand Down Expand Up @@ -136,16 +134,16 @@ class PythonFunctionTests: XCTestCase {

var helloOutput: String?
var helloWorldOutput: String?

// Declare subclasses of `Python.Exception`

let HelloException = PythonClass(
"HelloException",
superclasses: [Python.Exception],
members: [
"str_prefix": "HelloException-prefix ",

"__init__": PythonInstanceMethod { (args: [PythonObject]) in
"__init__": PythonInstanceMethod { args in
let `self` = args[0]
let message = "hello \(args[1])"
helloOutput = String(message)
Expand All @@ -155,6 +153,7 @@ class PythonFunctionTests: XCTestCase {
return Python.None
},

// Example of function using the `self` convention instead of `args`.
"__str__": PythonInstanceMethod { (`self`: PythonObject) in
return `self`.str_prefix + Python.repr(`self`)
}
Expand All @@ -167,7 +166,7 @@ class PythonFunctionTests: XCTestCase {
members: [
"str_prefix": "HelloWorldException-prefix ",

"__init__": PythonInstanceMethod { (args: [PythonObject]) in
"__init__": PythonInstanceMethod { args in
let `self` = args[0]
let message = "world \(args[1])"
helloWorldOutput = String(message)
Expand All @@ -179,14 +178,15 @@ class PythonFunctionTests: XCTestCase {
return Python.None
},

// Example of function using the `self` convention instead of `args`.
"custom_method": PythonInstanceMethod { (`self`: PythonObject) in
return `self`.int_param
}
]
).pythonObject

// Test that inheritance works as expected

let error1 = HelloException("test 1")
XCTAssertEqual(helloOutput, "hello test 1")
XCTAssertEqual(Python.str(error1), "HelloException-prefix HelloException('hello test 1')")
Expand All @@ -201,8 +201,10 @@ class PythonFunctionTests: XCTestCase {
XCTAssertNotEqual(error2.custom_method(), "123")

// Test that subclasses behave like Python exceptions

let testFunction = PythonFunction { (_: [PythonObject]) in

// Example of function with no named parameters, which can be stated
// ergonomically using an underscore. The ignored input is a [PythonObject].
let testFunction = PythonFunction { _ in
throw HelloWorldException("EXAMPLE ERROR MESSAGE", 2)
}.pythonObject

Expand Down