Skip to content

Type issues with SPARQL graph.query() #3129

Open
@multimeric

Description

@multimeric

Consider the following example:

from rdflib import Graph, URIRef, Literal
from typing import reveal_type

graph = Graph()
graph.add((URIRef("http://example.org/subject"), URIRef("http://schema.org/name"), Literal("foo")))
for result in graph.query("""
    SELECT ?name ?description
    WHERE {
        ?file_name <http://schema.org/name> ?name .
        OPTIONAL {
            ?file_name <http://schema.org/description> ?description .
        }
    }
"""):
    reveal_type(result)
    reveal_type(result.name)
    reveal_type(result.description)

Firstly, the type of result.description is incorrect.
The static type according to the Pyright type checker is:

information: Type of "result.description" is "Unknown | Identifier"

But at runtime we get:

Runtime type is 'NoneType'

So, because of OPTIONAL{}, we need to type result variables as Identifier | None.

Secondly, as noted in #2283, result is an annoying type union. Pyright says Type of "result" is "Tuple[Node, Node, Node] | bool | ResultRow". The reason why this should not be typed as a union is because the syntax of the SPARQL query defines the result type, meaning that I know statically which result type it should be, but I have no way to express this. Downstream this union causes issues because:

error: Cannot access attribute "description" for class "_TripleType"
error: Cannot access attribute "description" for class "bool"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions