How do I add my own custom attributes to existing built-in Python types? Like a string?
Question: 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?](http://stackoverflow.com/questions/4698493/can-i-add-custom-methods-
attributes-to-built-in-python-types)


Answer: 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.

