How to add a method to a python class/object during debug session break in Pycharm?

Viewed 91

Needed to add a proc in my class/object on runtime to execute some code using inner variables and other private class methods (can't provide more details).

Was wondering how to achieve this so arrived at my own solution (provided as the current answer). Is there a better way of doing the same?

1 Answers

Thanks @user2357112. Following code works (executed from debug-evaluator dialog box launched during a debug break):

class someClass(object):
    def __init__(self):
        self.element1 = '1'
    def pre_defined_method (self):
        print('in pre_defined_method - element1: {}'.format(self.element1))

def new_object_bound_method (self):
    print('in new_object_bound_method - element1: {}'.format(self.element1))

from  types import MethodType

obj = someClass()
setattr(obj, 'new_object_bound_method', 
            MethodType(new_object_bound_method, obj))
obj.pre_defined_method()
obj.new_object_bound_method()
obj.pre_defined_method()

try:
    obj2 = someClass()
    obj2.new_object_bound_method()
except Exception as e:
    print('"new_object_bound_method" is only bound to instance "obj" and not class "someClass"')
    print(e)

def new_class_bound_method(self):
    print('in new_class_bound_method - element1: {}'.format(self.element1))

someClass.new_class_bound_method = \
    MethodType(new_class_bound_method, None, someClass)

obj2.new_class_bound_method()

Output is:

in pre_defined_method - element1: 1
in new_object_bound_method - element1: 1
in pre_defined_method - element1: 1
"new_object_bound_method" is only bound to instance "obj" and not class "someClass"
'someClass' object has no attribute 'new_object_bound_method'
in new_class_bound_method - element1: 1
Related