Created
September 9, 2020 07:17
-
-
Save ImSingee/a433c16ec661e67a33a0b4edf392461f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Example: | |
Input: { | |
"format": "short", | |
"label": "Mbps", | |
"logBase": 1, | |
"max": null, | |
"min": null, | |
"show": true | |
} | |
Output: | |
class SomeObject: | |
def __init(self, format=None, label=None, log_base=None, max=None, min=None, show=None): | |
self.format = format | |
self.label = label | |
self.log_base = log_base | |
self.max = max | |
self.min = min | |
self.show = show | |
def to_dict(self): | |
return { | |
'format': self.format, | |
'label': self.label, | |
'logBase': self.log_base, | |
'max': self.max, | |
'min': self.min, | |
'show': self.show, | |
} | |
""" | |
import re | |
def convert(d: dict): | |
d = {re.sub('([A-Z]+)', r'_\1', k).lower(): k for k in d.keys()} | |
result = "class SomeObject:\n" | |
result += " def __init(self, " + ", ".join([f"{x}=None" for x in d.keys()]) + "):" + "\n" | |
result += "\n".join([f" self.{x} = {x}" for x in d.keys()]) | |
result += "\n\n" | |
result += " def to_dict(self):" + "\n" | |
result += " return {" + "\n" | |
result += "\n".join([f" '{y}': self.{x}," for x, y in d.items()]) + "\n" | |
result += " }" | |
return result | |
if __name__ == "__main__": | |
import json | |
print(convert(json.loads("""{ | |
"format": "short", | |
"label": "Mbps", | |
"logBase": 1, | |
"max": null, | |
"min": null, | |
"show": true | |
}"""))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment