2

I am working on a python project and below is what I have:

mystring= 'Hello work'

and I want to write a function that replaces k with a m some thing like below:

def replace_alpha(string):
    return string.replace('k', 'm') # returns Hello worm

I wanted to use Monkey Patching on a string such that I can use it the below way:

string = 'Hello work'
string = string.replace_alpha()
print(string)   # prints Hello worm

instead of:

string = replace_alpha(string)

is this possible? Can I use monkey patching with a built-in rather can I extent the __builtins__?

iam.Carrot
  • 4,976
  • 2
  • 24
  • 71

2 Answers2

4

It is possible with forbiddenfruit library:

from forbiddenfruit import curse

def replace_alpha(string):
    return string.replace('k', 'm')

curse(str, "replace_alpha", replace_alpha)

s = 'Hello work'
print(s.replace_alpha())
georgexsh
  • 15,984
  • 2
  • 37
  • 62
1

It is not possible so easily. You cannot set attributes of immutable str instances or the built-in str class. Without that capability, it is tough change their behaviour. You can, however, subclass str:

class PatchStr(str):
  def replace_alpha(self):
    return self.replace('k', 'm')

string = PatchStr('hello work')
string = string.replace_alpha()
string
# 'hello worm'

I don't think you can get much closer.

user2390182
  • 72,016
  • 6
  • 67
  • 89