Skip to content
Snippets Groups Projects
Commit 6ee40eab authored by Lamm's avatar Lamm
Browse files

Updated LegoComponent to use Google style docstrings. Modified __str__ and...

Updated LegoComponent to use Google style docstrings. Modified __str__ and __repr__ to be more consistent with typical conventions
parent b3bace71
No related branches found
No related tags found
1 merge request!8Unifying PraDDa and GdD Code Style
...@@ -2,18 +2,19 @@ ...@@ -2,18 +2,19 @@
File consists of several classes to model elements and assembly File consists of several classes to model elements and assembly
layers of a composed device. layers of a composed device.
""" """
from __future__ import annotations from __future__ import annotations
import uuid import uuid
import json import json
import operator import operator
from enum import Enum, auto from enum import Enum, auto
from typing import List, Dict, Optional from typing import Any, Optional
from copy import deepcopy from copy import deepcopy
class AggregationLayer(Enum): class AggregationLayer(Enum):
"""Describes the levl of aggregation for the objects LegoComponent """Describes the level of aggregation for the objects LegoComponent and LegoAssembly
and LegoAssembly and provides the 4 applicable layers. and provides the 4 applicable layers.
""" """
SYSTEM = auto() SYSTEM = auto()
...@@ -23,60 +24,48 @@ class AggregationLayer(Enum): ...@@ -23,60 +24,48 @@ class AggregationLayer(Enum):
class LegoComponent: class LegoComponent:
""" """Information storage for a single Lego component.
A class for storing information about a single Lego component.
...
Attributes Attributes
---------- uuid (uuid.UUID): A randomly generated unique identifier for the component.
uuid : UUID parent (None | LegoAssembly): The parent of the component. None if the
A randomly generated unique identifier for the component. component has no parent.
parent : None | LegoAssembly layer (AggregationLayer): An enumeration indicating the hierarchy level. For
The parent of the component. Can be either None or a LegoAssembly object. components, this is COMPONENT by default.
layer : AggregationLayer properties (dict[str, Any]): dictionary that holds all properties of the
An enumeration indicating the hierarchy level. For compoennts, this is component that can be saved in a dictionary format.
COMPONENT by default.
properties : dict
Dictionary that holds all properties of the component that can be saved
in a dictionary format.
Methods Methods
------- clone(new_label=None): Returns a new instance of LegoComponent identical to the
clone(new_label=None) current instance.
Returns a new instance of LegoComponent identical to the current instance. get_root_assembly(): Returns the top-level assembly in which the component is
get_root_assembly() contained.
Returns the top-level assembly in which the component belongs. to_dict(): Returns the current instance represented as a dictionary.
to_dict()
Returns the current instance represented as a dictionary.
""" """
def __init__( def __init__(
self, self,
label: Optional[str] = None, label: Optional[str] = None,
datasheet: Optional[dict] = None, datasheet: Optional[dict[str, Any]] = None,
*more_properties: dict, *more_properties: dict,
**kwargs, **kwargs,
) -> None: ) -> None:
""" """Create a LegoComponent object.
Constructs all the necessary attributes for the LegoComponent object.
Args:
Parameters label (str, optional): The name of the component to add. Defaults
---------- to None.
label : str, optional datasheet (dict[str, Any], optional): Metadata describing the component,
The name of the component to add. read from datasheet. Defaults to None.
datasheet : dict, optional more_properties tuple of dict, dict
Metadata describing the component, read from datasheet.
more_properties : tuple of dict, dict
Additional dictionaries representing custom properties. Additional dictionaries representing custom properties.
kwargs kwargs
Arbitrary keyword arguments representing custom properties. Arbitrary keyword arguments representing custom properties.
Raises Raises:
------ ValueError: If the type of more_properties argument is not a dictionary.
ValueError
If the type of more_properties argument is not a dictionary.
""" """
self.uuid: uuid.UUID = uuid.uuid4() self.uuid: uuid.UUID = uuid.uuid4()
self.parent: None | LegoAssembly = None self.parent: None | LegoAssembly = None
self.layer: AggregationLayer = AggregationLayer.COMPONENT self.layer: AggregationLayer = AggregationLayer.COMPONENT
...@@ -94,24 +83,20 @@ class LegoComponent: ...@@ -94,24 +83,20 @@ class LegoComponent:
self.properties[key] = deepcopy(value) self.properties[key] = deepcopy(value)
def clone(self, new_label: Optional[str] = None) -> LegoComponent: def clone(self, new_label: Optional[str] = None) -> LegoComponent:
""" """Return a new instance of LegoComponent identical to the current instance.
Returns a new instance of LegoComponent identical to the current instance.
This method creates a new instance of LegoComponent that is identical to the This method creates a new instance of LegoComponent that is identical to the
current instance with an optional different label. current instance with an optional different label.
The assigned uuid changes and elements are copied. The assigned uuid changes and elements are copied.
Parameters Args:
---------- new_label (str, optional): A new label string to use. Defaults to None.
new_label : str, optional
A new label string to use. Defaults to None.
Returns
-------
LegoComponent
A new instance of LegoComponent that is identical to the current instance.
Returns:
LegoComponent: A new instance of LegoComponent that is identical to the
current instance.
""" """
if new_label is None: if new_label is None:
new_label = self.properties["label"] new_label = self.properties["label"]
clone = LegoComponent(None, None, deepcopy(self.properties)) clone = LegoComponent(None, None, deepcopy(self.properties))
...@@ -119,17 +104,15 @@ class LegoComponent: ...@@ -119,17 +104,15 @@ class LegoComponent:
return clone return clone
def get_root_assembly(self): def get_root_assembly(self):
""" """Return the top-level assembly in which the component belongs.
Returns the top-level assembly in which the component belongs.
This method traverses the parent hierarchy of a LegoComponent object until it This method traverses the parent hierarchy of a LegoComponent object until it
finds the root-level LegoAssembly, returning it to the caller. A parent is finds the root-level LegoAssembly, returning it to the caller. A parent is
assigned when a LegoComponent or LegoItem is added to a LegoAssembly object. assigned when a LegoComponent or LegoItem is added to a LegoAssembly object.
Returns Returns:
------- None | LegoAssembly: The root-level LegoAssembly or None if the component
None | LegoAssembly has no parent.
The root-level LegoAssembly or None if the component has no parent.
""" """
if self.parent is None: if self.parent is None:
return None return None
...@@ -138,17 +121,14 @@ class LegoComponent: ...@@ -138,17 +121,14 @@ class LegoComponent:
current_assembly = current_assembly.parent current_assembly = current_assembly.parent
return current_assembly return current_assembly
def to_dict(self) -> Dict: def to_dict(self) -> dict:
""" """Return the current instance represented as a dictionary.
Returns the current instance represented as a dictionary.
This method returns a dictionary representation of the LegoComponent object This method returns a dictionary representation of the LegoComponent object
suitable for serialization as JSON. suitable for serialization as JSON.
Returns Returns:
------- dict[str, Any]: A dictionary representation of the object.
dict
A dictionary representation of the object.
""" """
dict_ = { dict_ = {
"uuid": self.uuid, "uuid": self.uuid,
...@@ -158,16 +138,23 @@ class LegoComponent: ...@@ -158,16 +138,23 @@ class LegoComponent:
return {"component": dict_} return {"component": dict_}
def __str__(self): def __str__(self):
"""Handle the conversion of LegoComponent objects to str objects.
Returns:
str: A string converted from the LegoComponent instance.
""" """
Simple string representation of the object. if self.properties.get("label") is None:
""" return f"LegoComponent [{self.uuid}]"
return self.__repr__() return f"LegoComponent {self.properties['label']} [{self.uuid}]"
def __repr__(self): def __repr__(self):
"""Create a machine-readable representation of the instance.
Returns:
str: A string representing the LegoComponent instance.
""" """
String representation of the object including the component label and UUID.
""" return f"LegoComponent({self.properties if self.properties else ""})"
return f"LegoComponent {self.properties['label']} [{self.uuid}]"
class LegoAssembly: class LegoAssembly:
...@@ -179,8 +166,8 @@ class LegoAssembly: ...@@ -179,8 +166,8 @@ class LegoAssembly:
parent (LegoAssembly or None): The parent assembly containing this one, if any. parent (LegoAssembly or None): The parent assembly containing this one, if any.
properties (dict): Optional properties for the assembly, such as a label. properties (dict): Optional properties for the assembly, such as a label.
layer (AggregationLayer): The aggregation layer of the assembly. layer (AggregationLayer): The aggregation layer of the assembly.
components (List[LegoComponent]): The list of contained components. components (list[LegoComponent]): The list of contained components.
assemblies (List[LegoAssembly]): The list of contained subassemblies. assemblies (list[LegoAssembly]): The list of contained subassemblies.
""" """
def __init__( def __init__(
...@@ -213,16 +200,16 @@ class LegoAssembly: ...@@ -213,16 +200,16 @@ class LegoAssembly:
raise ValueError(f"Unexpected argument type: {type(properties)}") raise ValueError(f"Unexpected argument type: {type(properties)}")
for key, value in kwargs.items(): for key, value in kwargs.items():
self.properties[key] = deepcopy(value) self.properties[key] = deepcopy(value)
self.components: List[LegoComponent] = [] self.components: list[LegoComponent] = []
self.assemblies: List[LegoAssembly] = [] self.assemblies: list[LegoAssembly] = []
def add_component(self, component: LegoComponent | List[LegoComponent]) -> None: def add_component(self, component: LegoComponent | list[LegoComponent]) -> None:
""" """
Adds a Lego component to the current assembly. Adds a Lego component to the current assembly.
Use add() to handle both components and assemblies. Use add() to handle both components and assemblies.
Args: Args:
component (LegoComponent or List[LegoComponent]): component (LegoComponent or list[LegoComponent]):
The component or list of components to add. The component or list of components to add.
Raises: Raises:
...@@ -251,13 +238,13 @@ class LegoAssembly: ...@@ -251,13 +238,13 @@ class LegoAssembly:
component.parent = self component.parent = self
self.components.append(component) self.components.append(component)
def add_assembly(self, assembly: LegoAssembly | List[LegoAssembly]) -> None: def add_assembly(self, assembly: LegoAssembly | list[LegoAssembly]) -> None:
""" """
Adds a subassembly to the current assembly. Adds a subassembly to the current assembly.
Use add() to handle both components and assemblies. Use add() to handle both components and assemblies.
Args: Args:
assembly (LegoAssembly or List[LegoAssembly]): assembly (LegoAssembly or list[LegoAssembly]):
The subassembly or list of subassemblies to add. The subassembly or list of subassemblies to add.
Raises: Raises:
...@@ -286,14 +273,14 @@ class LegoAssembly: ...@@ -286,14 +273,14 @@ class LegoAssembly:
self.assemblies.append(assembly) self.assemblies.append(assembly)
def add( def add(
self, part: LegoAssembly | LegoComponent | List[LegoAssembly | LegoComponent] self, part: LegoAssembly | LegoComponent | list[LegoAssembly | LegoComponent]
) -> None: ) -> None:
""" """
Adds either a Lego component, a subassembly or a (mixed) list of them to the Adds either a Lego component, a subassembly or a (mixed) list of them to the
current assembly. Uses internal functions add_component() and add_assembly(). current assembly. Uses internal functions add_component() and add_assembly().
Args: Args:
part (LegoAssembly or LegoComponent or List[LegoAssembly or LegoComponent]): part (LegoAssembly or LegoComponent or list[LegoAssembly or LegoComponent]):
The part or parts to add. The part or parts to add.
Raises: Raises:
...@@ -314,7 +301,7 @@ class LegoAssembly: ...@@ -314,7 +301,7 @@ class LegoAssembly:
f"Got {type(part).__name__} instead." f"Got {type(part).__name__} instead."
) )
def children(self) -> Dict[str, List[LegoComponent] | List[LegoAssembly]]: def children(self) -> dict[str, list[LegoComponent] | list[LegoAssembly]]:
""" """
Returns a dictionary of the assembly's children (components and Returns a dictionary of the assembly's children (components and
sub-assemblies), sorted by category. sub-assemblies), sorted by category.
...@@ -325,7 +312,7 @@ class LegoAssembly: ...@@ -325,7 +312,7 @@ class LegoAssembly:
""" """
return {"components": self.components, "assemblies": self.assemblies} return {"components": self.components, "assemblies": self.assemblies}
def get_component_list(self, max_depth: int = -1) -> List[LegoComponent]: def get_component_list(self, max_depth: int = -1) -> list[LegoComponent]:
""" """
Gets a full list of all components contained in the assembly or any of Gets a full list of all components contained in the assembly or any of
its sub-assemblies. its sub-assemblies.
...@@ -382,7 +369,7 @@ class LegoAssembly: ...@@ -382,7 +369,7 @@ class LegoAssembly:
return True return True
return False return False
def to_dict(self) -> Dict: def to_dict(self) -> dict:
""" """
Serializes the current LegoAssembly instance and its descendants into a dict. Serializes the current LegoAssembly instance and its descendants into a dict.
...@@ -436,7 +423,7 @@ def print_assembly_tree(root, levels=None): ...@@ -436,7 +423,7 @@ def print_assembly_tree(root, levels=None):
Args: Args:
root (LegoAssembly): The root of the assembly tree to print. root (LegoAssembly): The root of the assembly tree to print.
levels (List[bool]): Internally used by recursion to know where levels (list[bool]): Internally used by recursion to know where
to print vertical connection. Defaults to an empty list. to print vertical connection. Defaults to an empty list.
""" """
if not isinstance(root, LegoAssembly): if not isinstance(root, LegoAssembly):
......
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