Skip to content

Instantly share code, notes, and snippets.

@zekefarwell
Created May 26, 2020 18:37
Show Gist options
  • Save zekefarwell/2aa7f821a18c8e6e034845a8fe992c96 to your computer and use it in GitHub Desktop.
Save zekefarwell/2aa7f821a18c8e6e034845a8fe992c96 to your computer and use it in GitHub Desktop.
Test of tree data structure
import json
class NestedDict(dict):
def __getitem__(self, key):
if key not in self:
return self.setdefault(key, NestedDict())
return self.get(key)
def getpath(self, path):
keys = path.split('.')
node = self
for key in keys:
if isinstance(node, NestedDict):
node = node.get(key)
else:
node = False
return node
def setpath(self, path, value):
keys = path.split('.')
final_key = keys.pop()
node = self
for key in keys:
node = node[key]
node[final_key] = value
class Product:
data = {}
path_defaults = (
('salesChannels.salesChannelName', 'Brightpearl'),
('salesChannels.description.languageCode', 'en'),
('salesChannels.description.format', 'HTML_FRAGMENT'),
('salesChannels.shortDescription.languageCode', 'en'),
('salesChannels.shortDescription.format', 'HTML_FRAGMENT'),
)
path_map = (
('brandId', 'brandId'),
('identity.sku', 'sku'),
('identity.upc', 'upc),'),
('stock.stockTracked', 'stockTracked'),
('stock.weight.magnitude', 'weight'),
('salesChannels.productName', 'name'),
('salesChannels.categories', 'categoryCodes'),
('salesChannels.description.text', 'description'),
('salesChannels.shortDescription.text', 'shortDescription'),
)
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def get_data_tree(self):
tree = NestedDict()
# Populate tree from set attributes
for path, key in self.path_map:
if value := self.data.get(key):
tree.setpath(path, value)
# Populate required defaults where parent node exists
for path, value in self.path_defaults:
parent_path, key = path.rsplit('.', 1)
if node := tree.getpath(parent_path):
node[key] = value
# Convert category list to nested structure
if category_codes := tree.getpath('salesChannels.categories'):
categories = [{'categoryCode': code} for code in category_codes]
tree.setpath('salesChannels.categories', categories)
# Wrap sales channel in a list
if channel := tree.get('salesChannels'):
tree['salesChannels'] = [channel]
return tree
def __getattr__(self, attr):
return self.data.get(attr)
def __setattr__(self, attr, value):
self.data[attr] = value
# These fields are all optional and can be commented out
product = Product(
brandId=456,
sku='BT-87-GK',
upc='498720723578',
stockTracked=True,
weight=2.4,
name="Balsam Hard Shell Jacket",
categoryCodes=[472, 23, 17],
description='The best jacket you will ever wear in your life. You will never wear any other jacket as long as you live',
shortDescription='This jacket is the bomb dot com. You will love it etc, etc, etc.',
)
print(json.dumps(product.get_data_tree()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment