Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the __contains__ method of the list class in Python implemented?

Tags:

python

Suppose I define the following variables:

mode = "access"
allowed_modes = ["access", "read", "write"]

I currently have a type checking statement which is

assert any(mode == allowed_mode for allowed_mode in allowed_modes)

However, it seems that I can replace this simply with

assert mode in allowed_modes

According to ThiefMaster's answer in Python List Class __contains__ Method Functionality, these two should be equivalent. Is this indeed the case? And how could I easily verify this by looking up Python's source code?

like image 816
Kurt Peek Avatar asked Jan 31 '17 11:01

Kurt Peek


People also ask

How does __ contains __ work in Python?

Python string __contains__() is an instance method and returns boolean value True or False depending on whether the string object contains the specified string object or not. Note that the Python string contains() method is case sensitive.

What is contains class Python?

__ contains __ method is used to overload the “in” operator in python. For example, you have a custom class MyClass and you want to check if one instance is in another by using it. What is this? In such case you'll use the contains a method to overload this “in” operator.

Can contains function be called?

Like all special methods (with "magic names" that begin and end in __ ), __contains__ is not meant to be called directly (except in very specific cases, such as up=calls to the superclass): rather, such methods are called as part of the operation of built-ins and operators.

What is a list class in Python?

List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.


1 Answers

No, they're not equivalent. For example:

>>> mode = float('nan')
>>> allowed_modes = [mode]
>>> any(mode == allowed_mode for allowed_mode in allowed_modes)
False
>>> mode in allowed_modes
True

See Membership test operations for more details, including this statement:

For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

like image 56
Stefan Pochmann Avatar answered Nov 15 '22 08:11

Stefan Pochmann