What is the most common python type to which I can add attributes?

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?

+6
python object types attributes
source share
3 answers

It’s just that the correct answer is indicated, and people don’t need to read all the comments: There is no such type. It was proposed, discussed, and the idea was rejected. Here is the link that aaronasterling sent to a comment where you can read more: http://mail.python.org/pipermail/python-bugs-list/2007-January/036866.html

+4
source share

you have the right idea, but you can make it more general. Or

  tmptype = type('tmptype', (object,) {}) 

or

  class tmptype(object): pass 

Then you can just do

 foo = tmptype() foo.is_valid = lambda: False 

as you wanted to do with object . Thus, you can use the same class for all your needs for dynamic, monochrome fixes.

+6
source share

why do you need to make it complicated? I think the easiest way (and the "standard" way) to do

 class FakeFoo(object): def is_valid(): return False 

Also, using lambda is not good in this context ... take a look at this: http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html is BDFL

etc.

+1
source share

All Articles