16

I want to do something like this...

def helloWorld():
  print "Hello world!"
str.helloWorld = helloWorld
"foo".helloWorld()

Which would print out "Hello world!"

EDIT: Refer to Can I add custom methods/attributes to built-in Python types?

2

8 Answers 8

25

On CPython you can use ctypes to access the C-API of the interpreter, this way you can change builtin types at runtime.

import ctypes as c


class PyObject_HEAD(c.Structure):
    _fields_ = [
        ('HEAD', c.c_ubyte * (object.__basicsize__ -
                              c.sizeof(c.c_void_p))),
        ('ob_type', c.c_void_p)
    ]

_get_dict = c.pythonapi._PyObject_GetDictPtr
_get_dict.restype = c.POINTER(c.py_object)
_get_dict.argtypes = [c.py_object]

def get_dict(object):
    return _get_dict(object).contents.value

def my_method(self):
    print 'tada'
get_dict(str)['my_method'] = my_method

print ''.my_method()

Although this is interesting to look at and may be quite interesting to figure out... don't ever use it in productive code. Just subclass the builtin type or try to figure out if there is another, may be more pythonic, approach to your problem.

5
  • +1 for the information! I'm curious though, being somewhat new to Python, why you wouldn't want to do this in production..? thanks
    – kodybrown
    Commented Sep 8, 2013 at 14:54
  • You also need to call PyType_Modified after modifying the type's internal dict, in order to clear the MRO attribute cache (or whatever it's called).
    – dlitz
    Commented Nov 5, 2013 at 5:55
  • 3
    there is forbiddenfruit that allows to patch builtin objects on several Python versions.
    – jfs
    Commented Mar 10, 2014 at 23:39
  • This might look like it works, but it actually causes memory corruption, since it bypasses work type.__setattr__ does to maintain internal invariants. For example, this linked code snippet prints the wrong result on the second print and then segfaults on the fourth print. (forbiddenfruit has the same flaws.) Commented Jun 1, 2020 at 17:32
  • class PyObject_HEAD is redundant
    – Joren
    Commented Jul 23, 2021 at 22:12
11

In short, you can't. The Python Way would be to subclass String and work from there.

4
  • 4
    Subclassing builtins is rarely useful. It is almost always better to make functions that operate on them or, in the case of adding some state, make classes with an instance whatever builtin as an attribute. Commented Mar 15, 2010 at 2:14
  • 3
    Subclassing dict to implement a OrderedDict, MultiDict, ImmutableDict or combinations of those is very common. On the other side dict is a collection str is not.
    – DasIch
    Commented Mar 15, 2010 at 22:39
  • @MikeGraham I also think that subclassing builtins is generally a pain (to simply add a new method, etc.). I like how .net extension methods allow the desired behavior in C# and was hoping for something similar in Python..
    – kodybrown
    Commented Sep 8, 2013 at 15:02
  • @wasatchwizard, Since non-tied-to-anything-functions are so common in Python, it makes plenty of sense just to write a function instead. It tends to be a lot easier to read than would be something like an extension method and it is less collision-prone. Commented Sep 11, 2013 at 0:05
6

Here's an idea. It isn't perfect, because it doesn't work for all strings, but it might be helpful.

To set attributes of a string or any other object:

def attr(e,n,v): #will work for any object you feed it, but only that object
    class tmp(type(e)):
        def attr(self,n,v):
            setattr(self,n,v)
            return self
    return tmp(e).attr(n,v)

Here's an example:

>>> def helloWorld():
...     print("hello world!") #python 3
...
>>> a=attr("foo",'heloWorld',helloWorld)
>>> a
'foo'
>>> a.helloWorld()
hello world!
>>> "foo".helloWorld()
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "foo".helloWorld()
AttributeError: 'str' object has no attribute 'helloWorld'
3

Ruby way:

"1".to_i
"1".to_roman 

Python way:

int("1")
Roman("1") # or 
Roman.fromstring("1") 

Where Roman will work on a fixed list of built-in types or anything with a __int__ method.

It is an implementation limitation of CPython that you can't set attributes of built-in/extension types. It is accompanied by cultural preference to avoid monkey-patching in favor of stand-alone functions, custom classes that have as an attribute desired object (or even subclassing in rare cases).

2

To do that you can subclass str.

However, while technically possible, most of the time you are subclassing builtins (such as str) you are looking at a 'has-a' kind of relationship, not 'is-a', therefore composition should be used, not inheritance (meaning you should create a class with a string as an instance attribute, rather than subclass string).

1
  • I'll have to look more into what the hell an instance attribute is, but this sounds very wise.
    – jedmao
    Commented Mar 16, 2010 at 9:43
1

You don't. Use separate dictionaries to "attach" (logically speaking) information to immutable values like strings or numbers (the string or number value as key, the information as corresponding value in the dict).

0

Python does not support that feature.

0
0

You can't, it isn't Pythonic. Monkey-patching isn't a commonly used feature of Python, so for performance -- I believe -- reasons you can't do it on the built it classes or instances thereof.

In fact, it has its own name in Python: duck-punching.

Not the answer you're looking for? Browse other questions tagged or ask your own question.