Metaclass (wip) to generate a dictionary

Metaclass (wip) to generate a dictionary

(TODO: I will add it if I can think of any use)

I made a class PreDict (OPreDict) that returns a dictionary when called

How to use

You can do the following:

--Generation --Inheritance --Merge --Owned

Generate

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.

Inheritance

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': {}}

Merge

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'})])

Owned

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)

Ingenuity in how to use Attribute

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

Metaclass (wip) to generate a dictionary
Add a dictionary to MeCab
Code to randomly generate a score
Script to create a Mac dictionary file
How to make a dictionary with a hierarchical structure.
How to generate a Python object from JSON
Generate a MeCab dictionary from Nico Nico Pedia data
I tried to generate a random character string
Automatically generate a polarity dictionary used for sentiment analysis
How to convert a class object to a dictionary with SQLAlchemy
How to write a list / dictionary type of Python3
I tried to automatically generate a password with Python3
How to use dictionary {}
[Morphological analysis] How to add a new dictionary to Mecab
Generate a bash script to add Datadog monitor settings
Access to dictionary fields
Generate a password that is easy to remember with apg
I want to automatically generate a modern metal band name
How to generate a public key from an SSH private key
How to generate a query using the IN operator in Django
How to write a metaclass that supports both python2 and python3
A relatively easy way to insert a NEologd dictionary on Windows-System Dictionary
A quick introduction to pytest-mock
Introduction to dictionary lookup algorithm
Create a dictionary in Python
A road to intermediate Python
A super introduction to Linux
Randomly generate a complete permutation
How to call a function
Upload a file to Dropbox
Send a signal to subprocess
How to hack a terminal
Try to select a language
Add user dictionary to MeCab
Expand a Python nested dictionary to do something like Pandas' MultiIndex
How to check the memory size of a dictionary in Python