Skip to content

# `` container

Classes:

- `Alt` –
- `Bag` –

  Unordered container (no preference order of elements)

- `Container` –

  A class for constructing RDF containers, as per https://www.w3.org/TR/rdf11-mt/#rdf-containers

- `NoElementException` –
- `Seq` –

## `` __all__ `module-attribute`

    __all__ = ['Container', 'Bag', 'Seq', 'Alt', 'NoElementException']

## `` Alt

    Alt(graph, uri, seq=[])

Bases: `Container`

Methods:

- `anyone` –

Source code in `rdflib/container.py`

    239
    240

    def __init__(self, graph, uri, seq=[]):
        Container.__init__(self, graph, uri, seq, "Alt")

### `` anyone

    anyone()

Source code in `rdflib/container.py`

    242
    243
    244
    245
    246
    247
    248

    def anyone(self):
        if len(self) == 0:
            raise NoElementException()
        else:
            p = randint(1, len(self))
            item = self.__getitem__(p)
            return item

## `` Bag

    Bag(graph, uri, seq=[])

Bases: `Container`

Unordered container (no preference order of elements)

Source code in `rdflib/container.py`

    234
    235

    def __init__(self, graph, uri, seq=[]):
        Container.__init__(self, graph, uri, seq, "Bag")

## `` Container

    Container(graph, uri, seq=[], rtype='Bag')

A class for constructing RDF containers, as per https://www.w3.org/TR/rdf11-mt/#rdf-containers

Basic usage, creating a `Bag` and adding to it:

    >>> from rdflib import Graph, BNode, Literal, Bag
    >>> g = Graph()
    >>> b = Bag(g, BNode(), [Literal("One"), Literal("Two"), Literal("Three")])
    >>> print(g.serialize(format="turtle"))
    @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
    <BLANKLINE>
    [] a rdf:Bag ;
        rdf:_1 "One" ;
        rdf:_2 "Two" ;
        rdf:_3 "Three" .
    <BLANKLINE>
    <BLANKLINE>

    >>> # print out an item using an index reference
    >>> print(b[2])
    Two

    >>> # add a new item
    >>> b.append(Literal("Hello")) # doctest: +ELLIPSIS
    <rdflib.container.Bag object at ...>
    >>> print(g.serialize(format="turtle"))
    @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
    <BLANKLINE>
    [] a rdf:Bag ;
        rdf:_1 "One" ;
        rdf:_2 "Two" ;
        rdf:_3 "Three" ;
        rdf:_4 "Hello" .
    <BLANKLINE>
    <BLANKLINE>

Parameters:

- ### `graph`

  –

  a Graph instance

- ### `uri`

  –

  URI or Blank Node of the Container

- ### `seq`

  –

  the elements of the Container

- ### `rtype`

  –

  the type of Container, one of “Bag”, “Seq” or “Alt”

Methods:

- `__delitem__` –

  Removing the item with index key or predicate rdf:_key

- `__getitem__` –

  Returns item of the container at index key

- `__len__` –

  Number of items in container

- `__setitem__` –

  Sets the item at index key or predicate rdf:_key of the container to value

- `append` –

  Adding item to the end of the container

- `append_multiple` –

  Adding multiple elements to the container to the end which are in python list other

- `clear` –

  Removing all elements from the container

- `end` –
- `index` –

  Returns the 1-based numerical index of the item in the container

- `items` –

  Returns a list of all items in the container

- `n3` –
- `type_of_conatiner` –
- `type_of_container` –

Attributes:

- `graph` –
- `uri` –

Source code in `rdflib/container.py`

    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68

    def __init__(self, graph, uri, seq=[], rtype="Bag"):
        """Creates a Container

        Args:
            graph: a Graph instance
            uri: URI or Blank Node of the Container
            seq: the elements of the Container
            rtype: the type of Container, one of "Bag", "Seq" or "Alt"
        """

        self.graph = graph
        self.uri = uri or BNode()
        self._len = 0
        self._rtype = rtype  # rdf:Bag or rdf:Seq or rdf:Alt

        self.append_multiple(seq)

        # adding triple corresponding to container type
        self.graph.add((self.uri, RDF.type, RDF[self._rtype]))

### `` graph `instance-attribute`

    graph = graph

### `` uri `instance-attribute`

    uri = uri or BNode()

### `` __delitem__

    __delitem__(key)

Removing the item with index key or predicate rdf:_key

Source code in `rdflib/container.py`

    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158

    def __delitem__(self, key):
        """Removing the item with index key or predicate rdf:_key"""

        assert isinstance(key, int)
        if key <= 0 or key > len(self):
            raise KeyError(key)

        graph = self.graph
        container = self.uri
        elem_uri = str(RDF) + "_" + str(key)
        graph.remove((container, URIRef(elem_uri), None))
        for j in range(key + 1, len(self) + 1):
            elem_uri = str(RDF) + "_" + str(j)
            v = graph.value(container, URIRef(elem_uri))
            graph.remove((container, URIRef(elem_uri), v))
            elem_uri = str(RDF) + "_" + str(j - 1)
            graph.add((container, URIRef(elem_uri), v))

        self._len -= 1

### `` __getitem__

    __getitem__(key)

Returns item of the container at index key

Source code in `rdflib/container.py`

    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126

    def __getitem__(self, key):
        """Returns item of the container at index key"""

        c = self._get_container()

        assert isinstance(key, int)
        elem_uri = str(RDF) + "_" + str(key)
        if key <= 0 or key > len(self):
            raise KeyError(key)
        v = self.graph.value(c, URIRef(elem_uri))
        if v:
            return v
        else:
            raise KeyError(key)

### `` __len__

    __len__()

Number of items in container

Source code in `rdflib/container.py`

    83
    84
    85
    86

    def __len__(self):
        """Number of items in container"""

        return self._len

### `` __setitem__

    __setitem__(key, value)

Sets the item at index key or predicate rdf:_key of the container to value

Source code in `rdflib/container.py`

    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138

    def __setitem__(self, key, value):
        """Sets the item at index key or predicate rdf:_key of the container to value"""

        assert isinstance(key, int)

        c = self._get_container()
        elem_uri = str(RDF) + "_" + str(key)
        if key <= 0 or key > len(self):
            raise KeyError(key)

        self.graph.set((c, URIRef(elem_uri), value))

### `` append

    append(item)

Adding item to the end of the container

Source code in `rdflib/container.py`

    189
    190
    191
    192
    193
    194
    195
    196
    197
    198

    def append(self, item):
        """Adding item to the end of the container"""

        end = self.end()
        elem_uri = str(RDF) + "_" + str(end + 1)
        container = self.uri
        self.graph.add((container, URIRef(elem_uri), item))
        self._len += 1

        return self

### `` append_multiple

    append_multiple(other)

Adding multiple elements to the container to the end which are in python list other

Source code in `rdflib/container.py`

    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212

    def append_multiple(self, other):
        """Adding multiple elements to the container to the end which are in python list other"""

        end = self.end()  # it should return the last index

        container = self.uri
        for item in other:
            end += 1
            self._len += 1
            elem_uri = str(RDF) + "_" + str(end)
            self.graph.add((container, URIRef(elem_uri), item))

        return self

### `` clear

    clear()

Removing all elements from the container

Source code in `rdflib/container.py`

    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228

    def clear(self):
        """Removing all elements from the container"""

        container = self.uri
        graph = self.graph
        i = 1
        while True:
            elem_uri = str(RDF) + "_" + str(i)
            if (container, URIRef(elem_uri), None) in self.graph:
                graph.remove((container, URIRef(elem_uri), None))
                i += 1
            else:
                break
        self._len = 0
        return self

### `` end

    end()

Source code in `rdflib/container.py`

    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187

    def end(self):  #
        # find end index (1-based) of container

        container = self.uri
        i = 1
        while True:
            elem_uri = str(RDF) + "_" + str(i)

            if (container, URIRef(elem_uri), None) in self.graph:
                i += 1
            else:
                return i - 1

### `` index

    index(item)

Returns the 1-based numerical index of the item in the container

Source code in `rdflib/container.py`

    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111

    def index(self, item):
        """Returns the 1-based numerical index of the item in the container"""

        pred = self.graph.predicates(self.uri, item)
        if not pred:
            raise ValueError("%s is not in %s" % (item, "container"))
        li_index = URIRef(str(RDF) + "_")

        i = None
        for p in pred:
            i = int(p.replace(li_index, ""))
        return i

### `` items

    items()

Returns a list of all items in the container

Source code in `rdflib/container.py`

    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174

    def items(self):
        """Returns a list of all items in the container"""

        l_ = []
        container = self.uri
        i = 1
        while True:
            elem_uri = str(RDF) + "_" + str(i)

            if (container, URIRef(elem_uri), None) in self.graph:
                i += 1
                l_.append(self.graph.value(container, URIRef(elem_uri)))
            else:
                break
        return l_

### `` n3

    n3()

Source code in `rdflib/container.py`

    70
    71
    72
    73
    74
    75
    76

    def n3(self):
        items = []
        for i in range(len(self)):
            v = self[i + 1]
            items.append(v)

        return "( %s )" % " ".join([a.n3() for a in items])

### `` type_of_conatiner

    type_of_conatiner()

Source code in `rdflib/container.py`

    88
    89
    90
    91
    92
    93
    94
    95

    def type_of_conatiner(self):
        warnings.warn(
            "rdflib.container.Container.type_of_conatiner is deprecated. "
            "Use type_of_container method instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return self._rtype

### `` type_of_container

    type_of_container()

Source code in `rdflib/container.py`

    97
    98

    def type_of_container(self):
        return self._rtype

## `` NoElementException

    NoElementException(message='rdf:Alt Container is empty')

Bases: `Exception`

Methods:

- `__str__` –

Attributes:

- `message` –

Source code in `rdflib/container.py`

    277
    278

    def __init__(self, message="rdf:Alt Container is empty"):
        self.message = message

### `` message `instance-attribute`

    message = message

### `` __str__

    __str__()

Source code in `rdflib/container.py`

    280
    281

    def __str__(self):
        return self.message

## `` Seq

    Seq(graph, uri, seq=[])

Bases: `Container`

Methods:

- `add_at_position` –

Source code in `rdflib/container.py`

    252
    253

    def __init__(self, graph, uri, seq=[]):
        Container.__init__(self, graph, uri, seq, "Seq")

### `` add_at_position

    add_at_position(pos, item)

Source code in `rdflib/container.py`

    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273

    def add_at_position(self, pos, item):
        assert isinstance(pos, int)
        if pos <= 0 or pos > len(self) + 1:
            raise ValueError("Invalid Position for inserting element in rdf:Seq")

        if pos == len(self) + 1:
            self.append(item)
        else:
            for j in range(len(self), pos - 1, -1):
                container = self._get_container()
                elem_uri = str(RDF) + "_" + str(j)
                v = self.graph.value(container, URIRef(elem_uri))
                self.graph.remove((container, URIRef(elem_uri), v))
                elem_uri = str(RDF) + "_" + str(j + 1)
                self.graph.add((container, URIRef(elem_uri), v))
            elem_uri_pos = str(RDF) + "_" + str(pos)
            self.graph.add((container, URIRef(elem_uri_pos), item))
            self._len += 1
        return self