clarete / forbiddenfruit

Patch built-in python objects
https://clarete.li/forbiddenfruit/
GNU General Public License v3.0
826 stars 52 forks source link

Add class method to dict? #76

Closed bscully27 closed 2 months ago

bscully27 commented 2 months ago

Is it possible to add a class method to python 3.8+ dictionaries?

Goal: dict.keys() or dict.my_added_method() to return list(dict.keys()) for indexing.

My failed attempt:

from forbiddenfruit import curse

def attempt(self):
    return list(self.keys())
curse(dict, "my_keys", classmethod(attempt))

d = dict(test=1)
d.my_keys()
fabiomcosta commented 2 months ago

Hi it sounds like what you are looking for is a method on the dict class instances and not a class method.

Try:

from forbiddenfruit import curse

def attempt(self):
    return list(self.keys())
curse(dict, "my_keys", attempt)

d = dict(test=1)
d.my_keys()
bscully27 commented 2 months ago

Perfect! Thank you.
This repo is very cool