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
No related merge requests found
......@@ -2,18 +2,19 @@
File consists of several classes to model elements and assembly
layers of a composed device.
"""
from __future__ import annotations
import uuid
import json
import operator
from enum import Enum, auto
from typing import List, Dict, Optional
from typing import Any, Optional
from copy import deepcopy
class AggregationLayer(Enum):
"""Describes the levl of aggregation for the objects LegoComponent
and LegoAssembly and provides the 4 applicable layers.
"""Describes the level of aggregation for the objects LegoComponent and LegoAssembly
and provides the 4 applicable layers.
"""
SYSTEM = auto()
......@@ -23,60 +24,48 @@ class AggregationLayer(Enum):
class LegoComponent:
"""
A class for storing information about a single Lego component.
...
"""Information storage for a single Lego component.
Attributes
----------
uuid : UUID
A randomly generated unique identifier for the component.
parent : None | LegoAssembly
The parent of the component. Can be either None or a LegoAssembly object.
layer : AggregationLayer
An enumeration indicating the hierarchy level. For compoennts, this is
COMPONENT by default.
properties : dict
Dictionary that holds all properties of the component that can be saved
in a dictionary format.
uuid (uuid.UUID): A randomly generated unique identifier for the component.
parent (None | LegoAssembly): The parent of the component. None if the
component has no parent.
layer (AggregationLayer): An enumeration indicating the hierarchy level. For
components, this is COMPONENT by default.
properties (dict[str, Any]): dictionary that holds all properties of the
component that can be saved in a dictionary format.
Methods
-------
clone(new_label=None)
Returns a new instance of LegoComponent identical to the current instance.
get_root_assembly()
Returns the top-level assembly in which the component belongs.
to_dict()
Returns the current instance represented as a dictionary.
clone(new_label=None): Returns a new instance of LegoComponent identical to the
current instance.
get_root_assembly(): Returns the top-level assembly in which the component is
contained.
to_dict(): Returns the current instance represented as a dictionary.
"""
def __init__(
self,
label: Optional[str] = None,
datasheet: Optional[dict] = None,
datasheet: Optional[dict[str, Any]] = None,
*more_properties: dict,
**kwargs,
) -> None:
"""
Constructs all the necessary attributes for the LegoComponent object.
Parameters
----------
label : str, optional
The name of the component to add.
datasheet : dict, optional
Metadata describing the component, read from datasheet.
more_properties : tuple of dict, dict
"""Create a LegoComponent object.
Args:
label (str, optional): The name of the component to add. Defaults
to None.
datasheet (dict[str, Any], optional): Metadata describing the component,
read from datasheet. Defaults to None.
more_properties tuple of dict, dict
Additional dictionaries representing custom properties.
kwargs
Arbitrary keyword arguments representing custom properties.
Raises
------
ValueError
If the type of more_properties argument is not a dictionary.
Raises:
ValueError: If the type of more_properties argument is not a dictionary.
"""
self.uuid: uuid.UUID = uuid.uuid4()
self.parent: None | LegoAssembly = None
self.layer: AggregationLayer = AggregationLayer.COMPONENT
......@@ -94,24 +83,20 @@ class LegoComponent:
self.properties[key] = deepcopy(value)
def clone(self, new_label: Optional[str] = None) -> LegoComponent:
"""
Returns a new instance of LegoComponent identical to the current instance.
"""Return a new instance of LegoComponent identical to the current instance.
This method creates a new instance of LegoComponent that is identical to the
current instance with an optional different label.
The assigned uuid changes and elements are copied.
Parameters
----------
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.
Args:
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.
"""
if new_label is None:
new_label = self.properties["label"]
clone = LegoComponent(None, None, deepcopy(self.properties))
......@@ -119,17 +104,15 @@ class LegoComponent:
return clone
def get_root_assembly(self):
"""
Returns the top-level assembly in which the component belongs.
"""Return the top-level assembly in which the component belongs.
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
assigned when a LegoComponent or LegoItem is added to a LegoAssembly object.
Returns
-------
None | LegoAssembly
The root-level LegoAssembly or None if the component has no parent.
Returns:
None | LegoAssembly: The root-level LegoAssembly or None if the component
has no parent.
"""
if self.parent is None:
return None
......@@ -138,17 +121,14 @@ class LegoComponent:
current_assembly = current_assembly.parent
return current_assembly
def to_dict(self) -> Dict:
"""
Returns the current instance represented as a dictionary.
def to_dict(self) -> dict:
"""Return the current instance represented as a dictionary.
This method returns a dictionary representation of the LegoComponent object
suitable for serialization as JSON.
Returns
-------
dict
A dictionary representation of the object.
Returns:
dict[str, Any]: A dictionary representation of the object.
"""
dict_ = {
"uuid": self.uuid,
......@@ -158,16 +138,23 @@ class LegoComponent:
return {"component": dict_}
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.
"""
return self.__repr__()
if self.properties.get("label") is None:
return f"LegoComponent [{self.uuid}]"
return f"LegoComponent {self.properties['label']} [{self.uuid}]"
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['label']} [{self.uuid}]"
return f"LegoComponent({self.properties if self.properties else ""})"
class LegoAssembly:
......@@ -179,8 +166,8 @@ class LegoAssembly:
parent (LegoAssembly or None): The parent assembly containing this one, if any.
properties (dict): Optional properties for the assembly, such as a label.
layer (AggregationLayer): The aggregation layer of the assembly.
components (List[LegoComponent]): The list of contained components.
assemblies (List[LegoAssembly]): The list of contained subassemblies.
components (list[LegoComponent]): The list of contained components.
assemblies (list[LegoAssembly]): The list of contained subassemblies.
"""
def __init__(
......@@ -213,16 +200,16 @@ class LegoAssembly:
raise ValueError(f"Unexpected argument type: {type(properties)}")
for key, value in kwargs.items():
self.properties[key] = deepcopy(value)
self.components: List[LegoComponent] = []
self.assemblies: List[LegoAssembly] = []
self.components: list[LegoComponent] = []
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.
Use add() to handle both components and assemblies.
Args:
component (LegoComponent or List[LegoComponent]):
component (LegoComponent or list[LegoComponent]):
The component or list of components to add.
Raises:
......@@ -251,13 +238,13 @@ class LegoAssembly:
component.parent = self
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.
Use add() to handle both components and assemblies.
Args:
assembly (LegoAssembly or List[LegoAssembly]):
assembly (LegoAssembly or list[LegoAssembly]):
The subassembly or list of subassemblies to add.
Raises:
......@@ -286,14 +273,14 @@ class LegoAssembly:
self.assemblies.append(assembly)
def add(
self, part: LegoAssembly | LegoComponent | List[LegoAssembly | LegoComponent]
self, part: LegoAssembly | LegoComponent | list[LegoAssembly | LegoComponent]
) -> None:
"""
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().
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.
Raises:
......@@ -314,7 +301,7 @@ class LegoAssembly:
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
sub-assemblies), sorted by category.
......@@ -325,7 +312,7 @@ class LegoAssembly:
"""
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
its sub-assemblies.
......@@ -382,7 +369,7 @@ class LegoAssembly:
return True
return False
def to_dict(self) -> Dict:
def to_dict(self) -> dict:
"""
Serializes the current LegoAssembly instance and its descendants into a dict.
......@@ -436,7 +423,7 @@ def print_assembly_tree(root, levels=None):
Args:
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.
"""
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