Skip to content

Simplify code by using Graph.set and Graph.value methods #30

@iosonopersia

Description

@iosonopersia

I just discovered a method of the rdflib.Graph class (which is extensively used by this library) which is the perfect fit for all the entities' setter methods that concern functional properties (e.g. br.has_title).

Graph.set is a convenience method that ensures no more than a single value is set for a specific subject-predicate pair by removing any preexisting values and replacing them with the new one.

Additionally, Graph.value is a convenience method that returns no more than a single value for a specific subject-predicate pair (it raises an error when more than one value exists).

Documentation for the set method.
Documentation for the value method.
Convenience methods for functional properties.

Example of a possible substitution:

    @accepts_only('literal')
    def has_title(self, string: str) -> None:
        self.remove_title()
        self._create_literal(GraphEntity.iri_title, string)

would become something similar to

    @accepts_only('literal')
    def has_title(self, string: str) -> None:
        self.g.set((self.res, GraphEntity.iri_title, Literal(string))

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions