Hi,
I have a class Foo with a method isValid. Then I have a method bar() that receives a Foo object and whose behavior depends on whether it is valid or not.
For testing this, I wanted to pass some object to bar whose isValid method returns always False. For other reasons, I cannot create an object of Foo at the time of testing, so I needed an object to fake it. What I first thought of was creating the most general object and adding the attribute isValid to it, for using it as a Foo. But that didn't quite work:
>>> foo = object()
>>> foo.isValid = lambda : False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'isValid'
I found out object doesn't have a __dict__
, so you cannot add attributes to it. At this point, the workaround I am using is creating a type on the fly for this purpose and then creating an object of that type:
>>> tmptype = type('tmptype', (), {'isValid' : lambda self : False})
>>> x = tmptype()
>>> x.isValid()
False
But this seems too long a shot. There must be some readily available general type that I could use for this purpose, but which?