0

This might be a long shot but I thought I would try anyway.

Is there anyway to get a class to act like a NoneType when it isn't one?

Lets say I have this object in a third party API that I can't change but I can monkey patch onto. Most of the methods can return this object at same stage. This object is the same as None, as in they decided to use their own custom type to mean the same thing as None.

Is it possible at all for me to monkey patch this type so that it will act like None when checked:

value = SpecialNoneClass()
if value is None:
   print foobar 
Nathan W
  • 54,475
  • 27
  • 99
  • 146
  • You can, but you'll have to implement a `__getattr__` for your class which returns `None`. – Torxed Aug 13 '13 at 11:49
  • That is fine. I can do that. – Nathan W Aug 13 '13 at 11:50
  • See this question just a few hours old: http://stackoverflow.com/questions/18204227/accessing-an-objects-attribute-inside-setattr#comment26682610_18204227 – Torxed Aug 13 '13 at 11:50
  • 1
    possible duplicate of [python: class override "is" behavior](http://stackoverflow.com/questions/3993239/python-class-override-is-behavior) – Ignacio Vazquez-Abrams Aug 13 '13 at 11:53
  • Not really a duplicate, considering that post ment to replace `is` and not a object type. – Torxed Aug 13 '13 at 11:54
  • @Torxed: No, that post is about hooking *into* the `is` operator and make it return `True` for something that is not the same object as the other operand. Which is what the OP is trying to do here. – Martijn Pieters Aug 13 '13 at 11:55

1 Answers1

3

No you cannot, because is tests for identity, not equality. The value reference has to point to the same object as None.

None is a singleton object, and None is a keyword in Python 3, so you cannot make None refer to another object either.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I guess the best I can do is implement `__nonzero__` and return `False` – Nathan W Aug 13 '13 at 12:01
  • That is a better bet; or test against *that* object with `is`: `if value is SpecialNoneClass`. If they are using it as a singleton that'll work just fine. – Martijn Pieters Aug 13 '13 at 12:03
  • `"If they are using it as a singleton that'll work just fine"` unfortunately not. Oh well such as life. – Nathan W Aug 13 '13 at 12:23