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__?

2
  • 4
    That's not monkey patching. Monkey patching is the modification of an object from a different scope. Commented Oct 25, 2018 at 7:37
  • @hspandher op stated that he doesnt want to touch __builtins__. Commented Oct 25, 2018 at 7:48

2 Answers 2

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())
Sign up to request clarification or add additional context in comments.

1 Comment

The wording of this library is beautiful :)
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.

4 Comments

string remains "hello work", however.
@AdamSmith which it (the str object the method is called on) does in the OP's code, too. Of course, you have to reassign the return value.
That's not how I understand the requested end state.
@AdamSmith string is just a variable name. The behaviour is the one stated by the OP. string = string.replace_alpha() in the original post indicates that they are not expecting to mutate the object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.