RDFLib is a Python library for working with RDF, a simple yet powerful language for representing information.
npx @tessl/cli install tessl/pypi-rdflib@7.1.0A comprehensive pure Python library for working with Resource Description Framework (RDF) data. RDFLib provides parsers and serializers for multiple RDF formats, a Graph interface that can be backed by various Store implementations, a complete SPARQL 1.1 implementation, and tools for namespace management and RDF data transformation.
pip install rdflibimport rdflibCommon patterns for working with RDF:
from rdflib import Graph, URIRef, Literal, BNode
from rdflib.namespace import RDF, RDFS, OWL, XSDFor SPARQL queries:
from rdflib import Graph
from rdflib.plugins.sparql import prepareQueryfrom rdflib import Graph, URIRef, Literal, Namespace
from rdflib.namespace import RDF, FOAF
# Create a new graph
g = Graph()
# Define a namespace
EX = Namespace("http://example.org/")
# Add some triples
g.add((EX.person1, RDF.type, FOAF.Person))
g.add((EX.person1, FOAF.name, Literal("John Doe")))
g.add((EX.person1, FOAF.age, Literal(30)))
# Parse RDF from a file or URL
g.parse("http://example.org/data.rdf")
# Query the graph with SPARQL
query = """
SELECT ?name ?age WHERE {
?person foaf:name ?name .
?person foaf:age ?age .
FILTER(?age > 25)
}
"""
results = g.query(query)
for row in results:
print(f"Name: {row.name}, Age: {row.age}")
# Serialize the graph
turtle_data = g.serialize(format='turtle')
print(turtle_data)RDFLib uses a modular architecture with several key components:
This design enables RDFLib to serve as both a simple RDF manipulation library and a foundation for complex semantic web applications.
Core RDF data types representing the fundamental building blocks of RDF: URIs, blank nodes, literals, and variables. These classes provide the foundation for all RDF operations.
class URIRef:
def __init__(self, value: str): ...
def toPython(self): ...
def n3(self): ...
class BNode:
def __init__(self, value: str = None): ...
def skolemize(self, authority: str = None): ...
class Literal:
def __init__(self, lexical_or_value, lang: str = None, datatype: URIRef = None): ...
def toPython(self): ...
@property
def value(self): ...
@property
def datatype(self): ...
@property
def language(self): ...Primary interface for working with RDF data. Provides methods for adding, removing, and querying RDF triples, plus parsing and serialization capabilities across multiple formats.
class Graph:
def __init__(self, store: str = 'default', identifier: Node = None): ...
def add(self, triple: Tuple[Node, Node, Node]): ...
def remove(self, triple: Tuple[Node, Node, Node]): ...
def parse(self, source, format: str = None, **kwargs): ...
def serialize(self, destination=None, format: str = 'xml', **kwargs): ...
def query(self, query_object, **kwargs): ...
def update(self, update_object, **kwargs): ...
def triples(self, triple: Tuple[Node, Node, Node]) -> Iterator: ...RDF 1.1 Dataset implementation for working with collections of named graphs. Provides methods for managing multiple graphs within a single container.
class Dataset:
def __init__(self, store: str = 'default', default_union: bool = False): ...
def graph(self, identifier: Node = None) -> Graph: ...
def add_graph(self, g: Graph): ...
def remove_graph(self, g: Graph): ...
@property
def default_graph(self) -> Graph: ...
def named_graphs(self) -> Iterator[Graph]: ...Tools for managing URI namespaces and prefixes. Provides predefined vocabularies and utilities for creating custom namespaces.
class Namespace:
def __init__(self, value: str): ...
def __getattr__(self, name: str) -> URIRef: ...
def __getitem__(self, key: str) -> URIRef: ...
class NamespaceManager:
def bind(self, prefix: str, namespace: Namespace): ...
def compute_qname(self, uri: URIRef) -> Tuple[str, URIRef, str]: ...
def normalizeUri(self, rdfTerm: URIRef) -> str: ...Complete SPARQL 1.1 implementation supporting SELECT, CONSTRUCT, ASK, DESCRIBE queries and INSERT, DELETE, LOAD, CLEAR updates with extension mechanisms for custom functions.
def prepareQuery(queryString: str, initNs: Dict[str, Namespace] = None): ...
class Result:
def __iter__(self): ...
def serialize(self, format: str = 'xml'): ...
@property
def type(self) -> str: ...
@property
def bindings(self) -> List[Dict]: ...Support for RDF containers (Bag, Seq, Alt) and collections (rdf:List) providing ordered and unordered groupings of RDF resources.
class Container:
def __init__(self, graph: Graph, uri: Node, seq: List = None, rtype: str = "Bag"): ...
def append(self, item: Node): ...
def __getitem__(self, index: int) -> Node: ...
class Collection:
def __init__(self, graph: Graph, uri: Node, seq: List = None): ...
def append(self, item: Node): ...
def clear(self): ...RDF Containers and Collections
Pluggable parsers and serializers supporting RDF/XML, Turtle, N-Triples, N-Quads, TriG, JSON-LD, and other RDF formats through a unified interface.
# Parsing
def parse(source, format: str = None, **kwargs): ...
# Serialization
def serialize(destination=None, format: str = 'xml', **kwargs): ...
# Plugin registration
def register(name: str, kind: str, module_path: str, class_name: str): ...Utility functions for RDF data manipulation, format detection, term conversion, and graph comparison operations.
def to_term(s) -> Node: ...
def from_n3(s: str) -> Node: ...
def first(seq): ...
def uniq(seq): ...
def guess_format(fpath: str) -> str: ...
def isomorphic(graph1: Graph, graph2: Graph) -> bool: ...# Literal normalization setting
NORMALIZE_LITERALS: bool
# SPARQL literal comparison mode
DAWG_LITERAL_COLLATION: bool