I\'m writing a class which encapsulates any arbitrary object, including simple types. I want the \"is\" keyword to operate on the encapsulated value, such as this behavior:<
is
itself cannot be overloaded, but you may be interested in other "Reflection" magic methods which may be suitable for your use case (since you are looking at this thread):
__instancecheck__(self, instance)
Checks if an instance is an instance of the class you defined (e.g.isinstance(instance, class)
.
__subclasscheck__(self, subclass)
Checks if a class subclasses the class you defined (e.g.issubclass(subclass, class)
).
Generally, if you want to test equality in terms of value (if x is 1, or True, or None), you'd use the ==
operator anyway. If you want to use the is
operator, you're generally testing if something is referring to something else, like list1 is list2
.
If you want to define special behavior for ==
, you can define __eq__
in your class definition.
No.
is
,and
, andor
cannot be overloaded.
Indeed. I believe that keywords are reserved and cannot be overloaded or changed.
See: http://docs.python.org/2/reference/lexical_analysis.html#keywords
"The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers."
The list is: ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
This list can be viewed through the command
keyword.kwlist
(Don't forget to import keyword first)
Also:
keyword.iskeyword('is')
Returns True
Update:
My answer was bad and I should feel bad.
I've messed with del myself. I don't know why I didn't notice that...
2nd try:
The following documentation provides a full list of customizable behavior on classes. This includes all the methods for overriding and overloading operators. 'is' is not included.
http://docs.python.org/2/reference/datamodel.html#special-method-names
Best I can do.
No. is
, and
, and or
cannot be overloaded.