Left: | ||
Right: |
OLD | NEW |
---|---|
1 | 1 |
2 .. _expressions: | 2 .. _expressions: |
3 | 3 |
4 *********** | 4 *********** |
5 Expressions | 5 Expressions |
6 *********** | 6 *********** |
7 | 7 |
8 .. index:: expression, BNF | 8 .. index:: expression, BNF |
9 | 9 |
10 This chapter explains the meaning of the elements of expressions in Python. | 10 This chapter explains the meaning of the elements of expressions in Python. |
(...skipping 994 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1005 | 1005 |
1006 .. index:: | 1006 .. index:: |
1007 pair: bitwise; or | 1007 pair: bitwise; or |
1008 pair: inclusive; or | 1008 pair: inclusive; or |
1009 | 1009 |
1010 The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which | 1010 The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which |
1011 must be integers. | 1011 must be integers. |
1012 | 1012 |
1013 | 1013 |
1014 .. _comparisons: | 1014 .. _comparisons: |
1015 .. _is: | |
1016 .. _is not: | |
1017 .. _in: | |
1018 .. _not in: | |
1019 | 1015 |
1020 Comparisons | 1016 Comparisons |
1021 =========== | 1017 =========== |
1022 | 1018 |
1023 .. index:: single: comparison | 1019 .. index:: single: comparison |
1024 | 1020 |
1025 .. index:: pair: C; language | 1021 .. index:: pair: C; language |
1026 | 1022 |
1027 Unlike C, all comparison operations in Python have the same priority, which is | 1023 Unlike C, all comparison operations in Python have the same priority, which is |
1028 lower than that of any arithmetic, shifting or bitwise operation. Also unlike | 1024 lower than that of any arithmetic, shifting or bitwise operation. Also unlike |
(...skipping 15 matching lines...) Expand all Loading... | |
1044 | 1040 |
1045 Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., | 1041 Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., |
1046 *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent | 1042 *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent |
1047 to ``a op1 b and b op2 c and ... y opN z``, except that each expression is | 1043 to ``a op1 b and b op2 c and ... y opN z``, except that each expression is |
1048 evaluated at most once. | 1044 evaluated at most once. |
1049 | 1045 |
1050 Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and | 1046 Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and |
1051 *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not | 1047 *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not |
1052 pretty). | 1048 pretty). |
1053 | 1049 |
1050 .. _comparison-operators: | |
1051 | |
1052 Comparison operators | |
1053 -------------------- | |
1054 | |
1054 The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the | 1055 The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the |
1055 values of two objects. The objects need not have the same type. If both are | 1056 values of two objects. The objects do not need to have the same type. |
1056 numbers, they are converted to a common type. Otherwise, the ``==`` and ``!=`` | |
1057 operators *always* consider objects of different types to be unequal, while the | |
1058 ``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when | |
1059 comparing objects of different types that do not implement these operators for | |
1060 the given pair of types. You can control comparison behavior of objects of | |
1061 non-built-in types by defining rich comparison methods like :meth:`__gt__`, | |
1062 described in section :ref:`customization`. | |
1063 | 1057 |
1064 Comparison of objects of the same type depends on the type: | 1058 Chapter :ref:`objects` states that objects have a value (in addition to type and |
1059 identity). The value of an object is a rather abstract notion in Python: For | |
1060 example, there is no canonical access method for an object's value. Also, there | |
1061 is no requirement that the value of an object should be constructed in a | |
1062 particular way, e.g. comprised of all its data attributes. | |
1063 Comparison operators implement a particular notion of what the value of an | |
1064 object is. One can think of them as defining the value of an object indirectly, | |
1065 by means of their comparison implementation. | |
1065 | 1066 |
1066 * Numbers are compared arithmetically. | 1067 Because all types are (direct or indirect) subtypes of :class:`object`, they |
1068 inherit the default comparison behavior from :class:`object`. Types can | |
1069 customize their comparison behavior by implementing | |
1070 :dfn:`rich comparison methods` like :meth:`__lt__`, described in | |
1071 :ref:`customization`. | |
1067 | 1072 |
1068 * The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special. | 1073 The default behavior for equality comparison (``==`` and ``!=``) is based on the |
1069 The are identical to themselves, ``x is x`` but are not equal to themselves, | 1074 identity of the objects. Hence, equality comparison of instances with the same |
1070 ``x != x``. Additionally, comparing any value to a not-a-number value | 1075 identity results in equality, and equality comparison of instances with |
1071 will return ``False``. For example, both ``3 < float('NaN')`` and | 1076 different identities results in inequality. A motivation for this default |
1072 ``float('NaN') < 3`` will return ``False``. | 1077 behavior is the desire that all objects should be reflexive (i.e. ``x is y`` |
1078 implies ``x == y``). | |
1073 | 1079 |
1074 * Bytes objects are compared lexicographically using the numeric values of their | 1080 A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; |
1075 elements. | 1081 an attempt raises :exc:`TypeError`. A motivation for this default behavior is |
1082 the lack of a similar invariant as for equality. | |
1076 | 1083 |
1077 * Strings are compared lexicographically using the numeric equivalents (the | 1084 The behavior of the default equality comparison, that instances with different |
1078 result of the built-in function :func:`ord`) of their characters. [#]_ String | 1085 identities are always unequal, may be in contrast to what types will need that |
1079 and bytes object can't be compared! | 1086 have a sensible definition of object value and value-based equality. Such types |
1087 will need to customize their comparison behavior, and in fact, a number of | |
1088 built-in types have done that. | |
1080 | 1089 |
1081 * Tuples and lists are compared lexicographically using comparison of | 1090 The following list describes the comparison behavior of the most important |
1082 corresponding elements. This means that to compare equal, each element must | 1091 built-in types. Unless otherwise stated, two instances of built-in types can |
1083 compare equal and the two sequences must be of the same type and have the same | 1092 only be compared if they are of the same type or one is a subtype of the other; |
1084 length. | 1093 otherwise, :exc:`TypeError` is raised: |
andymaier
2014/10/13 11:17:23
After thinking again about Martin Panter's comment
Martin Panter
2014/10/13 15:17:35
Fine by me. In the previous patch I was referring
andymaier
2014/10/14 18:47:33
Done.
| |
1085 | 1094 |
1086 If not equal, the sequences are ordered the same as their first differing | 1095 * Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard |
1087 elements. For example, ``[1,2,x] <= [1,2,y]`` has the same value as | 1096 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be |
1088 ``x <= y``. If the corresponding element does not exist, the shorter | 1097 compared within the same type and between different of those types. Within |
1089 sequence is ordered first (for example, ``[1,2] < [1,2,3]``). | 1098 the limits of the types involved, they compare mathematically |
1099 (algorithmically) correct without loss of precision, and since version 3.2 | |
1100 also between different types (for example, ``1 == 1.0`` is true). | |
Martin Panter
2014/10/13 15:17:35
This sounds like 1 and 1.0 were considered unequal
andymaier
2014/10/14 18:47:33
That is what I had in mind, but I'm not sure we ev
| |
1090 | 1101 |
1091 * Mappings (dictionaries) compare equal if and only if they have the same | 1102 Complex numbers do not support order comparison. |
1092 ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')`` | 1103 |
1093 raise :exc:`TypeError`. | 1104 The not-a-number values :const:`float('NaN')` and :const:`Decimal('NaN')` are |
1105 special. They are identical to themselves (``x is x`` is true) but are not | |
1106 equal to themselves (``x == x`` is false). Additionally, comparing any number | |
1107 to a not-a-number value will return ``False``. For example, both | |
1108 ``3 < float('NaN')`` and ``float('NaN') < 3`` will return ``False``. | |
1094 | 1109 |
1095 * Sets and frozensets define comparison operators to mean subset and superset | 1110 * Binary sequences (instances of :class:`bytes` or :class:`bytearray`) are |
1096 tests. Those relations do not define total orderings (the two sets ``{1,2}`` | 1111 compared lexicographically using the numeric values of their elements. |
andymaier
2014/10/14 18:47:33
Martin Panter's comment:
| |
1097 and {2,3} are not equal, nor subsets of one another, nor supersets of one | |
1098 another). Accordingly, sets are not appropriate arguments for functions | |
1099 which depend on total ordering. For example, :func:`min`, :func:`max`, and | |
1100 :func:`sorted` produce undefined results given a list of sets as inputs. | |
1101 | 1112 |
1102 * Most other objects of built-in types compare unequal unless they are the same | 1113 * Strings (instances of :class:`str`) are compared lexicographically using the |
1103 object; the choice whether one object is considered smaller or larger than | 1114 numerical Unicode code points (the result of the built-in function |
1104 another one is made arbitrarily but consistently within one execution of a | 1115 :func:`ord`) of their characters. [#]_ |
1105 program. | |
1106 | 1116 |
1107 Comparison of objects of differing types depends on whether either of the | 1117 Strings and binary sequences cannot be directly compared. |
1108 types provide explicit support for the comparison. Most numeric types can be | |
1109 compared with one another. When cross-type comparison is not supported, the | |
1110 comparison method returns ``NotImplemented``. | |
1111 | 1118 |
1119 * Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) are | |
1120 compared lexicographically using comparison of corresponding elements. | |
1121 | |
1122 Ranges do not support order comparison. | |
andymaier
2014/10/14 18:47:33
Martin Panter's comment:
| |
1123 | |
1124 Comparison of sequences enforces reflexivity of its elements. | |
1125 | |
1126 In enforcing reflexivity of elements, the comparison of collections assumes | |
1127 that for a collection element ``x``, ``x == x`` is always true. Based on | |
1128 that assumption, element identity is compared first, and element comparison | |
1129 is performed only for distinct elements. This approach yields the same result | |
1130 as a strict element comparison would, if the compared elements are reflexive. | |
1131 Comparison of non-reflexive elements in collections also tests identity first, | |
1132 and thus the result is different than for strict element comparison, and may | |
1133 be surprising: The non-reflexive not-a-number values for example result in | |
1134 the following comparison behavior when used in a list:: | |
1135 | |
1136 >>> nan = float('NaN') | |
1137 >>> nan is nan | |
1138 True | |
1139 >>> nan == nan | |
1140 False <-- the defined non-reflexive behavior of NaN | |
1141 >>> [nan] == [nan] | |
1142 True <-- list enforces reflexivity and tests identity first | |
1143 | |
1144 Lexicographical comparison between built-in collections works as follows: For two | |
1145 collections to compare equal, they must be of the same type, | |
1146 have the same length, and each pair of corresponding elements | |
1147 must compare equal. | |
1148 Collections that support order comparison are ordered the same as their first | |
1149 unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same value as | |
1150 ``x <= y``). If a corresponding element does not exist, the shorter | |
1151 collection is ordered first (for example, ``[1,2] < [1,2,3]`` is true). | |
1152 | |
1153 * Mappings (instances of :class:`dict`) compare equal if and only if they have | |
1154 equal `(key, value)` pairs. Equality comparison of the keys and elements | |
1155 enforces reflexivity. | |
1156 | |
1157 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`. | |
1158 | |
1159 * Sets (instances of :class:`set` or :class:`frozenset`) can be compared within | |
1160 the same type and between different of those types. | |
1161 | |
1162 They define order | |
1163 comparison operators to mean subset and superset tests. Those relations do | |
1164 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` | |
1165 are not equal, nor subsets of one another, nor supersets of one another). | |
1166 Accordingly, sets are not appropriate arguments for functions which depend on | |
1167 total ordering (for example, :func:`min`, :func:`max`, and :func:`sorted` | |
1168 produce undefined results given a list of sets as inputs). | |
1169 | |
1170 Comparison of sets enforces reflexivity of its elements. | |
1171 | |
1172 * Most other built-in types have no comparison methods implemented, so they | |
1173 inherit the default comparison behavior. | |
1174 | |
andymaier
2014/10/13 11:19:43
Should we move the remainder of this section to 3.
Martin Panter
2014/10/13 15:17:35
Not sure. It might also be useful to people using
| |
1175 User-defined classes that customize their comparison behavior should follow | |
1176 some consistency rules, if possible: | |
1177 | |
1178 * Equality comparison should be reflexive. | |
1179 In other words, identical objects should compare equal: | |
1180 | |
1181 ``x is y`` implies ``x == y`` | |
1182 | |
1183 * Comparison should be symmetric. | |
1184 In other words, the following expressions should have the same result: | |
1185 | |
1186 ``x == y`` and ``y == x`` | |
1187 | |
1188 ``x != y`` and ``y != x`` | |
1189 | |
1190 ``x < y`` and ``y > x`` | |
1191 | |
1192 ``x <= y`` and ``y >= x`` | |
1193 | |
1194 * Comparison should be transitive. | |
1195 The following (non-exhaustive) examples illustrate that: | |
1196 | |
1197 ``x > y and y > z`` implies ``x > z`` | |
1198 | |
1199 ``x < y and y <= z`` implies ``x < z`` | |
1200 | |
1201 * Inverse comparison should result in the boolean negation. | |
1202 In other words, the following expressions should have the same result: | |
1203 | |
1204 ``x == y`` and ``not x != y`` | |
1205 | |
1206 ``x < y`` and ``not x >= y`` (for total ordering) | |
1207 | |
1208 ``x > y`` and ``not x <= y`` (for total ordering) | |
1209 | |
1210 The last two expressions apply to totally ordered collections (e.g. to | |
1211 sequences, but not to sets or mappings). See also the | |
1212 :func:`~functools.total_ordering` decorator. | |
1213 | |
1214 Python does not enforce these consistency rules. In fact, the not-a-number | |
1215 values are an example for not following these rules. | |
1216 | |
1217 | |
1218 .. _in: | |
1219 .. _not in: | |
1112 .. _membership-test-details: | 1220 .. _membership-test-details: |
1221 .. _membership-test-operators: | |
1222 | |
1223 Membership test operators | |
1224 ------------------------- | |
1113 | 1225 |
1114 The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in | 1226 The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in |
1115 s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not | 1227 s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not |
1116 in s`` returns the negation of ``x in s``. All built-in sequences and set types | 1228 in s`` returns the negation of ``x in s``. All built-in sequences and set types |
1117 support this as well as dictionary, for which :keyword:`in` tests whether the | 1229 support this as well as dictionary, for which :keyword:`in` tests whether the |
1118 dictionary has a given key. For container types such as list, tuple, set, | 1230 dictionary has a given key. For container types such as list, tuple, set, |
1119 frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent | 1231 frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent |
1120 to ``any(x is e or x == e for e in y)``. | 1232 to ``any(x is e or x == e for e in y)``. |
1121 | 1233 |
1122 For the string and bytes types, ``x in y`` is true if and only if *x* is a | 1234 For the string and bytes types, ``x in y`` is true if and only if *x* is a |
(...skipping 21 matching lines...) Expand all Loading... | |
1144 pair: membership; test | 1256 pair: membership; test |
1145 object: sequence | 1257 object: sequence |
1146 | 1258 |
1147 The operator :keyword:`not in` is defined to have the inverse true value of | 1259 The operator :keyword:`not in` is defined to have the inverse true value of |
1148 :keyword:`in`. | 1260 :keyword:`in`. |
1149 | 1261 |
1150 .. index:: | 1262 .. index:: |
1151 operator: is | 1263 operator: is |
1152 operator: is not | 1264 operator: is not |
1153 pair: identity; test | 1265 pair: identity; test |
1266 | |
1267 | |
1268 .. _is: | |
1269 .. _is not: | |
1270 | |
1271 Identity test operators | |
1272 ----------------------- | |
1154 | 1273 |
1155 The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x | 1274 The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x |
1156 is y`` is true if and only if *x* and *y* are the same object. ``x is not y`` | 1275 is y`` is true if and only if *x* and *y* are the same object. ``x is not y`` |
1157 yields the inverse truth value. [#]_ | 1276 yields the inverse truth value. [#]_ |
1158 | 1277 |
1159 | 1278 |
1160 .. _booleans: | 1279 .. _booleans: |
1161 .. _and: | 1280 .. _and: |
1162 .. _or: | 1281 .. _or: |
1163 .. _not: | 1282 .. _not: |
(...skipping 207 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1371 1e100``, which is numerically exactly equal to ``1e100``. The function | 1490 1e100``, which is numerically exactly equal to ``1e100``. The function |
1372 :func:`math.fmod` returns a result whose sign matches the sign of the | 1491 :func:`math.fmod` returns a result whose sign matches the sign of the |
1373 first argument instead, and so returns ``-1e-100`` in this case. Which approa ch | 1492 first argument instead, and so returns ``-1e-100`` in this case. Which approa ch |
1374 is more appropriate depends on the application. | 1493 is more appropriate depends on the application. |
1375 | 1494 |
1376 .. [#] If x is very close to an exact integer multiple of y, it's possible for | 1495 .. [#] If x is very close to an exact integer multiple of y, it's possible for |
1377 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such | 1496 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such |
1378 cases, Python returns the latter result, in order to preserve that | 1497 cases, Python returns the latter result, in order to preserve that |
1379 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. | 1498 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. |
1380 | 1499 |
1381 .. [#] While comparisons between strings make sense at the byte level, they may | 1500 .. [#] The Unicode standard distinguishes between :dfn:`code points` |
1382 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and | 1501 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A"). |
1383 ``"\u0327\u0043"`` compare differently, even though they both represent the | 1502 While most abstract characters in Unicode are only represented using one |
1384 same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare | 1503 code point, there is a number of abstract characters that can in addition be |
1385 strings in a human recognizable way, compare using | 1504 represented using a sequence of more than one code point. For example, the |
1386 :func:`unicodedata.normalize`. | 1505 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented |
1506 as a single :dfn:`precomposed character` at code position U+00C7, or as a | |
1507 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL | |
1508 LETTER C), followed by a :dfn:`combining character` at code position U+0327 | |
1509 (COMBINING CEDILLA). | |
1510 | |
1511 The comparison operators on strings compare at the level of Unicode code | |
1512 points. This may be counter-intuitive to humans. For example, | |
1513 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings | |
1514 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA". | |
1515 | |
1516 To compare strings at the level of abstract characters (that is, in a way | |
1517 intuitive to humans), use :func:`unicodedata.normalize`. | |
1387 | 1518 |
1388 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature o f | 1519 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature o f |
1389 descriptors, you may notice seemingly unusual behaviour in certain uses of | 1520 descriptors, you may notice seemingly unusual behaviour in certain uses of |
1390 the :keyword:`is` operator, like those involving comparisons between instance | 1521 the :keyword:`is` operator, like those involving comparisons between instance |
1391 methods, or constants. Check their documentation for more info. | 1522 methods, or constants. Check their documentation for more info. |
1392 | 1523 |
1393 .. [#] The ``%`` operator is also used for string formatting; the same | 1524 .. [#] The ``%`` operator is also used for string formatting; the same |
1394 precedence applies. | 1525 precedence applies. |
1395 | 1526 |
1396 .. [#] The power operator ``**`` binds less tightly than an arithmetic or | 1527 .. [#] The power operator ``**`` binds less tightly than an arithmetic or |
1397 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. | 1528 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. |
OLD | NEW |