Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add my own custom attributes to existing built-in Python types? Like a string? [duplicate]

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?

like image 631
jedmao Avatar asked Mar 15 '10 02:03

jedmao


People also ask

How are attributes added to a class in Python?

Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.


1 Answers

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.

like image 103
DasIch Avatar answered Oct 02 '22 02:10

DasIch