3

I want a dummy object I can instantiate in python and programmatically create attributes for via setattr().

I tried it on the built in object but probably for a good reason that didn't work.

What base object can I use in python for such purposes without actually defining one myself?

user1561108
  • 2,666
  • 9
  • 44
  • 69

3 Answers3

9

You can't use mock = object(), instead just create a Mock derived from object

class Mock(object):
    pass

mock = Mock()

setattr(mock, 'test', 'whatever')
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

If you use a mocking library (e.g. mock) then you get to make assertions about what gets called on the object. You may or may not want to do this.

Katriel
  • 120,462
  • 19
  • 136
  • 170
0

An improvement to Jon Clement's technique, in case you want your mock object to get some attributes upon creation:

class Mock(object):
    def __init__(self, **kwArgs):  # constructor turns keyword args into attributes
       self.__dict__.update(kwArgs)


# now you can do things like this:
options = Mock(verbose=True, debug=False)