RDFLib is a Python library for working with RDF, a simple yet powerful language for representing information.
—
Primary interface for working with RDF data. The Graph class provides methods for adding, removing, and querying RDF triples, plus parsing and serialization capabilities across multiple formats.
The main container for RDF triples with comprehensive functionality for RDF data manipulation.
class Graph:
def __init__(self, store: Union[Store, str] = 'default', identifier: Optional[Union[Node, str]] = None, namespace_manager: Optional[NamespaceManager] = None, base: Optional[str] = None, bind_namespaces: str = 'rdflib'):
"""
Create an RDF graph.
Parameters:
- store: Store type ('Memory', 'SPARQLStore', etc.)
- identifier: Graph identifier (URIRef or BNode)
- namespace_manager: Custom namespace manager
"""
def add(self, triple: Tuple[Node, Node, Node]) -> 'Graph':
"""
Add a triple to the graph.
Parameters:
- triple: (subject, predicate, object) tuple
Returns:
Graph: Self for method chaining
"""
def remove(self, triple: Tuple[Node, Node, Node]) -> 'Graph':
"""
Remove triples matching the pattern.
Parameters:
- triple: Pattern tuple (None acts as wildcard)
Returns:
Graph: Self for method chaining
"""
def parse(self, source: Optional[Union[str, IO, InputSource]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[IO] = None, data: Optional[Union[str, bytes]] = None, **args) -> 'Graph':
"""
Parse RDF data into the graph.
Parameters:
- source: Source location (URL, file path, or file-like object)
- publicID: Logical URI for the document
- format: RDF format ('xml', 'turtle', 'n3', 'nt', 'json-ld', etc.)
- location: Physical location hint
- file: File-like object
- data: RDF data as string
Returns:
Graph: Self for method chaining
"""
def serialize(self, destination: Optional[Union[str, IO]] = None, format: str = 'turtle', base: Optional[str] = None, encoding: Optional[str] = None, **args) -> Union[str, bytes, 'Graph']:
"""
Serialize the graph to RDF format.
Parameters:
- destination: Output destination (file path or file-like object)
- format: Output format ('xml', 'turtle', 'n3', 'nt', 'json-ld', etc.)
- base: Base URI for relative references
- encoding: Character encoding
Returns:
str: Serialized RDF data if no destination specified
"""
def query(self, query_object: Union[str, Query], processor: str = 'sparql', result: str = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs) -> Result:
"""
Execute a SPARQL query against the graph.
Parameters:
- query_object: Query string or prepared query
- processor: Query processor to use
- result: Result format
- initNs: Initial namespace bindings
- initBindings: Initial variable bindings
- use_store_provided: Use store's query capabilities if available
Returns:
Result: Query results
"""
def update(self, update_object: Union[str, Update], processor: str = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs) -> None:
"""
Execute a SPARQL update against the graph.
Parameters:
- update_object: Update string or prepared update
- processor: Update processor to use
- initNs: Initial namespace bindings
- initBindings: Initial variable bindings
- use_store_provided: Use store's update capabilities if available
"""
def triples(self, triple: Tuple[Node, Node, Node]) -> Iterator[Tuple[Node, Node, Node]]:
"""
Iterate over triples matching the pattern.
Parameters:
- triple: Pattern tuple (None acts as wildcard)
Returns:
Iterator: Matching triples
"""
def __contains__(self, triple: Tuple[Node, Node, Node]) -> bool:
"""
Check if graph contains a triple.
Parameters:
- triple: Triple to check
Returns:
bool: True if triple exists
"""
def __len__(self) -> int:
"""
Get number of triples in graph.
Returns:
int: Triple count
"""
def __iter__(self) -> Iterator[Tuple[Node, Node, Node]]:
"""
Iterate over all triples in graph.
Returns:
Iterator: All triples
"""
def subjects(self, predicate: Node = None, object: Node = None) -> Iterator[Node]:
"""
Get subjects matching predicate/object pattern.
Parameters:
- predicate: Predicate to match (None for any)
- object: Object to match (None for any)
Returns:
Iterator: Matching subjects
"""
def predicates(self, subject: Node = None, object: Node = None) -> Iterator[Node]:
"""
Get predicates matching subject/object pattern.
Parameters:
- subject: Subject to match (None for any)
- object: Object to match (None for any)
Returns:
Iterator: Matching predicates
"""
def objects(self, subject: Node = None, predicate: Node = None) -> Iterator[Node]:
"""
Get objects matching subject/predicate pattern.
Parameters:
- subject: Subject to match (None for any)
- predicate: Predicate to match (None for any)
Returns:
Iterator: Matching objects
"""
def subject_objects(self, predicate: Node = None) -> Iterator[Tuple[Node, Node]]:
"""
Get subject-object pairs for predicate.
Parameters:
- predicate: Predicate to match
Returns:
Iterator: (subject, object) pairs
"""
def subject_predicates(self, object: Node = None) -> Iterator[Tuple[Node, Node]]:
"""
Get subject-predicate pairs for object.
Parameters:
- object: Object to match
Returns:
Iterator: (subject, predicate) pairs
"""
def predicate_objects(self, subject: Node = None) -> Iterator[Tuple[Node, Node]]:
"""
Get predicate-object pairs for subject.
Parameters:
- subject: Subject to match
Returns:
Iterator: (predicate, object) pairs
"""
def bind(self, prefix: str, namespace: Namespace, override: bool = True):
"""
Bind namespace prefix.
Parameters:
- prefix: Prefix string
- namespace: Namespace URI
- override: Whether to override existing binding
"""
def namespace(self, prefix: str) -> Namespace:
"""
Get namespace for prefix.
Parameters:
- prefix: Prefix string
Returns:
Namespace: Namespace object
"""
def namespaces(self) -> Iterator[Tuple[str, Namespace]]:
"""
Get all namespace bindings.
Returns:
Iterator: (prefix, namespace) pairs
"""
@property
def store(self):
"""
Get the underlying store.
Returns:
Store: Graph's store implementation
"""
@property
def namespace_manager(self) -> NamespaceManager:
"""
Get the namespace manager.
Returns:
NamespaceManager: Namespace manager instance
"""
@property
def identifier(self) -> Node:
"""
Get the graph identifier.
Returns:
Node: Graph identifier
"""Container for multiple named graphs. Deprecated in favor of Dataset.
class ConjunctiveGraph(Graph):
def __init__(self, store: str = 'default', identifier: Node = None):
"""
Create a conjunctive graph.
Parameters:
- store: Store type
- identifier: Graph identifier
"""
def get_context(self, identifier: Node) -> Graph:
"""
Get or create a named graph context.
Parameters:
- identifier: Context identifier
Returns:
Graph: Named graph context
"""
def contexts(self, triple: Tuple[Node, Node, Node] = None) -> Iterator[Graph]:
"""
Get contexts containing the triple pattern.
Parameters:
- triple: Triple pattern to match
Returns:
Iterator: Matching contexts
"""
@property
def default_context(self) -> Graph:
"""
Get the default context.
Returns:
Graph: Default context
"""from rdflib import Graph, URIRef, Literal, BNode
from rdflib.namespace import RDF, FOAF
# Create a graph
g = Graph()
# Add triples
person = URIRef("http://example.org/person/1")
g.add((person, RDF.type, FOAF.Person))
g.add((person, FOAF.name, Literal("John Doe")))
g.add((person, FOAF.age, Literal(30)))
# Check if triple exists
if (person, FOAF.name, None) in g:
print("Person has a name")
# Get all names
for name in g.objects(person, FOAF.name):
print(f"Name: {name}")
# Remove a triple
g.remove((person, FOAF.age, None))
# Get graph size
print(f"Graph has {len(g)} triples")from rdflib import Graph
g = Graph()
g.parse("data.ttl", format="turtle")
# SPARQL SELECT query
query = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?email WHERE {
?person foaf:name ?name .
?person foaf:mbox ?email .
}
"""
results = g.query(query)
for row in results:
print(f"Name: {row.name}, Email: {row.email}")
# SPARQL CONSTRUCT query
construct_query = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
CONSTRUCT { ?person foaf:name ?name }
WHERE { ?person foaf:name ?name }
"""
new_graph = g.query(construct_query)from rdflib import Graph
g = Graph()
# Parse from different sources
g.parse("http://example.org/data.rdf") # From URL
g.parse("data.ttl", format="turtle") # From file
g.parse(data=rdf_string, format="xml") # From string
# Serialize to different formats
turtle_data = g.serialize(format="turtle")
xml_data = g.serialize(format="xml")
jsonld_data = g.serialize(format="json-ld")
# Serialize to file
g.serialize("output.ttl", format="turtle")from rdflib import Graph, Namespace
from rdflib.namespace import RDF, FOAF
g = Graph()
# Bind custom namespace
EX = Namespace("http://example.org/")
g.bind("ex", EX)
# Use bound namespace in serialization
g.add((EX.person1, RDF.type, FOAF.Person))
turtle = g.serialize(format="turtle")
# Will use 'ex:' prefix in outputfrom rdflib import Graph, URIRef
from rdflib.namespace import RDF, FOAF
g = Graph()
# ... add some data ...
# Iterate over all triples
for s, p, o in g:
print(f"{s} {p} {o}")
# Find all people
for person in g.subjects(RDF.type, FOAF.Person):
print(f"Person: {person}")
# Get all properties of a person
person = URIRef("http://example.org/person/1")
for pred, obj in g.predicate_objects(person):
print(f"{pred}: {obj}")
# Pattern matching with wildcards
for s, p, o in g.triples((None, FOAF.name, None)):
print(f"{s} has name {o}")Install with Tessl CLI
npx tessl i tessl/pypi-rdflib