Skip to content
Snippets Groups Projects
Commit ef65ce39 authored by Tsegelnik Nikita's avatar Tsegelnik Nikita
Browse files

Working on the new implementation of the graphs -- GDGraph

parent d196fd0c
No related branches found
No related tags found
1 merge request!19New version
Pipeline #16659 passed
#!/usr/bin/env python3
from __future__ import annotations
from typing import Any, List, Optional, Sequence, Tuple
import warnings
if __package__ is None or __package__ == "":
# uses current directory visibility
# fixed import error when building documentation
from gdata import GData
else:
# uses current package visibility
from .gdata import GData
class GDNode:
def __init__(self, name: str, data: Any, next: Any = None) -> None:
self.name = name
self.data = data
self.next = next
@classmethod
def from_gdata(cls, data: GData, next: Optional[GData] = None) -> GDNode:
return cls(data.uname(), data, next)
class GDGraph:
"""
Simple directed graph, containing list of all nodes,
references to the top node (only one) and a bottom node (random)
Implemented to the advanced Pattern Matching
"""
def __init__(
self,
nodes: Sequence[Any] = None,
debug: bool = False,
strict: bool = False,
) -> None:
self.debug = debug
self.strict = strict
self.names = []
self.nodes = []
if isinstance(nodes, (List, Tuple)):
self.add_nodes(nodes)
else:
raise ValueError(
"The nodes must be `List` or `Tuple`, "
f"but given '{type(nodes)}'!"
)
def add_nodes(self, nodes: Sequence[Any]) -> None:
for node in nodes:
if isinstance(node, GData):
self.add_node(node, node.uname())
elif isinstance(node, GDNode):
self.add_node(node, node.name)
elif isinstance(node, (List, Tuple)):
self.add_nodes(node)
else:
if self.strict:
raise ValueError(
"In the strict mode the allowed types are `GData` "
f"and `GDNode`, but given '{type(node)}'!"
)
elif self.debug:
warnings.warn(
"The name of the node cannot be determined, "
"so the string representation of the node is used "
"as the name.",
RuntimeWarning,
)
self.add_node(node, node)
def add_node(
self, data: Any, name: Optional[str] = None, next: Any = None
) -> GDNode:
"""
Adding node to the graph
"""
node = (
GDNode.from_gdata(data, next)
if isinstance(data, GData)
else GDNode(name or str(data), data, next)
)
self.nodes.append(node)
return node
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment