Despite the fact that Python is mainly a dynamic language, there are object types such as str , file (including stdout ), dict and list , which are actually implemented in low-level C and are completely static:
>>> a = [] >>> a.append = 'something else' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object attribute 'append' is read-only >>> a.hello = 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'hello' >>> a.__dict__
If your object is native C code, your only hope is to use a real regular class. For your case, as already mentioned, you can 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 source 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
source share