10

How do you add a custom method to a built-in python datatype? For example, I'd like to implement one of the solutions from this question but be able to call it as follows:

>>> s = "A   string  with extra   whitespace"
>>> print s.strip_inner()
>>> A string with extra whitespace

So how would I define a custom .strip_inner() string method?

Community
  • 1
  • 1
mwolfe02
  • 23,787
  • 9
  • 91
  • 161
  • possible duplicate of [Extending builtin classes in python](http://stackoverflow.com/questions/352537/extending-builtin-classes-in-python) –  Dec 23 '10 at 14:46

3 Answers3

7

You can't. And you don't need to.

See Extending builtin classes in python for an alternative solution. Subclassing is the way to go here.

Community
  • 1
  • 1
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • You're right. I didn't want to. I wanted to subclass I just couldn't remember what it was called so I couldn't google the solution myself. Thanks. – mwolfe02 Dec 23 '10 at 14:49
  • On closer inspection that is not exactly what I was trying to do (as you say, I can't do *exactly* what I want), but it is certainly a workable solution. – mwolfe02 Dec 23 '10 at 14:54
2

The built-in classes such as str are implemented in C, so you can't manipulate them. What you can do, instead, is extend the str class:

>>> class my_str(str):
...     def strip_inner(self):
...         return re.sub(r'\s{2,}', ' ', s)
... 
>>> s = my_str("A   string  with extra   whitespace")
>>> print s.strip_inner()
A string with extra whitespace
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
moinudin
  • 134,091
  • 45
  • 190
  • 216
1

You can't add methods to built-in classes. But what's wrong with using functions? strip_inner(s) is just fine and pythonic.

If you need polymorphism, then just use if isinstance(obj, type_) to determine what to do, or for something more extensible, use a generic function package, like PEAK-Rules.

Ants Aasma
  • 53,288
  • 15
  • 90
  • 97
  • +1 for the first paragraph and -1 for the second one. As to why function may be better than method see [methods vs. functions](http://stackoverflow.com/questions/967538/) – Piotr Dobrogost Nov 02 '11 at 18:17