Search code examples
pythonarraysclassmethodsbuilt-in

Add a method to a Built-In Function


How can I add a method to a built-in function?

For example:

Adding push function (Inspired from deque module) to a list

def push(self, element):
    self.insert(0, self)  # First way I could think of

# And adding push to built-in `list`
# Example:

class list:
    def __init__(self, iterable):
        # Do something with iterable
        self.push = push

Not necessarily push method but add any method to any built-in function.
I'm just giving an example.

Thanks!


Solution

  • The fully general answer is that you can't. The built-in stuff is implemented at a lower level than normal classes, so you get a little less freedom for monkey-patching and such.

    Depending on what specifically you're after, there can be workarounds though. For example, if you want a list with some extra methods, you can just subclass it