Burathar
4 years ago
5 changed files with 63 additions and 34 deletions
@ -0,0 +1,37 @@
@@ -0,0 +1,37 @@
|
||||
class RecursiveProperty: |
||||
|
||||
def __init__(self, property_key): |
||||
self.property_key = property_key |
||||
|
||||
def config_dict(self, values_only=False): |
||||
# pylint: disable=no-member |
||||
property_key_value = getattr(self, self.property_key) |
||||
if property_key_value is None: |
||||
raise TypeError(f"{self.property_key} cannot be None") |
||||
property_dict = {k: v for k, v in self.__dict__.items() if v is not None} |
||||
property_dict.pop(self.property_key) |
||||
property_dict.pop('property_key') |
||||
if values_only: |
||||
return property_dict |
||||
return {property_key_value : property_dict} |
||||
|
||||
@classmethod |
||||
def _from_dict(cls, property_dict, property_key): |
||||
if property_dict is None: |
||||
return None |
||||
|
||||
# Extract the name |
||||
property_name = [*property_dict][0] |
||||
|
||||
# Step into object |
||||
property_dict = property_dict.get(property_name) |
||||
|
||||
# Add name to dict |
||||
property_dict[property_key] = property_name |
||||
|
||||
# Create empty instance |
||||
recursive_property = cls(property_key) |
||||
|
||||
# Fill instance with dict |
||||
recursive_property.__dict__ = property_dict |
||||
return recursive_property |
Loading…
Reference in new issue