create custom_function in rdflib

51 Views Asked by At

I'm trying to create a custom function in rdflib in Python to call from a SPARQL query.

I created this simple example that should return "test". It does not give an error. It just returns nothing.

from rdflib import Graph, URIRef, Literal
from rdflib.plugins.sparql.operators import custom_function

g = Graph()

@custom_function(URIRef("http://example.org/myCustomFunction"))
def myCustomFunction(args):
    return Literal("test")

query = """
SELECT ?result WHERE {
    BIND(<http://example.org/myCustomFunction>() AS ?result)
}
"""

for row in g.query(query):
    print(f"Result: {row.result}")

I hope anyone can help.

1

There are 1 best solutions below

0
Rick Companje On BEST ANSWER

I just found the solution to my problem. The amount of arguments matters. So if the custom function has one argument ('args' in the example above) it should also be called from SPARQL with 1 argument. It would have helped if an error message was shown.

this works:

def myCustomFunction(a,b):
    return Literal(a+b)
BIND(<http://example.org/myCustomFunction>(5,6) AS ?result)

I hope this is useful for others.