Feb-27-2023, 10:04 AM
(This post was last modified: Feb-27-2023, 11:17 AM by Gribouillis.)
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()