Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the 'is' keyword implemented in Python?

... 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 >>> 
like image 729
Srikanth Avatar asked Jun 07 '10 08:06

Srikanth


People also ask

How use is keyword in Python?

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.

Is keyword a keyword in Python?

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.

Is file a keyword in Python?

file is neither a keyword nor a builtin in Python 3. file is also used as variable example from Python 3 doc.

Is string a keyword in Python?

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.


1 Answers

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.

like image 105
Jochen Ritzel Avatar answered Sep 22 '22 11:09

Jochen Ritzel