CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rdflib

RDFLib is a Python library for working with RDF, a simple yet powerful language for representing information.

Pending
Overview
Eval results
Files

namespace-management.mddocs/

Namespace Management

Tools for managing URI namespaces and prefixes. Provides predefined vocabularies and utilities for creating custom namespaces, enabling clean and readable RDF serialization.

Capabilities

Namespace - Custom Namespace Creation

Create custom namespaces for URI construction with attribute or dictionary access.

class Namespace:
    def __init__(self, value: str):
        """
        Create a namespace.
        
        Parameters:
        - value: Base URI for the namespace
        """
    
    def __getattr__(self, name: str) -> URIRef:
        """
        Get URI by attribute access.
        
        Parameters:
        - name: Local name to append
        
        Returns:
        URIRef: Combined URI
        """
    
    def __getitem__(self, key: str) -> URIRef:
        """
        Get URI by dictionary access.
        
        Parameters:
        - key: Local name to append
        
        Returns:
        URIRef: Combined URI
        """
    
    def term(self, name: str) -> URIRef:
        """
        Create a term in this namespace.
        
        Parameters:
        - name: Local name
        
        Returns:
        URIRef: Namespaced URI
        """

NamespaceManager - Namespace Binding Management

Manages namespace prefix bindings for graphs.

class NamespaceManager:
    def __init__(self, graph: Graph):
        """
        Create a namespace manager.
        
        Parameters:
        - graph: Graph to manage namespaces for
        """
    
    def bind(self, prefix: str, namespace: Namespace, override: bool = True, replace: bool = False):
        """
        Bind a prefix to a namespace.
        
        Parameters:
        - prefix: Prefix string (without colon)
        - namespace: Namespace URI or Namespace object
        - override: Whether to override existing binding
        - replace: Whether to replace existing namespace
        """
    
    def compute_qname(self, uri: URIRef, generate: bool = True) -> Tuple[str, URIRef, str]:
        """
        Compute prefix:localname for a URI.
        
        Parameters:
        - uri: URI to compute qname for
        - generate: Whether to generate prefix if none exists
        
        Returns:
        Tuple: (prefix, namespace, localname)
        """
    
    def compute_qname_strict(self, uri: URIRef, generate: bool = True) -> Tuple[str, URIRef, str]:
        """
        Compute qname with strict validation.
        
        Parameters:
        - uri: URI to compute qname for
        - generate: Whether to generate prefix if none exists
        
        Returns:
        Tuple: (prefix, namespace, localname)
        """
    
    def normalizeUri(self, rdfTerm: URIRef) -> str:
        """
        Get normalized (prefixed) representation of URI.
        
        Parameters:
        - rdfTerm: URI to normalize
        
        Returns:
        str: Normalized URI string
        """
    
    def expand_curie(self, curie: str) -> URIRef:
        """
        Expand a CURIE to full URI.
        
        Parameters:
        - curie: Compact URI (prefix:localname)
        
        Returns:
        URIRef: Full URI
        """
    
    def qname(self, uri: URIRef) -> str:
        """
        Get qualified name for URI.
        
        Parameters:
        - uri: URI to get qname for
        
        Returns:
        str: Qualified name (prefix:localname)
        """
    
    def namespaces(self) -> Iterator[Tuple[str, URIRef]]:
        """
        Get all namespace bindings.
        
        Returns:
        Iterator: (prefix, namespace) pairs
        """
    
    def reset(self):
        """Reset to default namespace bindings."""
    
    def __getitem__(self, prefix: str) -> Namespace:
        """
        Get namespace by prefix.
        
        Parameters:
        - prefix: Prefix string
        
        Returns:
        Namespace: Namespace object
        """

Predefined Namespaces

RDFLib provides many predefined namespace objects for common vocabularies:

# Core RDF/RDFS/OWL
RDF: Namespace  # http://www.w3.org/1999/02/22-rdf-syntax-ns#
RDFS: Namespace  # http://www.w3.org/2000/01/rdf-schema#
OWL: Namespace  # http://www.w3.org/2002/07/owl#

# XML Schema Datatypes
XSD: Namespace  # http://www.w3.org/2001/XMLSchema#

# Social Web
FOAF: Namespace  # http://xmlns.com/foaf/0.1/
DOAP: Namespace  # http://usefulinc.com/ns/doap#

# Dublin Core
DC: Namespace  # http://purl.org/dc/elements/1.1/
DCTERMS: Namespace  # http://purl.org/dc/terms/
DCMITYPE: Namespace  # http://purl.org/dc/dcmitype/

# Knowledge Organization
SKOS: Namespace  # http://www.w3.org/2004/02/skos/core#

# Provenance
PROV: Namespace  # http://www.w3.org/ns/prov#

# Dataset/Catalog
DCAT: Namespace  # http://www.w3.org/ns/dcat#
VOID: Namespace  # http://rdfs.org/ns/void#

# Organizations
ORG: Namespace  # http://www.w3.org/ns/org#

# Time
TIME: Namespace  # http://www.w3.org/2006/time#

# Geography
GEO: Namespace  # http://www.w3.org/2003/01/geo/wgs84_pos#

# Schema.org
SDO: Namespace  # http://schema.org/

# SHACL
SH: Namespace  # http://www.w3.org/ns/shacl#

# Sensors
SOSA: Namespace  # http://www.w3.org/ns/sosa/
SSN: Namespace  # http://www.w3.org/ns/ssn/

# Data Cube
QB: Namespace  # http://purl.org/linked-data/cube#

# Profiles
PROF: Namespace  # http://www.w3.org/ns/dx/prof/

# Digital Rights
ODRL2: Namespace  # http://www.w3.org/ns/odrl/2/

# Building/IoT
BRICK: Namespace  # https://brickschema.org/schema/Brick#

# CSV on Web
CSVW: Namespace  # http://www.w3.org/ns/csvw#

# Vocabulary Annotation
VANN: Namespace  # http://purl.org/vocab/vann/

# XML
XMLNS: Namespace  # http://www.w3.org/2000/xmlns/

Usage Examples

Creating Custom Namespaces

from rdflib import Namespace, URIRef

# Create custom namespace
EX = Namespace("http://example.org/")
COMPANY = Namespace("http://company.example.com/vocab#")

# Use attribute access
person_uri = EX.person1  # Creates URIRef("http://example.org/person1")
employee_class = COMPANY.Employee  # Creates URIRef("http://company.example.com/vocab#Employee")

# Use dictionary access
product_uri = EX['product-123']  # Handles special characters

Using Predefined Namespaces

from rdflib import Graph, Literal
from rdflib.namespace import RDF, RDFS, FOAF, XSD

g = Graph()

# Use predefined namespaces
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, datatype=XSD.integer)))
g.add((person, RDFS.label, Literal("A person named John")))

Binding Namespaces to Graphs

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

g = Graph()

# Create and bind custom namespace
EX = Namespace("http://example.org/")
g.bind("ex", EX)
g.bind("foaf", FOAF)

# Add data using bound namespaces
g.add((EX.person1, RDF.type, FOAF.Person))
g.add((EX.person1, FOAF.name, Literal("Alice")))

# Serialization will use prefixes
turtle_output = g.serialize(format="turtle")
print(turtle_output)
# Output will include:
# @prefix ex: <http://example.org/> .
# @prefix foaf: <http://xmlns.com/foaf/0.1/> .

Working with NamespaceManager

from rdflib import Graph, URIRef, Namespace

g = Graph()
nm = g.namespace_manager

# Bind namespaces
EX = Namespace("http://example.org/")
nm.bind("ex", EX)

# Compute qualified names
uri = URIRef("http://example.org/person1")
prefix, namespace, localname = nm.compute_qname(uri)
print(f"Prefix: {prefix}, Namespace: {namespace}, Local: {localname}")

# Get normalized representation
normalized = nm.normalizeUri(uri)
print(f"Normalized: {normalized}")  # "ex:person1"

# Expand CURIE
expanded = nm.expand_curie("ex:person1")
print(f"Expanded: {expanded}")  # URIRef("http://example.org/person1")

Managing Multiple Namespaces

from rdflib import Graph, Namespace, Literal
from rdflib.namespace import RDF, FOAF, DCTERMS

g = Graph()

# Multiple custom namespaces
COMPANY = Namespace("http://company.example.com/")
PROJECT = Namespace("http://projects.example.com/")
SKILL = Namespace("http://skills.example.com/")

# Bind all namespaces
g.bind("company", COMPANY)
g.bind("project", PROJECT)
g.bind("skill", SKILL)
g.bind("dcterms", DCTERMS)

# Use in RDF data
employee = COMPANY.employee123
g.add((employee, RDF.type, FOAF.Person))
g.add((employee, FOAF.name, Literal("Jane Smith")))
g.add((employee, COMPANY.worksOn, PROJECT.webapp_redesign))
g.add((employee, COMPANY.hasSkill, SKILL.python))
g.add((employee, DCTERMS.created, Literal("2023-01-15", datatype=XSD.date)))

# All namespaces will be properly prefixed in serialization

Namespace Utilities

from rdflib import Graph, Namespace
from rdflib.namespace import NamespaceManager

g = Graph()
nm = g.namespace_manager

# List all bound namespaces
for prefix, namespace in nm.namespaces():
    print(f"{prefix}: {namespace}")

# Reset to defaults
nm.reset()

# Check available namespaces after reset
default_namespaces = list(nm.namespaces())
print(f"Default namespaces: {len(default_namespaces)}")

Advanced Namespace Operations

from rdflib import Graph, URIRef, Namespace

# Create graph with custom namespace handling
g = Graph()

# Create hierarchical namespaces
BASE = Namespace("http://example.org/")
PEOPLE = Namespace("http://example.org/people/")
ORGS = Namespace("http://example.org/organizations/")

g.bind("base", BASE)
g.bind("people", PEOPLE)
g.bind("orgs", ORGS)

# Use namespaces for different types
person_uri = PEOPLE.john_doe
org_uri = ORGS.tech_corp
concept_uri = BASE.employee_of

g.add((person_uri, concept_uri, org_uri))

# Compute qnames for different URIs
person_qname = g.namespace_manager.qname(person_uri)
org_qname = g.namespace_manager.qname(org_uri)
concept_qname = g.namespace_manager.qname(concept_uri)

print(f"Person: {person_qname}")    # people:john_doe
print(f"Organization: {org_qname}") # orgs:tech_corp
print(f"Concept: {concept_qname}")  # base:employee_of

Install with Tessl CLI

npx tessl i tessl/pypi-rdflib

docs

dataset-named-graphs.md

graph-operations.md

index.md

namespace-management.md

parsers-serializers.md

rdf-containers-collections.md

rdf-terms.md

sparql-queries-updates.md

utilities-helpers.md

tile.json