(TODO: I will add it if I can think of any use)
I made a class PreDict (OPreDict) that returns a dictionary when called
You can do the following:
--Generation --Inheritance --Merge --Owned
You can create a dictionary as if it were a class definition.
class Person(OPreDict):
name = Attribute(doc="name")
age = Attribute(doc="age")
print(Person())
# OrderedDict([('name', {'doc': 'name'}), ('age', {'doc': 'age'})])
It also holds the order relation of class definitions.
Of course it can be inherited because it is a class definition.
class Info(PreDict): #Since it is not OPreDict, it does not maintain the order relation.
success = Attribute()
failure = Attribute()
class Info2(Info):
warnings = Attribute()
print(Info2()) # {'failure': {}, 'success': {}, 'warnings': {}}
You can merge multiple classes together.
class Student(OPreDict):
grade = Attribute(doc="School year")
print((Student + Person)())
# OrderedDict([('grade', {'doc': 'School year'}), ('name', {'doc': 'name'}), ('age', {'doc': 'age'})])
You can also generate a class that owns the class.
class Parents(OPreDict):
father = Attribute(Person, doc="father")
mother = Attribute(Person, doc="mother")
import json
print(json.dumps(Parents(), ensure_ascii=False))
{"father": {"name": {"doc": "name"}, "age": {"doc": "age"}, "doc": "father"},
"mother": {"name": {"doc": "name"}, "age": {"doc": "age"}, "doc": "mother"}}
Is it possible to define something like a collection? can not. (TODO: Think about something later)
Until now, Attribute has been used as if it were just a field for dictionary generation.
It seems that Attribute can be made a little more convenient by using functools.partial
.
For example, defining a data type.
from functools import partial
Number = partial(Attribute, type="number")
String = partial(Attribute, type="string")
Then you can get the following json.
class Person(OPreDict):
name = String(doc="name")
age = Number(doc="age")
def pp(D):
print(json.dumps(D, indent=2, ensure_ascii=False))
pp(Person())
# {
# "name": {
# "type": "string",
# "doc": "name"
# },
# "age": {
# "type": "number",
# "doc": "age"
# }
# }
The implementation is below https://gist.github.com/podhmo/5297214c9dc3ba57ec93
Recommended Posts