Using Serd in Python

Overview

Serd is a lightweight C library for working with RDF data. This is the documentation for its Python bindings, which also serves as a gentle introduction to the basics of RDF.

Serd is designed for high-performance or resource-constrained applications, and makes it possible to work with very large documents quickly and/or using minimal memory. In particular, it is dramatically faster than rdflib, though it is less fully-featured and not pure Python.

These bindings expose a relatively Pythonic interface to Serd as the serd module:

import serd

Nodes

Nodes are the basic building blocks of data. Nodes are essentially strings:

>>> print(serd.uri("http://example.org/something"))
http://example.org/something
>>> print(serd.string("hello"))
hello
>>> print(serd.decimal(1234))
1234.0
>>> len(serd.string("hello"))
5

However, nodes also have a type(), and optionally either a datatype() or language().

Representation

The string content of a node as shown above can be ambiguous. For example, it is impossible to tell a URI from a string literal using only their string contents. The to_syntax() method returns a complete representation of a node, in the Turtle syntax by default:

>>> print(serd.uri("http://example.org/something").to_syntax())
<http://example.org/something>
>>> print(serd.string("hello").to_syntax())
"hello"
>>> print(serd.decimal(1234).to_syntax())
1234.0

Note that the representation of a node in some syntax may be the same as the str() contents which are printed, but this is usually not the case. For example, as shown above, URIs and strings are quoted differently in Turtle.

A different syntax can be used by specifying one explicitly:

>>> print(serd.decimal(1234).to_syntax(serd.Syntax.NTRIPLES))
"1234.0"^^<http://www.w3.org/2001/XMLSchema#decimal>

An identical node can be recreated from such a string using the from_syntax() method:

>>> node = serd.decimal(1234)
>>> copy = serd.Node.from_syntax(node.to_syntax()) # Don't actually do this
>>> print(copy)
1234.0

Alternatively, the repr() builtin will return the Python construction representation:

>>> repr(serd.decimal(1234))
'serd.typed_literal("1234.0", "http://www.w3.org/2001/XMLSchema#decimal")'

Any node can be round-tripped to and from a string using these methods. That is, for any node n, both:

serd.Node.from_syntax(world, n.to_syntax())

and:

eval(repr(n))

produce an equivalent node. Using the to_syntax() method is generally recommended, since it uses standard syntax.

Primitives

For convenience, nodes can be constructed from Python primitives by simply passing a value to the constructor:

>>> repr(serd.Node(True))
'serd.boolean(True)'
>>> repr(serd.Node("hello"))
'serd.string("hello")'
>>> repr(serd.Node(1234))
'serd.typed_literal("1234", "http://www.w3.org/2001/XMLSchema#integer")'
>>> repr(serd.Node(12.34))
'serd.typed_literal("1.234E1", "http://www.w3.org/2001/XMLSchema#double")'

Note that it is not possible to construct every type of node this way, and care should be taken to not accidentally construct a string literal where a URI is desired.

Fundamental Constructors

As the above examples suggest, several node constructors are just convenience wrappers for more fundamental ones. All node constructors reduce to one of the following:

serd.plain_literal()

A string with optional language, like "hallo"@de in Turtle.

serd.typed_literal()

A string with optional datatype, like "1.2E9"^^xsd:float in Turtle.

serd.blank()

A blank node ID, like “b42”, or _:b42 in Turtle.

serd.uri()

A URI, like “http://example.org”, or <http://example.org> in Turtle.

Convenience Constructors

serd.string()

A string literal with no language or datatype.

serd.decimal()

An xsd:decimal, like “123.45”.

serd.double()

An xsd:double, like “1.2345E2”.

serd.integer()

An xsd:integer, like “1234567”.

serd.boolean()

An xsd:boolean, like “true” or “false”.

serd.base64()

An xsd:base64Binary, like “aGVsbG8=”.

serd.file_uri()

A file URI, like “file:///doc.ttl”.

Namespaces

It is common to use many URIs that share a common prefix. The Namespace utility class can be used to make code more readable and make mistakes less likely:

>>> eg = serd.Namespace("http://example.org/")
>>> print(eg.thing)
http://example.org/thing

Dictionary syntax can also be used:

>>> print(eg["thing"])
http://example.org/thing

For convenience, namespaces also act like strings in many cases:

>>> print(eg)
http://example.org/
>>> print(eg + "stringeyName")
http://example.org/stringeyName

Note that this class is just a simple syntactic convenience, it does not “remember” names and there is no corresponding C API.

Statements

A Statement is a tuple of either 3 or 4 nodes: the subject, predicate, object, and optional graph. Statements declare that a subject has some property. The predicate identifies the property, and the object is its value.

A statement is a bit like a very simple machine-readable sentence. The “subject” and “object” are as in natural language, and the predicate is like the verb, but more general. For example, we could make a statement in English about your intrepid author:

drobilla has the first name “David”

We can break this statement into 3 pieces like so:

Subject

Predicate

Object

drobilla

has the first name

“David”

To make a Statement out of this, we need to define some URIs. In RDF, the subject and predicate must be resources with an identifier (for example, neither can be a string). Conventionally, predicate names do not start with “has” or similar words, since that would be redundant in this context. So, we assume that http://example.org/drobilla is the URI for drobilla, and http://example.org/firstName has been defined somewhere to be a property with the appropriate meaning, and can make an equivalent Statement:

>>> print(serd.Statement(eg.drobilla, eg.firstName, serd.string("David")))
<http://example.org/drobilla> <http://example.org/firstName> "David"

If you find this terminology confusing, it may help to think in terms of dictionaries instead. For example, the above can be thought of as equivalent to:

drobilla[firstName] = "David"

or:

drobilla.firstName = "David"

Accessing Fields

Statement fields can be accessed via named methods or array indexing:

>>> statement = serd.Statement(eg.s, eg.p, eg.o, eg.g)
>>> print(statement.subject())
http://example.org/s
>>> print(statement[serd.Field.SUBJECT])
http://example.org/s
>>> print(statement[0])
http://example.org/s

Graph

The graph field can be used as a context to distinguish otherwise identical statements. For example, it is often set to the URI of the document that the statement was loaded from:

>>> print(serd.Statement(eg.s, eg.p, eg.o, serd.uri("file:///doc.ttl")))
<http://example.org/s> <http://example.org/p> <http://example.org/o> <file:///doc.ttl>

The graph field is always accessible, but may be None:

>>> triple = serd.Statement(eg.s, eg.p, eg.o)
>>> print(triple.graph())
None
>>> quad = serd.Statement(eg.s, eg.p, eg.o, eg.g)
>>> print(quad.graph())
http://example.org/g

World

So far, we have only used nodes and statements, which are simple independent objects. Higher-level facilities in serd require a World which represents the global library state.

A program typically uses just one world, which can be constructed with no arguments:

world = serd.World()

All “global” library state is handled explicitly via the world. Serd does not contain any static mutable data, allowing it to be used concurrently in several parts of a program, for example in plugins.

If multiple worlds are used in a single program, they must never be mixed: objects “inside” one world can not be used with objects inside another.

Note that the world is not a database, it only manages a small amount of library state for things like configuration and logging.

Generating Blanks

Blank nodes, or simply “blanks”, are used for resources that do not have URIs. Unlike URIs, they are not global identifiers, and only have meaning within their local context (for example, a document). The world provides a method for automatically generating unique blank identifiers:

>>> print(repr(world.get_blank()))
serd.blank("b1")
>>> print(repr(world.get_blank()))
serd.blank("b2")

Model

A Model is an indexed set of statements. A model can be used to store any set of data, from a few statements (for example, a protocol message), to an entire document, to a database with millions of statements.

A model can be constructed and statements inserted manually using the insert() method. Tuple syntax is supported as a shorthand for creating statements:

>>> model = serd.Model(world)
>>> model.insert((eg.s, eg.p, eg.o1))
>>> model.insert((eg.s, eg.p, eg.o2))
>>> model.insert((eg.t, eg.p, eg.o3))

Iterating over the model yields every statement:

>>> for s in model: print(s)
<http://example.org/s> <http://example.org/p> <http://example.org/o1>
<http://example.org/s> <http://example.org/p> <http://example.org/o2>
<http://example.org/t> <http://example.org/p> <http://example.org/o3>

Familiar Pythonic collection operations work as you would expect:

>>> print(len(model))
3
>>> print((eg.s, eg.p, eg.o4) in model)
False
>>> model += (eg.s, eg.p, eg.o4)
>>> print((eg.s, eg.p, eg.o4) in model)
True

Pattern Matching

The ask() method can be used to check if a statement is in a model:

>>> print(model.ask(eg.s, eg.p, eg.o1))
True
>>> print(model.ask(eg.s, eg.p, eg.s))
False

This method is more powerful than the in statement because it also does pattern matching. To check for a pattern, use None as a wildcard:

>>> print(model.ask(eg.s, None, None))
True
>>> print(model.ask(eg.unknown, None, None))
False

The count() method works similarly, but instead returns the number of statements that match the pattern:

>>> print(model.count(eg.s, None, None))
3
>>> print(model.count(eg.unknown, None, None))
0

Getting Values

Sometimes you are only interested in a single node, and it is cumbersome to first search for a statement and then get the node from it. The get() method provides a more convenient way to do this. To get a value, specify a triple pattern where exactly one field is None. If a statement matches, then the node that “fills” the wildcard will be returned:

>>> print(model.get(eg.t, eg.p, None))
http://example.org/o3

If multiple statements match the pattern, then the matching node from an arbitrary statement is returned. It is an error to specify more than one wildcard, excluding the graph.

Erasing Statements

>>> model2 = model.copy()
>>> for s in model2: print(s)
<http://example.org/s> <http://example.org/p> <http://example.org/o1>
<http://example.org/s> <http://example.org/p> <http://example.org/o2>
<http://example.org/s> <http://example.org/p> <http://example.org/o4>
<http://example.org/t> <http://example.org/p> <http://example.org/o3>

Individual statements can be erased by value, again with tuple syntax supported for convenience:

>>> model2.erase((eg.s, eg.p, eg.o1))
>>> for s in model2: print(s)
<http://example.org/s> <http://example.org/p> <http://example.org/o2>
<http://example.org/s> <http://example.org/p> <http://example.org/o4>
<http://example.org/t> <http://example.org/p> <http://example.org/o3>

Many statements can be erased at once by erasing a range:

>>> model2.erase_statements(model2.find(eg.s, None, None))
>>> for s in model2: print(s)
<http://example.org/t> <http://example.org/p> <http://example.org/o3>

Saving Documents

Serd provides simple methods to save an entire model to a file or string, which are similar to functions in the standard Python json module.

A model can be saved to a file with the dump() method:

>>> world.dump(model, "out.ttl")
>>> print(open("out.ttl", "r").read())
<http://example.org/s>
  <http://example.org/p> <http://example.org/o1> ,
    <http://example.org/o2> ,
    <http://example.org/o4> .

<http://example.org/t>
<http://example.org/p> <http://example.org/o3> .

Similarly, a model can be written as a string with the serd.World.dumps() method:

>>> print(world.dumps(model))
<http://example.org/s>
...

Loading Documents

There are also simple methods to load an entire model, again loosely following the standard Python json module.

A model can be loaded from a file with the load() method:

>>> model3 = world.load("out.ttl")
>>> print(model3 == model)
True

By default, the syntax type is determined by the file extension, and statements are stored in (S, P, O) order, so only (s p ?) and (s ? ?) queries will be fast. See the method documentation for how to control things more precisely.

Similarly, a model can be loaded from a string with the loads() method:

>>> ttl = "<{}> <{}> <{}> .".format(eg.s, eg.p, eg.o)
>>> model4 = world.loads(ttl)
>>> for s in model4: print(s)
<http://example.org/s> <http://example.org/p> <http://example.org/o>

File Caret

When data is loaded from a file into a model with the flag STORE_CARETS, each statement will have a caret which describes the file name, line, and column where the statement originated. The caret points to the start of the object node in the statement:

>>> model5 = world.load("out.ttl", model_flags=serd.ModelFlags.STORE_CARETS)
>>> for s in model5: print(s.caret())
out.ttl:2:24
out.ttl:3:2
out.ttl:4:2
out.ttl:7:24

Streaming Data

More advanced input and output can be performed by using the Reader and Writer classes directly. The Reader produces an Event stream which describes the content of the file, and the Writer consumes such a stream and writes syntax.

Reading Files

The reader reads from a source, which should be a FileInput to read from a file. Parsed input is sent to a sink, which is called for each event:

def sink(event):
    print(event)

env = serd.Env(world)
reader = serd.Reader(world, serd.Syntax.TURTLE, env, sink)
with serd.FileInput("out.ttl") as in_stream:
    with reader.open(in_stream) as context:
        context.read_document()

# FIXME: caret
serd.statement_event(serd.Statement(serd.uri("http://example.org/s"), serd.uri("http://example.org/p"), serd.uri("http://example.org/o1"), serd.Caret(serd.string("input"), 2, 24)))
...

For more advanced use cases that keep track of state, the sink can be a custom Sink with a call operator:

class MySink(serd.Sink):
    def __init__(self, world):
        super().__init__(world)
        self.events = []

    def __call__(self, event: serd.Event) -> serd.Status:
        self.events += [event]
        return serd.Status.SUCCESS

env = serd.Env(world)
sink = MySink(world)
reader = serd.Reader(world, serd.Syntax.TURTLE, env, sink)
with serd.FileInput("out.ttl") as in_stream:
    with reader.open(in_stream) as context:
        context.read_document()

print(sink.events[0])

# FIXME: caret
serd.statement_event(serd.Statement(serd.uri("http://example.org/s"), serd.uri("http://example.org/p"), serd.uri("http://example.org/o1"), serd.Caret(serd.string("input"), 2, 24)))

Reading Strings

To read from a string, use a StringInput with the reader:

ttl = """
@base <http://drobilla.net/> .
@prefix eg: <http://example.org/> .
<sw/serd> eg:name "Serd" .
"""

def sink(event):
    print(event)

env = serd.Env(world)
reader = serd.Reader(world, serd.Syntax.TURTLE, env, sink)
with serd.StringInput(ttl) as in_stream:
    with reader.open(in_stream) as context:
        context.read_document()

# FIXME: caret
serd.base_event("http://drobilla.net/")
serd.prefix_event("eg", "http://example.org/")
serd.statement_event(serd.Statement(serd.uri("http://drobilla.net/sw/serd"), serd.uri("http://example.org/name"), serd.string("Serd"), serd.Caret(serd.string("input"), 4, 19)))

Reading into a Model

To read new data into an existing model, send it to the sink returned by inserter():

ttl = """
@prefix eg: <http://example.org/> .
eg:newSubject eg:p eg:o .
"""

env = serd.Env(world)
sink = model.inserter(env)
reader = serd.Reader(world, serd.Syntax.TURTLE, env, sink)

with serd.StringInput(ttl) as in_stream:
    with reader.open(in_stream) as context:
        context.read_document()

for s in model: print(s)
<http://example.org/newSubject> <http://example.org/p> <http://example.org/o>
<http://example.org/s> <http://example.org/p> <http://example.org/o1>
<http://example.org/s> <http://example.org/p> <http://example.org/o2>
<http://example.org/s> <http://example.org/p> <http://example.org/o4>
<http://example.org/t> <http://example.org/p> <http://example.org/o3>

Writing Files

env = serd.Env(world)
with serd.FileOutput("written.ttl") as out_stream:
    writer = serd.Writer(world, serd.Syntax.TURTLE, env, out_stream)
    st = model.all().write(writer.sink(), 0)
    writer.finish()
print(open("written.ttl", "r").read())
<http://example.org/newSubject>
  <http://example.org/p> <http://example.org/o> .

<http://example.org/s>
  <http://example.org/p> <http://example.org/o1> ,
    <http://example.org/o2> ,
    <http://example.org/o4> .

<http://example.org/t>
  <http://example.org/p> <http://example.org/o3> .

API Reference

A lightweight library for working with RDF data.

class serd.Caret

The origin of a statement in a document.

column() int

Return the zero-relative column number in the line.

line() int

Return the one-relative line number in the document.

name() Node

Return the document name.

This is typically a file URI, but may be a descriptive string node for statements that originate from strings or streams.

class serd.Cursor

A range of statements in a model.

This class is iterable so it can be used like a collection. For example, serd.Model.all() returns a range, so all the statements in a model can be printed like so:

for statement in model.all():
    print(statement)

A range is “truthy” if it is non-empty.

empty() bool

Return true iff there are no statements in this range.

write(sink: SinkBase, flags: DescribeFlags) Status

Write this range to sink.

The serialisation style can be controlled with flags. The default is to write statements in an order suited for pretty-printing with Turtle or TriG with as many objects written inline as possible. If DescribeFlags.NO_INLINE_OBJECTS is given, a simple sorted stream is written instead, which is significantly faster since no searching is required, but can result in ugly output for Turtle or Trig.

class serd.DescribeFlags(value)

Flags that control the style of a model serialisation.

NO_INLINE_OBJECTS = 1
class serd.Env

Lexical environment for abbreviating and expanding URIs.

base_uri() Node

Return the current base URI.

expand(node: Node) Node

Expand node, transforming CURIEs into URIs

If node is a relative URI reference, it is expanded to a full URI if possible. If node is a literal, its datatype is expanded if necessary. If node is a CURIE, it is expanded to a full URI if possible.

Returns None if node can not be expanded.

set_base_uri(uri) Status

Set the current base URI.

set_prefix(name, uri: Node) Status

Set a namespace prefix.

A namespace prefix is used to expand CURIE nodes, for example, with the prefix “xsd” set to “http://www.w3.org/2001/XMLSchema#”, “xsd:decimal” will expand to “http://www.w3.org/2001/XMLSchema#decimal”.

write_prefixes(sink: SinkBase) Status

Write all prefixes to sink.

class serd.Event

An event in a data stream.

Streams of data are represented as a series of events. Events represent everything that can occur in an RDF document, and are used to plumb together different components. For example, when parsing a document, a reader emits a stream of events which can be sent to a writer to rewrite the document, or to an inserter to build a model in memory.

flags() StatementFlags
name() Node
node() Node
statement() StatementFlags
type() EventType
uri() Node
class serd.EventType(value)

The type of a serd.Event.

BASE = 1
END = 4
PREFIX = 2
STATEMENT = 3
class serd.Field(value)

Index of a statement in a field.

GRAPH = 3
OBJECT = 2
PREDICATE = 1
SUBJECT = 0
class serd.FileInput

A byte source for text input that reads from a file.

close()
class serd.FileOutput

An output stream that writes to a file.

close()
class serd.InputStream

A source for bytes that provides text input.

This is only a base class, use StringInput or FileInput instead.

close()
class serd.Model

An indexed set of statements.

all() Cursor

Return a range of all statements in the model in SPO order.

ask(s: Node, p: Node, o: Node, g: Node) bool

Return true iff the model contains a statement matching a pattern.

None can be used as a wildcard which matches any node.

clear() None

Remove everything from this model.

copy() Model

Return a deep copy of this model.

count(s: Node, p: Node, o: Node, g: Node) int

Return the number of statements in the model that match a pattern.

None can be used as a wildcard which matches any node.

default_order() StatementOrder

Get the default statement order of this model.

empty() bool

Return true iff there are no statements in this model.

erase(arg) Status

Erase a statement from the model.

The argument can be a statement, tuple of nodes, or a cursor.

erase_statements(cursor: Cursor) Status

Erase a range of statements from the model.

find(subject: Node, predicate: Node, object: Node, graph: Node) Cursor

Search for statements that match a pattern.

Returns a cursor that points to the first match, or the end if no matches were found.

flags() ModelFlags

Get the flags enabled on this model.

get(subject: Node, predicate: Node, object: Node, graph: Node) Node

Search for a single node that matches a pattern.

Exactly one of subject, predicate, or object must be None. This function is mainly useful for predicates that only have one value.

Returns the first matching node, or None if no matches are found.

insert(arg) None

Insert a statement into this model.

insert_statements(range: Cursor) None

Insert a range of statements into this model.

inserter(env: Env, default_graph: Node) Sink

Return a sink that will insert into this model when written to.

ordered(order: StatementOrder) Cursor

Return a range of all statements in the model in a given order.

size() int

Return the number of statements stored in this model.

world() World

Get the world associated with this model.

class serd.ModelFlags(value)

Flags that control model storage and indexing.

STORE_CARETS = 2
STORE_GRAPHS = 1
class serd.Namespace(prefix)

Namespace prefix.

Use attribute syntax to easily create URIs within this namespace, for example:

>>> world = lilv.World()
>>> ns = Namespace(world, "http://example.org/")
>>> print(ns.foo)
http://example.org/foo
name(uri)
class serd.Namespaces(**kwargs)
class serd.Node

An RDF node.

datatype() Node

Return the datatype of this literal, or None.

The returned node is always a URI, typically something like serd.uri(“http://www.w3.org/2001/XMLSchema#decimal”).

static from_syntax(string: unicode, syntax: Syntax, env: Env)

Return a new node created from a string.

The string must be a single node in the given syntax, as returned by serd.Node.to_syntax().

language() Node

Return the language of this literal, or None.

The returned node is always a string, typically something like serd.string(“en”).

string_view()
to_syntax(syntax: Syntax, env: Env) unicode

Return a string representation of this node in a syntax.

The returned string represents that node as if written as an object in the given syntax, without any extra quoting or punctuation. The syntax should be either TURTLE or NTRIPLES (the others are redundant). Note that namespaced (CURIE) nodes and relative URIs can not be expressed in NTriples.

Passing the returned string to Node.from_syntax() will produce a node equivalent to this one.

type() NodeType

Return the type of this node.

This returns the fundamental “kind” of the node, for example NodeType.URI or NodeType.LITERAL. Note that this is different than the optional datatype URI of a literal node, which, for example, states that a literal is an integer or a double.

class serd.NodeFlag(value)

Flags that describe the details of a node.

HAS_DATATYPE = 2
HAS_LANGUAGE = 4
IS_LONG = 1
class serd.NodeType(value)

Type of a node

An RDF node, in the abstract sense, can be either a resource, literal, or a blank. This type is more precise, because syntactically there are two ways to refer to a resource (by URI or CURIE). Serd also has support for variable nodes to support some features, which are not RDF nodes.

There are also two ways to refer to a blank node in syntax (by ID or anonymously), but this is handled by statement flags rather than distinct node types.

BLANK = 4
CURIE = 3
LITERAL = 1
URI = 2
VARIABLE = 5
class serd.OutputStream

An output stream that receives bytes.

This is only a base class, use StringOutput or FileOutput instead.

close()
class serd.ReadContext(reader, source)

Context manager for a scoped read.

read_chunk() None

Read a single “chunk” of data during an incremental read.

This function will read a single top level description, and return. This may be a directive, statement, or several statements; essentially it reads until a ‘.’ is encountered. This is particularly useful for reading directly from a pipe or socket.

read_document() None

Read a complete document from the source.

This function will continue pulling from the source until a complete document has been read. Note that this may block when used with streams, for incremental reading use serd_reader_read_chunk().

class serd.Reader

Streaming parser that reads a text stream and writes to a sink.

serd.Reader(world: serd.World, syntax: serd.Syntax, env: serd.Env, sink, flags: serd.ReaderFlags = serd.ReaderFlags(0), stack_size: int = 4096)

Construct a new reader.

The sink can be either a serd.Sink, a built-in sink (for example, from serd.Writer.sink() or serd.Model.inserter()), or a function that takes a serd.Event and returns a serd.Status.

finish() Status

Finish reading from the source.

This should be called before starting to read from another source. Finish reading from the source.

open(input_stream) ReadContext

Return a scoped read context.

read_chunk() Status

Read a single “chunk” of data during an incremental read.

This function will read a single top level description, and return. This may be a directive, statement, or several statements; essentially it reads until a ‘.’ is encountered. This is particularly useful for reading directly from a pipe or socket.

read_document() Status

Read a complete document from the source.

This function will continue pulling from the source until a complete document has been read. Note that this may block when used with streams, for incremental reading use serd_reader_read_chunk().

start(input_stream: InputStream, input_name: Node, block_size: int) Status

Prepare to read from an input stream.

class serd.ReaderFlags(value)

Reader support options.

READ_LAX = 1
READ_VARIABLES = 2
exception serd.SerdError(status: Status, message: unicode)

An exception thrown by serd.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class serd.Sink
on_event(event: Event) Status
class serd.SinkBase

Base class for any Sink (not for direct use).

class serd.SinkView
write_base(uri) Status

Set the base URI.

write_event(event: Event) Status

Send an event to the sink.

write_prefix(name, uri) Status

Set a namespace prefix.

write_statement(statement, flags: StatementFlags) Status

Write a statement.

class serd.Statement

An RDF statement.

serd.serd.Statement(subject: serd.Node, predicate: serd.Node, object: serd.Node, graph: serd.Node = None, caret: serd.Caret = None)

Construct a new statement.

caret() Caret

Return the file location this statement came from, or None.

graph() Node

Return the graph node in this statement.

matches(s: Node, p: Node, o: Node, g: Node)

Return true iff this statement matches the given pattern.

Nodes match if they are equivalent, or if one of them is NULL. The statement matches if every node matches.

node(field: Field) Node

Return a node in this statement.

object() Node

Return the object node in this statement.

predicate() Node

Return the predicate node of this statement.

subject() Node

Return the subject node of this statement.

class serd.StatementFlags(value)

Flags indicating inline abbreviation information for a statement.

ANON_O = 16
ANON_S = 8
EMPTY_G = 4
EMPTY_O = 2
EMPTY_S = 1
LIST_O = 64
LIST_S = 32
TERSE_O = 256
TERSE_S = 128
class serd.StatementOrder(value)

Statement ordering.

GOPS = 8
GOSP = 9
GPOS = 11
GPSO = 10
GSOP = 7
GSPO = 6
OPS = 2
OSP = 3
POS = 5
PSO = 4
SOP = 1
SPO = 0
class serd.Status(value)

Return status code.

BAD_ALLOC = 9
BAD_ARG = 6
BAD_CALL = 15
BAD_CURIE = 8
BAD_CURSOR = 21
BAD_DATA = 18
BAD_EVENT = 16
BAD_INDEX = 22
BAD_LABEL = 7
BAD_LITERAL = 19
BAD_PATTERN = 20
BAD_READ = 10
BAD_STACK = 13
BAD_STREAM = 12
BAD_SYNTAX = 5
BAD_TEXT = 14
BAD_URI = 17
BAD_WRITE = 11
FAILURE = 1
NO_DATA = 2
OVERFLOW = 3
SUCCESS = 0
UNKNOWN_ERROR = 4
class serd.StringInput

A byte source for text input that reads from a string.

close()
class serd.StringOutput
close()
output() unicode
class serd.Syntax(value)

RDF syntax type.

EMPTY = 0
NQUADS = 3
NTRIPLES = 2
TRIG = 4
TURTLE = 1
class serd.World

Global library state.

dump(model: Model, path: unicode, syntax: Syntax, writer_flags: WriterFlags, describe_flags: DescribeFlags, env: Env) None

Write a model to a file.

dumps(model: Model, syntax: Syntax, writer_flags: WriterFlags, describe_flags: DescribeFlags, env: Env) unicode

Write a model to a string and return it.

file_sink(path: unicode, env: Env, syntax: Syntax, flags: WriterFlags, block_size: int)

Return a scoped context manager for writing to a file.

This is for use with ‘with’ statements, for example:

with world.file_sink("output.ttl", serd.Syntax.TURTLE) as sink:
    sink.write_base("http://example.org/")
get_blank() Node

Return a unique blank node.

load(path: unicode, syntax: Syntax, reader_flags: ReaderFlags, default_order: StatementOrder, model_flags: ModelFlags, default_graph: Node, stack_size: int) Model

Load a model from a file and return it.

loads(s: unicode, base_uri: Node, syntax: Syntax, reader_flags: ReaderFlags, model_flags: ModelFlags, default_graph: Node, stack_size: int) Model

Load a model from a string and return it.

read_file(path: unicode, sink, syntax: Syntax, reader_flags: ReaderFlags, env: Env, stack_size: int)

Read a file by streaming events to a sink.

read_string(s: unicode, sink, syntax: Syntax, reader_flags: ReaderFlags, env: Env, stack_size: int)

Read a string by streaming events to a sink.

class serd.Writer

Streaming writer that emits text as it receives events.

finish() Status

Finish a write.

This flushes any pending output, for example terminating punctuation, so that the output is a complete document.

set_root_uri(uri: unicode) Status

Set the current root URI.

The root URI should be a prefix of the base URI. The path of the root URI is the highest path any relative up-reference can refer to. For example, with root <file:///foo/root> and base <file:///foo/root/base>, <file:///foo/root> will be written as <../>, but <file:///foo> will be written non-relatively as <file:///foo>. If the root is not explicitly set, it defaults to the base URI, so no up-references will be created at all.

sink() SinkView

Return a sink interface that emits statements via this writer.

class serd.WriterFlags(value)

Writer style options.

These flags allow more precise control of writer output style. Note that some options are only supported for some syntaxes, for example, NTriples does not support abbreviation and is always ASCII.

WRITE_ASCII = 1
WRITE_LAX = 4
WRITE_TERSE = 2
serd.base64(buf) Node
serd.base_event(base_uri)

Return an event that sets the base URI.

serd.blank(s: unicode) Node
serd.boolean(b: bool) Node
serd.decimal(d: float) Node
serd.double(d: float) Node
serd.end_event(node)

Return an event that ends an anonymous node description.

serd.file_uri(path: unicode, hostname: unicode = '') Node
serd.guess_syntax(filename: unicode) Syntax

Guess a syntax from a filename.

This uses the file extension to guess the syntax of a file.

Returns:

A syntax, or Syntax.EMPTY if the name is not recognized.

serd.integer(i: int) Node
serd.plain_literal(s: unicode, lang: unicode = None) Node
serd.prefix_event(name, namespace_uri)

Return an event that sets a namespace prefix.

serd.statement_event(statement, flags: ~serd.StatementFlags = StatementFlags.None)

Return an event that represents a statement.

serd.strerror(status: Status) unicode

Return a string describing a status code.

serd.string(s: unicode) Node
serd.syntax_by_name(name: unicode) Syntax

Get a syntax by name.

Case-insensitive, supports “Turtle”, “NTriples”, “NQuads”, and “TriG”.

Returns:

A syntax, or Syntax.EMPTY if the name is not recognized.

serd.syntax_has_graphs(syntax: Syntax) bool

Return whether a syntax can represent multiple graphs.

Returns:

True for Syntax.NQUADS and Syntax.TRIG, False otherwise.

serd.typed_literal(s: unicode, datatype) Node
serd.uri(s: unicode) Node
serd.variable(s: unicode) Node

Index Module Index