... the is
keyword that can be used for equality in strings.
>>> s = 'str' >>> s is 'str' True >>> s is 'st' False
I tried both __is__()
and __eq__()
but they didn't work.
>>> class MyString: ... def __init__(self): ... self.s = 'string' ... def __is__(self, s): ... return self.s == s ... >>> >>> >>> m = MyString() >>> m is 'ss' False >>> m is 'string' # <--- Expected to work False >>> >>> class MyString: ... def __init__(self): ... self.s = 'string' ... def __eq__(self, s): ... return self.s == s ... >>> >>> m = MyString() >>> m is 'ss' False >>> m is 'string' # <--- Expected to work, but again failed False >>>
The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.
Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.
file is neither a keyword nor a builtin in Python 3. file is also used as variable example from Python 3 doc.
How to check if a string is a keyword? Python in its language defines an inbuilt module “keyword” which handles certain operations related to keywords. A function “iskeyword()” checks if a string is a keyword or not. Returns true if a string is a keyword, else returns false.
Testing strings with is
only works when the strings are interned. Unless you really know what you're doing and explicitly interned the strings you should never use is
on strings.
is
tests for identity, not equality. That means Python simply compares the memory address a object resides in. is
basically answers the question "Do I have two names for the same object?" - overloading that would make no sense.
For example, ("a" * 100) is ("a" * 100)
is False. Usually Python writes each string into a different memory location, interning mostly happens for string literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With