Module osbot_utils.graphs.mgraph.MGraph

Expand source code
from typing import List

from osbot_utils.utils.Misc import random_text, lower
from osbot_utils.base_classes.Kwargs_To_Self   import Kwargs_To_Self
from osbot_utils.graphs.mgraph.MGraph__Config  import MGraph__Config
from osbot_utils.graphs.mgraph.MGraph__Edge    import MGraph__Edge
from osbot_utils.graphs.mgraph.MGraph__Node    import MGraph__Node


# todo add support for storing the data in sqlite so that we get the ability to search nodes and edges
class MGraph(Kwargs_To_Self):
    config : MGraph__Config
    edges  : List[MGraph__Edge]
    key    : str
    nodes  : List[MGraph__Node]


    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if not self.key:
            self.key = random_text("mgraph", lowercase=True)                 # make sure there is always a key

    def add_edge(self, from_node, to_node, label=None,attributes=None):
        if self.config.allow_circle_edges is False:
            if from_node == to_node:
                return None
        if self.config.allow_duplicate_edges is False:                          # todo: figure out if there is a more efficient way to do this
            for edge in self.edges:
                if edge.from_node == from_node and edge.to_node == to_node:
                    return None
        new_edge = MGraph__Edge(from_node=from_node, to_node=to_node, label=label, attributes=attributes)
        self.edges.append(new_edge)
        return new_edge

    def add_node(self, key=None, label=None, attributes=None):
        new_node = MGraph__Node(key=key, label=label, attributes=attributes)
        self.nodes.append(new_node)
        return new_node

    def data(self):
        from osbot_utils.graphs.mgraph.MGraph__Data import MGraph__Data
        return MGraph__Data(mgraph=self)

    # def save(self, format='pickle'):
    #     if format == 'pickle':
    #         return pickle_save_to_file(self)

    #todo: add save that return saved object
    # def save(self):
    #     from osbot_utils.graphs.mgraph.MGraph__Serializer import MGraph__Serializer        # due to circular dependency
    #     return MGraph__Serializer(mgraph=self).save()

    def print(self):
        print()
        return self.data().print()

Classes

class MGraph (**kwargs)

A mixin class to strictly assign keyword arguments to pre-defined instance attributes during initialization.

This base class provides an init method that assigns values from keyword arguments to instance attributes. If an attribute with the same name as a key from the kwargs is defined in the class, it will be set to the value from kwargs. If the key does not match any predefined attribute names, an exception is raised.

This behavior enforces strict control over the attributes of instances, ensuring that only predefined attributes can be set at the time of instantiation and avoids silent attribute creation which can lead to bugs in the code.

Usage

class MyConfigurableClass(Kwargs_To_Self): attribute1 = 'default_value' attribute2 = True attribute3 : str attribute4 : list attribute4 : int = 42

# Other methods can be added here

Correctly override default values by passing keyword arguments

instance = MyConfigurableClass(attribute1='new_value', attribute2=False)

This will raise an exception as 'attribute3' is not predefined

instance = MyConfigurableClass(attribute3='invalid_attribute')

this will also assign the default value to any variable that has a type defined. In the example above the default values (mapped by default__kwargs and locals) will be: attribute1 = 'default_value' attribute2 = True attribute3 = '' # default value of str attribute4 = [] # default value of list attribute4 = 42 # defined value in the class

Note

It is important that all attributes which may be set at instantiation are predefined in the class. Failure to do so will result in an exception being raised.

Methods

init(**kwargs): The initializer that handles the assignment of keyword arguments to instance attributes. It enforces strict attribute assignment rules, only allowing attributes that are already defined in the class to be set.

Initialize an instance of the derived class, strictly assigning provided keyword arguments to corresponding instance attributes.

Parameters

**kwargs: Variable length keyword arguments.

Raises

Exception
If a key from kwargs does not correspond to any attribute pre-defined in the class, an exception is raised to prevent setting an undefined attribute.
Expand source code
class MGraph(Kwargs_To_Self):
    config : MGraph__Config
    edges  : List[MGraph__Edge]
    key    : str
    nodes  : List[MGraph__Node]


    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if not self.key:
            self.key = random_text("mgraph", lowercase=True)                 # make sure there is always a key

    def add_edge(self, from_node, to_node, label=None,attributes=None):
        if self.config.allow_circle_edges is False:
            if from_node == to_node:
                return None
        if self.config.allow_duplicate_edges is False:                          # todo: figure out if there is a more efficient way to do this
            for edge in self.edges:
                if edge.from_node == from_node and edge.to_node == to_node:
                    return None
        new_edge = MGraph__Edge(from_node=from_node, to_node=to_node, label=label, attributes=attributes)
        self.edges.append(new_edge)
        return new_edge

    def add_node(self, key=None, label=None, attributes=None):
        new_node = MGraph__Node(key=key, label=label, attributes=attributes)
        self.nodes.append(new_node)
        return new_node

    def data(self):
        from osbot_utils.graphs.mgraph.MGraph__Data import MGraph__Data
        return MGraph__Data(mgraph=self)

    # def save(self, format='pickle'):
    #     if format == 'pickle':
    #         return pickle_save_to_file(self)

    #todo: add save that return saved object
    # def save(self):
    #     from osbot_utils.graphs.mgraph.MGraph__Serializer import MGraph__Serializer        # due to circular dependency
    #     return MGraph__Serializer(mgraph=self).save()

    def print(self):
        print()
        return self.data().print()

Ancestors

Subclasses

Class variables

var configMGraph__Config
var edges : List[MGraph__Edge]
var key : str
var nodes : List[MGraph__Node]

Methods

def add_edge(self, from_node, to_node, label=None, attributes=None)
Expand source code
def add_edge(self, from_node, to_node, label=None,attributes=None):
    if self.config.allow_circle_edges is False:
        if from_node == to_node:
            return None
    if self.config.allow_duplicate_edges is False:                          # todo: figure out if there is a more efficient way to do this
        for edge in self.edges:
            if edge.from_node == from_node and edge.to_node == to_node:
                return None
    new_edge = MGraph__Edge(from_node=from_node, to_node=to_node, label=label, attributes=attributes)
    self.edges.append(new_edge)
    return new_edge
def add_node(self, key=None, label=None, attributes=None)
Expand source code
def add_node(self, key=None, label=None, attributes=None):
    new_node = MGraph__Node(key=key, label=label, attributes=attributes)
    self.nodes.append(new_node)
    return new_node
def data(self)
Expand source code
def data(self):
    from osbot_utils.graphs.mgraph.MGraph__Data import MGraph__Data
    return MGraph__Data(mgraph=self)
def print(self)
Expand source code
def print(self):
    print()
    return self.data().print()

Inherited members