Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make rdflib.term.Node abstract (fixes #2518) #2520

Merged
merged 2 commits into from
Aug 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions rdflib/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ def n3(self) -> str:
"2"^^<http://www.w3.org/2001/XMLSchema#integer>
"3"^^<http://www.w3.org/2001/XMLSchema#integer> )
"""
# type error: "Node" has no attribute "n3"
return "( %s )" % (" ".join([i.n3() for i in self])) # type: ignore[attr-defined]
return "( %s )" % (" ".join([i.n3() for i in self]))

def _get_container(self, index: int) -> Optional[Node]:
"""Gets the first, rest holding node at index."""
Expand Down
15 changes: 6 additions & 9 deletions rdflib/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -1609,10 +1609,9 @@ def update(

return processor.update(update_object, initBindings, initNs, **kwargs)

def n3(self) -> str:
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a little confused. The body of this method is updated to use namespace_manager as a keyword argument on an n3() method; but, this syntax looks like it's specifying namespace_manager as a positional argument.

Could the signature become instead:

def n3(
    self,
    *args: Any,
    namespace_manager: Optional["NamespaceManager"]=None,
    **kwargs: Any,
) -> str: ...

"""Return an n3 identifier for the Graph"""
# type error: "IdentifiedNode" has no attribute "n3"
return "[%s]" % self.identifier.n3() # type: ignore[attr-defined]
Comment on lines -1614 to -1615
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm glad to see these no-attribute issues being addressed.

return "[%s]" % self.identifier.n3(namespace_manager=namespace_manager)

def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]:
return (
Expand Down Expand Up @@ -2591,14 +2590,12 @@ def addN(self: _GraphT, quads: Iterable["_QuadType"]) -> _GraphT: # noqa: N802
)
return self

def n3(self) -> str:
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
"""Return an n3 identifier for the Graph"""
# type error: "IdentifiedNode" has no attribute "n3"
return "{%s}" % self.identifier.n3() # type: ignore[attr-defined]
return "{%s}" % self.identifier.n3(namespace_manager=namespace_manager)

def __str__(self) -> str:
# type error: "IdentifiedNode" has no attribute "n3"
identifier = self.identifier.n3() # type: ignore[attr-defined]
identifier = self.identifier.n3()
label = self.store.__class__.__name__
pattern = (
"{this rdflib.identifier %s;rdflib:storage "
Expand Down Expand Up @@ -2900,7 +2897,7 @@ def parse( # type: ignore[override]
) -> NoReturn: # noqa: N803
raise ModificationException()

def n3(self) -> NoReturn:
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> NoReturn:
raise UnSupportedAggregateOperation()

def __reduce__(self) -> NoReturn:
Expand Down
8 changes: 3 additions & 5 deletions rdflib/plugins/serializers/nt.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,12 @@ def __init__(self, store: Graph):
def _nt_row(triple: _TripleType) -> str:
if isinstance(triple[2], Literal):
return "%s %s %s .\n" % (
# type error: "Node" has no attribute "n3"
triple[0].n3(), # type: ignore[attr-defined]
triple[1].n3(), # type: ignore[attr-defined]
triple[0].n3(),
triple[1].n3(),
_quoteLiteral(triple[2]),
)
else:
# type error: "Node" has no attribute "n3"
return "%s %s %s .\n" % (triple[0].n3(), triple[1].n3(), triple[2].n3()) # type: ignore[attr-defined]
return "%s %s %s .\n" % (triple[0].n3(), triple[1].n3(), triple[2].n3())


def _quoteLiteral(l_: Literal) -> str: # noqa: N802
Expand Down
3 changes: 1 addition & 2 deletions rdflib/plugins/serializers/trig.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ def serialize(
# Show the full graph URI if a prefix for it doesn't already exist
iri = self.getQName(store.identifier, False)
if iri is None:
# type error: "IdentifiedNode" has no attribute "n3"
iri = store.identifier.n3() # type: ignore[attr-defined]
iri = store.identifier.n3()
self.write(self.indent() + "\n%s {" % iri)

self.depth += 1
Expand Down
6 changes: 2 additions & 4 deletions rdflib/plugins/sparql/algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,12 +1006,10 @@ def convert_node_arg(
) -> str:
if isinstance(node_arg, Identifier):
if node_arg in self.aggr_vars.keys():
# type error: "Identifier" has no attribute "n3"
grp_var = self.aggr_vars[node_arg].pop(0).n3() # type: ignore[attr-defined]
grp_var = self.aggr_vars[node_arg].pop(0).n3()
return grp_var
else:
# type error: "Identifier" has no attribute "n3"
return node_arg.n3() # type: ignore[attr-defined]
return node_arg.n3()
elif isinstance(node_arg, CompValue):
return "{" + node_arg.name + "}"
elif isinstance(node_arg, Expr):
Expand Down
3 changes: 1 addition & 2 deletions rdflib/plugins/stores/sparqlstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ def _node_to_sparql(node: "Node") -> str:
"SPARQLStore does not support BNodes! "
"See http://www.w3.org/TR/sparql11-query/#BGPsparqlBNodes"
)
# type error: "Node" has no attribute "n3"
return node.n3() # type: ignore[attr-defined]
return node.n3()


class SPARQLStore(SPARQLConnector, Store):
Expand Down
7 changes: 6 additions & 1 deletion rdflib/term.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
* Numerical Ranges

"""
import abc
import re
from fractions import Fraction

Expand Down Expand Up @@ -128,13 +129,17 @@ def _is_valid_unicode(value: Union[str, bytes]) -> bool:
return True


class Node:
class Node(abc.ABC):
"""
A Node in the Graph.
"""

__slots__ = ()

@abc.abstractmethod
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
...


class Identifier(Node, str): # allow Identifiers to be Nodes in the Graph
"""
Expand Down
6 changes: 3 additions & 3 deletions test/utils/dawg_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ class ManifestEntry:
result_cardinality: Optional[URIRef] = field(init=False)

def __post_init__(self) -> None:
type = self.value(RDF.type, IdentifiedNode)
type = self.value(RDF.type, IdentifiedNode) # type: ignore[type-abstract]
assert type is not None
self.type = type

self.action = self.value(MF.action, IdentifiedNode)
self.result = self.value(MF.result, IdentifiedNode)
self.action = self.value(MF.action, IdentifiedNode) # type: ignore[type-abstract]
self.result = self.value(MF.result, IdentifiedNode) # type: ignore[type-abstract]
self.result_cardinality = self.value(MF.resultCardinality, URIRef)
if self.result_cardinality is not None:
assert self.result_cardinality == MF.LaxCardinality
Expand Down
Loading