0

Lets assume class:

class Something():
    def first(self):
        return None

I need to replace this class with Mock object but I need to call or add nonexisting attribute to it. When I try

fake = flexmock(Something, new_method=lambda:None)

I receive AttributeError.

Is it possible to add non existing attribute or method ?

1 Answers1

1

Adding a non-existing attribute to an object or class is as easy as something.new_attr = some_value or setattr(something, 'new_attr', some_value). To add a non-existing method to an object or class, just call one of the following functions:

def add_method(target, method_name): 
    """add class method to a target class or attach a function to a target object"""
    setattr(target, method_name, types.MethodType(lambda x:x, target))
def add_instance_method(target, method_name):
    """add instance method to a target class"""
    setattr(target, method_name, types.MethodType(lambda x:x, None, target))

Now, add_method(Something, 'new_method') will add a (dummy) class-level 'new_method' to class Something, add_method(something, 'new_method') will add a 'new_method' to object something of type Something(but not for other instances of Something), add_instance_method(Something, 'new_method') will add a instance-level 'new_method' to class Something(i.e. available for all the instances of Something).

Note: the above doesn't work for instances that has not __dict__ attribute(e.g. instance of built-in class object).

Please check the other question on stackoverflow: Adding a Method to an Existing Object Instance

Community
  • 1
  • 1
Hui Zheng
  • 10,084
  • 2
  • 35
  • 40