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


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