The Wild

Can You Monkey Patch Builtin str in Python 3?

· 7 min read · Mammals

In this article
  1. Background: What Monkey Patching Means
  2. How Built-in Types Differ from Pure Python Classes
  3. Why Literal String Operations Are Not Affected
  4. What Actually Works: Patching New Attributes and Methods
  5. Common Problems and Misconceptions
  6. How to Choose: When to Patch vs. Use Alternatives
  7. Safety and Risks
  8. Frequently Asked Questions

Yes, you can monkey patch the built-in str type in Python 3, but only partially and with significant caveats — you can replace attributes and methods on the str class itself, yet you cannot change the behavior of string literals or most internal operations that rely on the C-level implementation. In practice, patching str works for code that explicitly calls the patched method, but it fails for literal expressions like 'hello'.upper() because those are compiled to direct C calls that bypass the Python-level attribute lookup. This article explains exactly what works, what doesn't, and safer alternatives.

Background: What Monkey Patching Means

Monkey patching is the practice of modifying a class or module at runtime, after it has been defined, to change its behavior. In Python, this is usually done by assigning a new function or method to an existing attribute. For example, you can add a method to a class you don't own:

class MyClass:
    pass

def new_method(self):
    return "patched"

MyClass.new_method = new_method

For built-in types like str, int, and list, the same syntax works because they are ordinary classes. However, built-in types are implemented in C (CPython) and have special internal mechanisms that affect how patches are applied and whether they take effect.

How Built-in Types Differ from Pure Python Classes

In CPython, built-in types are defined in C and their methods are stored in a static table called the type's method table. When you access an attribute on an instance, Python first checks the instance's __dict__, then the class's __dict__ (which is a normal dictionary for most classes). For built-in types, the class __dict__ is a mappingproxy — a read-only view — but you can still assign new attributes to the class itself because the type object is mutable. For example:

str.new_method = lambda self: "patched"
print("hello".new_method())  # prints "patched"

This works because str is a class object, and adding a new attribute to it is allowed. However, replacing an existing method like upper is trickier. In CPython, many built-in methods are not stored as normal Python function objects; they are method descriptors implemented in C. Assigning a Python function to str.upper does replace the descriptor in the class dictionary, but the interpreter's bytecode for string literals may not use that dictionary lookup.

Why Literal String Operations Are Not Affected

When you write 'hello'.upper(), the Python compiler generates bytecode that loads the string constant and then calls the upper method via a special opcode (LOAD_METHOD or CALL_METHOD). In CPython, this lookup goes through the type's tp_methods table (the C-level method table) rather than the Python-level class dictionary. The LOAD_METHOD opcode first checks the type's method cache, which is populated from the C table, and only falls back to the Python dictionary if the method is not found there. Since upper exists in the C table, the C implementation is used directly, bypassing any Python-level patch.

In contrast, if you call a method that does not exist in the C table (like a new method you add), the interpreter will find it in the class dictionary and use your Python function. So the rule is: patching existing C methods on built-in types has no effect on literal calls; adding new methods works, but only for explicit attribute access on instances.

What Actually Works: Patching New Attributes and Methods

You can successfully add new methods to str that are not part of the original API. For example:

def shout(self):
    return self.upper() + "!"

str.shout = shout
print("hello".shout())  # prints "HELLO!"

This works because shout is not in the C method table, so the interpreter falls back to the Python class dictionary. Similarly, you can add class-level attributes or even override __repr__? Actually, overriding __repr__ on str does not affect how strings are represented in the REPL or in print() because those use the C-level tp_repr slot. But if you call str.__repr__(obj) explicitly, your patch might be used if you replace it in the class dictionary — though again, literal representations are unaffected.

You can also patch class methods like str.join? Actually, join is an instance method, but you can replace it with a Python function. However, the replacement will only be used when calling the method on a string instance via normal attribute access, not when the interpreter internally calls it (e.g., in string concatenation optimizations).

Common Problems and Misconceptions

A frequent misconception is that patching str will change all string behavior globally. In reality, it only affects Python-level attribute lookups. For example, if you patch str.upper to return "patched", then 'abc'.upper() will still return 'ABC' because the C implementation is used. But if you call str.upper('abc') directly, the interpreter will use the class dictionary and your patch will be applied (since you're explicitly accessing the attribute on the class). This inconsistency is confusing and can lead to subtle bugs.

Another problem is that patching built-in types can break code that relies on the original behavior, especially if the patch is applied globally. It also makes debugging harder because the source of the change is not obvious. Additionally, some Python implementations (like PyPy) may handle built-in patches differently, so code that works on CPython might not work elsewhere.

How to Choose: When to Patch vs. Use Alternatives

Given the limitations, monkey patching str is rarely a good idea. If you need to extend string behavior, consider these alternatives:

  • Subclass str: Create a subclass and override methods. This works reliably because your subclass's methods are used for instances of that subclass, and you can control where the subclass is used.
  • Use a wrapper class: Instead of subclassing, create a class that internally stores a string and delegates methods. This gives you full control and avoids the pitfalls of patching built-ins.
  • Use utility functions: If you just need a specific transformation, write a function that takes a string and returns a modified string. This is the simplest and most explicit approach.
  • Use contextlib or decorators: For temporary changes, you can use a context manager that patches and then restores the original, but this still suffers from the literal-call problem.

If you still want to patch, be aware that it will only affect code that uses explicit attribute access on string instances, not literals or internal operations. You should also consider patching after all modules are loaded, to avoid interfering with imports.

Safety and Risks

Monkey patching built-in types is generally unsafe in production code because it affects the entire process and can lead to unpredictable behavior. It can break third-party libraries that assume the original implementation. It also makes your code harder to maintain and test, since the patch is global and implicit. If you must do it, isolate the patch in a single module and document it clearly. Also, be aware that some Python environments (like those using pypy or jython) may not support patching built-in types at all, or may behave differently.

Another risk is that the patch might not be applied consistently across different Python versions. For example, in older Python 3.x versions, the behavior of method lookup for built-ins may differ slightly. Always test thoroughly on your target Python version.

Frequently Asked Questions

Can I change the behavior of string methods like upper() for all strings?

No, not reliably. In CPython, string literals and most internal operations use the C-level method table, which is not affected by Python-level patches. Even if you assign a new function to str.upper, calls like 'abc'.upper() will still use the original C implementation. Only explicit calls like str.upper('abc') might use your patch, but that's inconsistent.

Is it possible to add a new method to str that works on all strings?

Yes, adding a new method that doesn't exist in the original API works on all string instances. For example, str.shout = lambda self: self.upper() + '!' will make 'hello'.shout() return 'HELLO!'. This works because the interpreter falls back to the Python class dictionary for methods not found in the C table.

What is the difference between patching a built-in type and subclassing it?

Patching modifies the original class globally, affecting all instances. Subclassing creates a new class that inherits the original behavior but allows you to override methods only for instances of the subclass. Subclassing is safer because it doesn't affect existing code, and it works consistently even with literal calls if you use the subclass's constructor.

Why does my patch not work when I call a method on a string literal?

Because string literals are compiled to bytecode that uses the C-level method table directly. The Python interpreter optimizes method calls on literals by looking up the method in the type's C table, bypassing the Python class dictionary. To see your patch, you would need to call the method via the class itself, like str.upper('abc'), but that's rarely done in practice.

Are there any Python implementations where patching built-in types works fully?

In some implementations like PyPy, the behavior may differ because they use a different object model. However, even in PyPy, patching built-in types is not guaranteed to affect all internal operations. The safest approach is to avoid relying on such patches entirely.

Can I use monkey patching to fix a bug in a third-party library that uses str?

It's possible, but risky. If the library uses explicit attribute access on string instances, your patch might work. But if it uses literals or internal C calls, it won't. A better approach is to fork the library or use a wrapper to intercept the calls you need to change.