I have a Foo class with the isValid method. Then I have a bar () method that gets a Foo object and whose behavior depends on whether it really is or not.
To test this, I wanted to pass some object to bar, whose isValid method always returns False. For other reasons, I cannot create a Foo object during testing, so I needed an object to fake. I first thought of creating the most general object and adding the isValid attribute to it, to use it as 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 that the object does not have __dict__ , so you cannot add attributes to it. At this point, the workaround that I use creates an on-the-fly type for this, and then creates an object of this type:
>>> tmptype = type('tmptype', (), {'isValid' : lambda self : False}) >>> x = tmptype() >>> x.isValid() False
But that seems like a too long shot. There should be some easily accessible generic type that I could use for this purpose, but which one?
python object types attributes
ricab
source share