Python Forum
Build a dict with class syntax
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Build a dict with class syntax
#2
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()
Reply


Messages In This Thread
Build a dict with class syntax - by Gribouillis - Feb-27-2023, 09:25 AM
RE: Build a dict with class syntax - by Gribouillis - Feb-27-2023, 10:04 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020