Skip to content

# `` slice

RDFLib Graphs (and Resources) can be “sliced” with [] syntax

This is a short-hand for iterating over triples.

Combined with SPARQL paths (see `foafpaths.py`) - quite complex queries can be realised.

See `Graph.__getitem__` for details

Attributes:

- `EXAMPLES_DIR` –
- `friends` –
- `graph` –

## `` EXAMPLES_DIR `module-attribute`

    EXAMPLES_DIR = parent

## `` friends `module-attribute`

    friends = list(graph[person:(knows * '+' / name)])

## `` graph `module-attribute`

    graph = Graph()

show_source: false show_docstring_attributes: false show_docstring_functions: false show_docstring_modules: false show_docstring_classes: false show_signature: false show_signature_annotations: false show_signature_type_parameters: false show_docstring_other_parameters: false show_docstring_parameters: false show_docstring_raises: false show_docstring_receives: false show_docstring_returns: false summary: false show_if_no_docstring: false

    from pathlib import Path

    from rdflib import RDF, Graph
    from rdflib.namespace import FOAF

    EXAMPLES_DIR = Path(__file__).parent

    if __name__ == "__main__":
        graph = Graph()
        graph.parse(f"{EXAMPLES_DIR / 'foaf.n3'}", format="n3")

        for person in graph[: RDF.type : FOAF.Person]:  # type: ignore[misc]
            friends = list(graph[person : FOAF.knows * "+" / FOAF.name])  # type: ignore[operator]
            if friends:
                print(f"{graph.value(person, FOAF.name)}'s circle of friends:")
                for name in friends:
                    print(name)