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
#1
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)
Output:
type of somedict is <class 'dict'> {'data': (8, 7, 3), 'foo': <function somedict.foo at 0x7fd44b27e0e0>, 'spam': <function somedict.spam at 0x7fd44b27e170>} foo was called spam said 110
Reply
#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


Forum Jump:

User Panel Messages

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