Build a dict with class syntax - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: Build a dict with class syntax (/thread-39492.html) |
Build a dict with class syntax - Gribouillis - Feb-27-2023 Using a metaclass, it is easy to distort the class syntax to produce just a dictionary. This could be especially useful to create dictionaries of functions class just_a_dict: def __new__(cls, name, bases, dic): # remove keys ending with two underscores return {k: v for k, v in dic.items() if not k.endswith('__')} class somedict(metaclass=just_a_dict): data = (8, 7, 3) def foo(): print('foo was called') def spam(x, y): print(f'spam said {x + y}') print('type of somedict is', type(somedict)) print(somedict) somedict['foo']() somedict['spam'](10, 100)
RE: Build a dict with class syntax - Gribouillis - Feb-27-2023 Here is a more elaborate version of the just_a_dict metaclass__version__ = '2023-02-26' class just_a_dict: """Metaclass to divert class definitions as dict builders Using this metaclass turns a class definition into a syntax to build dictionaries. Example: class spam(metaclass=just_a_dict): x = 3 y = 'some string' def eggs(): print('eggs') Now spam is only a dictionary (an instance of type dict) {'x': 3, 'y': 'some_string', 'eggs': <function spam.eggs...>} Some keys cannot be used in dictionaries created this way, because these keys are automatically added by Python in class definitions. As of python 3.10, these incompatible_keys are ('__module__', '__qualname__') These keys are available as a tuple: just_a_dict.incompatible_keys """ def __new__(cls, name, bases, dic): for k in cls.incompatible_keys: dic.pop(k, None) return dic def incompatible_keys(): class M: def __new__(c, n, b, d): return tuple(d) class x(metaclass=M): pass return x incompatible_keys = incompatible_keys() |