Given how dynamic Python is, I\'ll be shocked if this isn\'t somehow possible:
I would like to change the implementation of sys.stdout.write.
I
Despite Python mostly being a dynamic language, there are native objects types like str, file (including stdout), dict, and list that are actually implemented in low-level C and are completely static:
>>> a = []
>>> a.append = 'something else'
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'list' object attribute 'append' is read-only
>>> a.hello = 3
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'list' object has no attribute 'hello'
>>> a.__dict__ # normal python classes would have this
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'list' object has no attribute '__dict__'
If your object is native C code, your only hope is to use an actual regular class. For your case, like already mentioned, you could do something like:
class NewOut(type(sys.stdout)):
def write(self, *args, **kwargs):
super(NewOut, self).write('The new one was called! ')
super(NewOut, self).write(*args, **kwargs)
sys.stdout = NewOut()
or, to do something similar to your original code:
original_stdoutWrite = sys.stdout.write
class MyClass(object):
pass
sys.stdout = MyClass()
def new_stdoutWrite(*a, **kw):
original_stdoutWrite("The new one was called! ")
original_stdoutWrite(*a, **kw)
sys.stdout.write = new_stdoutWrite