1

I am trying to pass keyword arguments into a Python function using PythonKit. So far, I have just passed strings, but this is stumping me. I do not know how PythonKit processes these dictionary inputs. I have put what I have tried so far (nonworking) and what my Python function expects. Thank you in advance!

    private func createDBDirectory() {
        let DBDirectoryPath = createDirectory(folderName: "databases")!.path
        userConfig.DBPath = DBDirectoryPath + "/fileORGS.db"
        let sqlInteract = Python.import("sqlFunctions")
        let tagInfoCols: [String: PythonObject] = ["tag": "NULL", "tagHashID": "NULL", "tagCreationTime": "NULL", "tagColor": "NULL"]
        sqlInteract.sqlCreateTable.callas(userConfig.DBPath, "tagINFO", tagInfoCols)
    }
}
def sqlCreateTable(databasePath, tableName: str, **columns):

Error message given by this code:

PythonKit/Python.swift:553: Fatal error: Could not access PythonObject member 'callas'

I expect the dictionary or kwargs to be passed into the Python function without raising an exception.

1 Answer 1

3

If all the argument names and the number of arguments are known at compile time, you can just do what you'd do in Python, except replacing the = with :,

sqlInteract.sqlCreateTable(
    userConfig.DBPath, "tagINFO",
    tag: "NULL",
    tagHashID: "NULL",
    tagCreationTime: "NULL",
    tagColor: "NULL"
)

If the number of arguments and/or parameter names is dynamic, you should use dynamicallyCall(withKeywordArguments:). Pass in a KeyValuePairs<String, any PythonConvertible>, or an [(String, any PythonConvertible)]. This should contain all the arguments you want to pass.

Use an empty string "" as the key if you don't want to pass an argument label.

// you can add/remove elements to this if you change this to "var"
let arguments: KeyValuePairs<String, any PythonConvertible> = [
    "": userConfig.DBPath,
    "": "tagINFO",
    "tag": "NULL",
    "tagHashID": "NULL",
    "tagCreationTime": "NULL",
    "tagColor": "NULL"
]
sqlInteract.sqlCreateTable.dynamicallyCall(withKeywordArguments: arguments)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.