Movatterモバイル変換


[0]ホーム

URL:


Navigation

6. Expressions

This chapter explains the meaning of the elements of expressions in Python.

Syntax Notes: In this and the following chapters, extended BNF notation willbe used to describe syntax, not lexical analysis. When (one alternative of) asyntax rule has the form

name ::=othername

and no semantics are given, the semantics of this form ofname are the sameas forothername.

6.1. Arithmetic conversions

When a description of an arithmetic operator below uses the phrase “the numericarguments are converted to a common type,” this means that the operatorimplementation for built-in types works that way:

  • If either argument is a complex number, the other is converted to complex;
  • otherwise, if either argument is a floating point number, the other isconverted to floating point;
  • otherwise, both must be integers and no conversion is necessary.

Some additional rules apply for certain operators (e.g., a string left argumentto the ‘%’ operator). Extensions must define their own conversion behavior.

6.2. Atoms

Atoms are the most basic elements of expressions. The simplest atoms areidentifiers or literals. Forms enclosed in parentheses, brackets or braces arealso categorized syntactically as atoms. The syntax for atoms is:

atom ::=identifier |literal |enclosureenclosure ::=parenth_form |list_display |dict_display |set_display               |generator_expression |yield_atom

6.2.1. Identifiers (Names)

An identifier occurring as an atom is a name. See sectionIdentifiers and keywordsfor lexical definition and sectionNaming and binding for documentation of naming andbinding.

When the name is bound to an object, evaluation of the atom yields that object.When a name is not bound, an attempt to evaluate it raises aNameErrorexception.

Private name mangling: When an identifier that textually occurs in a classdefinition begins with two or more underscore characters and does not end in twoor more underscores, it is considered aprivate name of that class.Private names are transformed to a longer form before code is generated forthem. The transformation inserts the class name, with leading underscoresremoved and a single underscore inserted, in front of the name. For example,the identifier__spam occurring in a class namedHam will be transformedto_Ham__spam. This transformation is independent of the syntacticalcontext in which the identifier is used. If the transformed name is extremelylong (longer than 255 characters), implementation defined truncation may happen.If the class name consists only of underscores, no transformation is done.

6.2.2. Literals

Python supports string and bytes literals and various numeric literals:

literal ::=stringliteral |bytesliteral             |integer |floatnumber |imagnumber

Evaluation of a literal yields an object of the given type (string, bytes,integer, floating point number, complex number) with the given value. The valuemay be approximated in the case of floating point and imaginary (complex)literals. See sectionLiterals for details.

All literals correspond to immutable data types, and hence the object’s identityis less important than its value. Multiple evaluations of literals with thesame value (either the same occurrence in the program text or a differentoccurrence) may obtain the same object or a different object with the samevalue.

6.2.3. Parenthesized forms

A parenthesized form is an optional expression list enclosed in parentheses:

parenth_form ::=  "(" [expression_list] ")"

A parenthesized expression list yields whatever that expression list yields: ifthe list contains at least one comma, it yields a tuple; otherwise, it yieldsthe single expression that makes up the expression list.

An empty pair of parentheses yields an empty tuple object. Since tuples areimmutable, the rules for literals apply (i.e., two occurrences of the emptytuple may or may not yield the same object).

Note that tuples are not formed by the parentheses, but rather by use of thecomma operator. The exception is the empty tuple, for which parenthesesarerequired — allowing unparenthesized “nothing” in expressions would causeambiguities and allow common typos to pass uncaught.

6.2.4. Displays for lists, sets and dictionaries

For constructing a list, a set or a dictionary Python provides special syntaxcalled “displays”, each of them in two flavors:

  • either the container contents are listed explicitly, or
  • they are computed via a set of looping and filtering instructions, called acomprehension.

Common syntax elements for comprehensions are:

comprehension ::=expressioncomp_forcomp_for ::=  "for"target_list "in"or_test [comp_iter]comp_iter ::=comp_for |comp_ifcomp_if ::=  "if"expression_nocond [comp_iter]

The comprehension consists of a single expression followed by at least onefor clause and zero or morefor orif clauses.In this case, the elements of the new container are those that would be producedby considering each of thefor orif clauses a block,nesting from left to right, and evaluating the expression to produce an elementeach time the innermost block is reached.

Note that the comprehension is executed in a separate scope, so names assignedto in the target list don’t “leak” in the enclosing scope.

6.2.5. List displays

A list display is a possibly empty series of expressions enclosed in squarebrackets:

list_display ::=  "[" [expression_list |comprehension] "]"

A list display yields a new list object, the contents being specified by eithera list of expressions or a comprehension. When a comma-separated list ofexpressions is supplied, its elements are evaluated from left to right andplaced into the list object in that order. When a comprehension is supplied,the list is constructed from the elements resulting from the comprehension.

6.2.6. Set displays

A set display is denoted by curly braces and distinguishable from dictionarydisplays by the lack of colons separating keys and values:

set_display ::=  "{" (expression_list |comprehension) "}"

A set display yields a new mutable set object, the contents being specified byeither a sequence of expressions or a comprehension. When a comma-separatedlist of expressions is supplied, its elements are evaluated from left to rightand added to the set object. When a comprehension is supplied, the set isconstructed from the elements resulting from the comprehension.

An empty set cannot be constructed with{}; this literal constructs an emptydictionary.

6.2.7. Dictionary displays

A dictionary display is a possibly empty series of key/datum pairs enclosed incurly braces:

dict_display ::=  "{" [key_datum_list |dict_comprehension] "}"key_datum_list ::=key_datum (","key_datum)* [","]key_datum ::=expression ":"expressiondict_comprehension ::=expression ":"expressioncomp_for

A dictionary display yields a new dictionary object.

If a comma-separated sequence of key/datum pairs is given, they are evaluatedfrom left to right to define the entries of the dictionary: each key object isused as a key into the dictionary to store the corresponding datum. This meansthat you can specify the same key multiple times in the key/datum list, and thefinal dictionary’s value for that key will be the last one given.

A dict comprehension, in contrast to list and set comprehensions, needs twoexpressions separated with a colon followed by the usual “for” and “if” clauses.When the comprehension is run, the resulting key and value elements are insertedin the new dictionary in the order they are produced.

Restrictions on the types of the key values are listed earlier in sectionThe standard type hierarchy. (To summarize, the key type should behashable, which excludesall mutable objects.) Clashes between duplicate keys are not detected; the lastdatum (textually rightmost in the display) stored for a given key valueprevails.

6.2.8. Generator expressions

A generator expression is a compact generator notation in parentheses:

generator_expression ::=  "("expressioncomp_for ")"

A generator expression yields a new generator object. Its syntax is the same asfor comprehensions, except that it is enclosed in parentheses instead ofbrackets or curly braces.

Variables used in the generator expression are evaluated lazily when the__next__() method is called for generator object (in the samefashion as normal generators). However, the leftmostfor clause isimmediately evaluated, so that an error produced by it can be seen before anyother possible error in the code that handles the generator expression.Subsequentfor clauses cannot be evaluated immediately since theymay depend on the previousfor loop. For example:(x*yforxinrange(10)foryinbar(x)).

The parentheses can be omitted on calls with only one argument. See sectionCalls for the detail.

6.2.9. Yield expressions

yield_atom ::=  "("yield_expression ")"yield_expression ::=  "yield" [expression_list | "from"expression]

The yield expression is only used when defining agenerator function andthus can only be used in the body of a function definition. Using a yieldexpression in a function’s body causes that function to be a generator.

When a generator function is called, it returns an iterator known as agenerator. That generator then controls the execution of a generator function.The execution starts when one of the generator’s methods is called. At thattime, the execution proceeds to the first yield expression, where it issuspended again, returning the value ofexpression_list to generator’scaller. By suspended, we mean that all local state is retained, including thecurrent bindings of local variables, the instruction pointer, and the internalevaluation stack. When the execution is resumed by calling one of thegenerator’s methods, the function can proceed exactly as if the yield expressionwas just another external call. The value of the yield expression afterresuming depends on the method which resumed the execution. If__next__() is used (typically via either afor orthenext() builtin) then the result isNone. Otherwise, ifsend() is used, then the result will be the value passed in tothat method.

All of this makes generator functions quite similar to coroutines; they yieldmultiple times, they have more than one entry point and their execution can besuspended. The only difference is that a generator function cannot controlwhere should the execution continue after it yields; the control is alwaystransferred to the generator’s caller.

yield expressions are allowed in thetry clause of atry...finally construct. If the generator is not resumed before it isfinalized (by reaching a zero reference count or by being garbage collected),the generator-iterator’sclose() method will be called,allowing any pendingfinally clauses to execute.

Whenyieldfrom<expr> is used, it treats the supplied expression asa subiterator. All values produced by that subiterator are passed directlyto the caller of the current generator’s methods. Any values passed in withsend() and any exceptions passed in withthrow() are passed to the underlying iterator if it has theappropriate methods. If this is not the case, thensend()will raiseAttributeError orTypeError, whilethrow() will just raise the passed in exception immediately.

When the underlying iterator is complete, thevalueattribute of the raisedStopIteration instance becomes the value ofthe yield expression. It can be either set explicitly when raisingStopIteration, or automatically when the sub-iterator is a generator(by returning a value from the sub-generator).

Changed in version 3.3:Addedyieldfrom<expr> to delegate control flow to a subiterator

The parentheses may be omitted when the yield expression is the sole expressionon the right hand side of an assignment statement.

See also

PEP 0255 - Simple Generators
The proposal for adding generators and theyield statement to Python.
PEP 0342 - Coroutines via Enhanced Generators
The proposal to enhance the API and syntax of generators, making themusable as simple coroutines.
PEP 0380 - Syntax for Delegating to a Subgenerator
The proposal to introduce theyield_from syntax, making delegationto sub-generators easy.

6.2.9.1. Generator-iterator methods

This subsection describes the methods of a generator iterator. They canbe used to control the execution of a generator function.

Note that calling any of the generator methods below when the generatoris already executing raises aValueError exception.

classgenerator
generator.__next__()

Starts the execution of a generator function or resumes it at the lastexecuted yield expression. When a generator function is resumed with a__next__() method, the current yield expression alwaysevaluates toNone. The execution then continues to the next yieldexpression, where the generator is suspended again, and the value of theexpression_list is returned tonext()‘s caller. If thegenerator exits without yielding another value, aStopIterationexception is raised.

This method is normally called implicitly, e.g. by afor loop, orby the built-innext() function.

generator.send(value)

Resumes the execution and “sends” a value into the generator function. Thevalue argument becomes the result of the current yield expression. Thesend() method returns the next value yielded by the generator, orraisesStopIteration if the generator exits without yielding anothervalue. Whensend() is called to start the generator, it must be calledwithNone as the argument, because there is no yield expression thatcould receive the value.

generator.throw(type[,value[,traceback]])

Raises an exception of typetype at the point where generator was paused,and returns the next value yielded by the generator function. If the generatorexits without yielding another value, aStopIteration exception israised. If the generator function does not catch the passed-in exception, orraises a different exception, then that exception propagates to the caller.

generator.close()

Raises aGeneratorExit at the point where the generator function waspaused. If the generator function then raisesStopIteration (byexiting normally, or due to already being closed) orGeneratorExit (bynot catching the exception), close returns to its caller. If the generatoryields a value, aRuntimeError is raised. If the generator raises anyother exception, it is propagated to the caller.close() does nothingif the generator has already exited due to an exception or normal exit.

.

6.2.9.2. Examples

Here is a simple example that demonstrates the behavior of generators andgenerator functions:

>>>defecho(value=None):...print("Execution starts when 'next()' is called for the first time.")...try:...whileTrue:...try:...value=(yieldvalue)...exceptExceptionase:...value=e...finally:...print("Don't forget to clean up when 'close()' is called.")...>>>generator=echo(1)>>>print(next(generator))Execution starts when 'next()' is called for the first time.1>>>print(next(generator))None>>>print(generator.send(2))2>>>generator.throw(TypeError,"spam")TypeError('spam',)>>>generator.close()Don't forget to clean up when 'close()' is called.

For examples usingyieldfrom, seePEP 380: Syntax for Delegating to a Subgenerator in “What’s New inPython.”

6.3. Primaries

Primaries represent the most tightly bound operations of the language. Theirsyntax is:

primary ::=atom |attributeref |subscription |slicing |call

6.3.1. Attribute references

An attribute reference is a primary followed by a period and a name:

attributeref ::=primary "."identifier

The primary must evaluate to an object of a type that supports attributereferences, which most objects do. This object is then asked to produce theattribute whose name is the identifier (which can be customized by overridingthe__getattr__() method). If this attribute is not available, theexceptionAttributeError is raised. Otherwise, the type and value of theobject produced is determined by the object. Multiple evaluations of the sameattribute reference may yield different objects.

6.3.2. Subscriptions

A subscription selects an item of a sequence (string, tuple or list) or mapping(dictionary) object:

subscription ::=primary "["expression_list "]"

The primary must evaluate to an object that supports subscription, e.g. a listor dictionary. User-defined objects can support subscription by defining a__getitem__() method.

For built-in objects, there are two types of objects that support subscription:

If the primary is a mapping, the expression list must evaluate to an objectwhose value is one of the keys of the mapping, and the subscription selects thevalue in the mapping that corresponds to that key. (The expression list is atuple except if it has exactly one item.)

If the primary is a sequence, the expression (list) must evaluate to an integeror a slice (as discussed in the following section).

The formal syntax makes no special provision for negative indices insequences; however, built-in sequences all provide a__getitem__()method that interprets negative indices by adding the length of the sequenceto the index (so thatx[-1] selects the last item ofx). Theresulting value must be a nonnegative integer less than the number of items inthe sequence, and the subscription selects the item whose index is that value(counting from zero). Since the support for negative indices and slicingoccurs in the object’s__getitem__() method, subclasses overridingthis method will need to explicitly add that support.

A string’s items are characters. A character is not a separate data type but astring of exactly one character.

6.3.3. Slicings

A slicing selects a range of items in a sequence object (e.g., a string, tupleor list). Slicings may be used as expressions or as targets in assignment ordel statements. The syntax for a slicing:

slicing ::=primary "["slice_list "]"slice_list ::=slice_item (","slice_item)* [","]slice_item ::=expression |proper_sliceproper_slice ::=  [lower_bound] ":" [upper_bound] [ ":" [stride] ]lower_bound ::=expressionupper_bound ::=expressionstride ::=expression

There is ambiguity in the formal syntax here: anything that looks like anexpression list also looks like a slice list, so any subscription can beinterpreted as a slicing. Rather than further complicating the syntax, this isdisambiguated by defining that in this case the interpretation as a subscriptiontakes priority over the interpretation as a slicing (this is the case if theslice list contains no proper slice).

The semantics for a slicing are as follows. The primary must evaluate to amapping object, and it is indexed (using the same__getitem__() method asnormal subscription) with a key that is constructed from the slice list, asfollows. If the slice list contains at least one comma, the key is a tuplecontaining the conversion of the slice items; otherwise, the conversion of thelone slice item is the key. The conversion of a slice item that is anexpression is that expression. The conversion of a proper slice is a sliceobject (see sectionThe standard type hierarchy) whosestart,stop andstep attributes are the values of theexpressions given as lower bound, upper bound and stride, respectively,substitutingNone for missing expressions.

6.3.4. Calls

A call calls a callable object (e.g., afunction) with a possibly emptyseries ofarguments:

call ::=primary "(" [argument_list [","] |comprehension] ")"argument_list ::=positional_arguments [","keyword_arguments]                            ["," "*"expression] [","keyword_arguments]                            ["," "**"expression]                          |keyword_arguments ["," "*"expression]                            [","keyword_arguments] ["," "**"expression]                          | "*"expression [","keyword_arguments] ["," "**"expression]                          | "**"expressionpositional_arguments ::=expression (","expression)*keyword_arguments ::=keyword_item (","keyword_item)*keyword_item ::=identifier "="expression

A trailing comma may be present after the positional and keyword arguments butdoes not affect the semantics.

The primary must evaluate to a callable object (user-defined functions, built-infunctions, methods of built-in objects, class objects, methods of classinstances, and all objects having a__call__() method are callable). Allargument expressions are evaluated before the call is attempted. Please referto sectionFunction definitions for the syntax of formalparameter lists.

If keyword arguments are present, they are first converted to positionalarguments, as follows. First, a list of unfilled slots is created for theformal parameters. If there are N positional arguments, they are placed in thefirst N slots. Next, for each keyword argument, the identifier is used todetermine the corresponding slot (if the identifier is the same as the firstformal parameter name, the first slot is used, and so on). If the slot isalready filled, aTypeError exception is raised. Otherwise, the value ofthe argument is placed in the slot, filling it (even if the expression isNone, it fills the slot). When all arguments have been processed, the slotsthat are still unfilled are filled with the corresponding default value from thefunction definition. (Default values are calculated, once, when the function isdefined; thus, a mutable object such as a list or dictionary used as defaultvalue will be shared by all calls that don’t specify an argument value for thecorresponding slot; this should usually be avoided.) If there are any unfilledslots for which no default value is specified, aTypeError exception israised. Otherwise, the list of filled slots is used as the argument list forthe call.

CPython implementation detail: An implementation may provide built-in functions whose positional parametersdo not have names, even if they are ‘named’ for the purpose of documentation,and which therefore cannot be supplied by keyword. In CPython, this is thecase for functions implemented in C that usePyArg_ParseTuple() toparse their arguments.

If there are more positional arguments than there are formal parameter slots, aTypeError exception is raised, unless a formal parameter using the syntax*identifier is present; in this case, that formal parameter receives a tuplecontaining the excess positional arguments (or an empty tuple if there were noexcess positional arguments).

If any keyword argument does not correspond to a formal parameter name, aTypeError exception is raised, unless a formal parameter using the syntax**identifier is present; in this case, that formal parameter receives adictionary containing the excess keyword arguments (using the keywords as keysand the argument values as corresponding values), or a (new) empty dictionary ifthere were no excess keyword arguments.

If the syntax*expression appears in the function call,expression mustevaluate to an iterable. Elements from this iterable are treated as if theywere additional positional arguments; if there are positional argumentsx1, ...,xN, andexpression evaluates to a sequencey1, ...,yM,this is equivalent to a call with M+N positional argumentsx1, ...,xN,y1, ...,yM.

A consequence of this is that although the*expression syntax may appearafter some keyword arguments, it is processedbefore the keyword arguments(and the**expression argument, if any – see below). So:

>>>deff(a,b):...print(a,b)...>>>f(b=1,*(2,))2 1>>>f(a=1,*(2,))Traceback (most recent call last):  File"<stdin>", line1, in?TypeError:f() got multiple values for keyword argument 'a'>>>f(1,*(2,))1 2

It is unusual for both keyword arguments and the*expression syntax to beused in the same call, so in practice this confusion does not arise.

If the syntax**expression appears in the function call,expression mustevaluate to a mapping, the contents of which are treated as additional keywordarguments. In the case of a keyword appearing in bothexpression and as anexplicit keyword argument, aTypeError exception is raised.

Formal parameters using the syntax*identifier or**identifier cannot beused as positional argument slots or as keyword argument names.

A call always returns some value, possiblyNone, unless it raises anexception. How this value is computed depends on the type of the callableobject.

If it is—

a user-defined function:

The code block for the function is executed, passing it the argument list. Thefirst thing the code block will do is bind the formal parameters to thearguments; this is described in sectionFunction definitions. When the code blockexecutes areturn statement, this specifies the return value of thefunction call.

a built-in function or method:

The result is up to the interpreter; seeBuilt-in Functions for thedescriptions of built-in functions and methods.

a class object:

A new instance of that class is returned.

a class instance method:

The corresponding user-defined function is called, with an argument list that isone longer than the argument list of the call: the instance becomes the firstargument.

a class instance:

The class must define a__call__() method; the effect is then the same asif that method was called.

6.4. The power operator

The power operator binds more tightly than unary operators on its left; it bindsless tightly than unary operators on its right. The syntax is:

power ::=primary ["**"u_expr]

Thus, in an unparenthesized sequence of power and unary operators, the operatorsare evaluated from right to left (this does not constrain the evaluation orderfor the operands):-1**2 results in-1.

The power operator has the same semantics as the built-inpow() function,when called with two arguments: it yields its left argument raised to the powerof its right argument. The numeric arguments are first converted to a commontype, and the result is of that type.

For int operands, the result has the same type as the operands unless the secondargument is negative; in that case, all arguments are converted to float and afloat result is delivered. For example,10**2 returns100, but10**-2 returns0.01.

Raising0.0 to a negative power results in aZeroDivisionError.Raising a negative number to a fractional power results in acomplexnumber. (In earlier versions it raised aValueError.)

6.5. Unary arithmetic and bitwise operations

All unary arithmetic and bitwise operations have the same priority:

u_expr ::=power | "-"u_expr | "+"u_expr | "~"u_expr

The unary- (minus) operator yields the negation of its numeric argument.

The unary+ (plus) operator yields its numeric argument unchanged.

The unary~ (invert) operator yields the bitwise inversion of its integerargument. The bitwise inversion ofx is defined as-(x+1). It onlyapplies to integral numbers.

In all three cases, if the argument does not have the proper type, aTypeError exception is raised.

6.6. Binary arithmetic operations

The binary arithmetic operations have the conventional priority levels. Notethat some of these operations also apply to certain non-numeric types. Apartfrom the power operator, there are only two levels, one for multiplicativeoperators and one for additive operators:

m_expr ::=u_expr |m_expr "*"u_expr |m_expr "//"u_expr |m_expr "/"u_expr            |m_expr "%"u_expra_expr ::=m_expr |a_expr "+"m_expr |a_expr "-"m_expr

The* (multiplication) operator yields the product of its arguments. Thearguments must either both be numbers, or one argument must be an integer andthe other must be a sequence. In the former case, the numbers are converted to acommon type and then multiplied together. In the latter case, sequencerepetition is performed; a negative repetition factor yields an empty sequence.

The/ (division) and// (floor division) operators yield the quotient oftheir arguments. The numeric arguments are first converted to a common type.Division of integers yields a float, while floor division of integers results in aninteger; the result is that of mathematical division with the ‘floor’ functionapplied to the result. Division by zero raises theZeroDivisionErrorexception.

The% (modulo) operator yields the remainder from the division of the firstargument by the second. The numeric arguments are first converted to a commontype. A zero right argument raises theZeroDivisionError exception. Thearguments may be floating point numbers, e.g.,3.14%0.7 equals0.34(since3.14 equals4*0.7+0.34.) The modulo operator always yields aresult with the same sign as its second operand (or zero); the absolute value ofthe result is strictly smaller than the absolute value of the second operand[1].

The floor division and modulo operators are connected by the followingidentity:x==(x//y)*y+(x%y). Floor division and modulo are alsoconnected with the built-in functiondivmod():divmod(x,y)==(x//y,x%y).[2].

In addition to performing the modulo operation on numbers, the% operator isalso overloaded by string objects to perform old-style string formatting (alsoknown as interpolation). The syntax for string formatting is described in thePython Library Reference, sectionprintf-style String Formatting.

The floor division operator, the modulo operator, and thedivmod()function are not defined for complex numbers. Instead, convert to a floatingpoint number using theabs() function if appropriate.

The+ (addition) operator yields the sum of its arguments. The argumentsmust either both be numbers or both sequences of the same type. In the formercase, the numbers are converted to a common type and then added together. Inthe latter case, the sequences are concatenated.

The- (subtraction) operator yields the difference of its arguments. Thenumeric arguments are first converted to a common type.

6.7. Shifting operations

The shifting operations have lower priority than the arithmetic operations:

shift_expr ::=a_expr |shift_expr ( "<<" | ">>" )a_expr

These operators accept integers as arguments. They shift the first argument tothe left or right by the number of bits given by the second argument.

A right shift byn bits is defined as floor division bypow(2,n). A leftshift byn bits is defined as multiplication withpow(2,n).

Note

In the current implementation, the right-hand operand is requiredto be at mostsys.maxsize. If the right-hand operand is larger thansys.maxsize anOverflowError exception is raised.

6.8. Binary bitwise operations

Each of the three bitwise operations has a different priority level:

and_expr ::=shift_expr |and_expr "&"shift_exprxor_expr ::=and_expr |xor_expr "^"and_expror_expr ::=xor_expr |or_expr "|"xor_expr

The& operator yields the bitwise AND of its arguments, which must beintegers.

The^ operator yields the bitwise XOR (exclusive OR) of its arguments, whichmust be integers.

The| operator yields the bitwise (inclusive) OR of its arguments, whichmust be integers.

6.9. Comparisons

Unlike C, all comparison operations in Python have the same priority, which islower than that of any arithmetic, shifting or bitwise operation. Also unlikeC, expressions likea<b<c have the interpretation that is conventionalin mathematics:

comparison ::=or_expr (comp_operatoror_expr )*comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="                   | "is" ["not"] | ["not"] "in"

Comparisons yield boolean values:True orFalse.

Comparisons can be chained arbitrarily, e.g.,x<y<=z is equivalent tox<yandy<=z, except thaty is evaluated only once (but in bothcasesz is not evaluated at all whenx<y is found to be false).

Formally, ifa,b,c, ...,y,z are expressions andop1,op2, ...,opN are comparison operators, thenaop1bop2c...yopNz is equivalenttoaop1bandbop2cand...yopNz, except that each expression isevaluated at most once.

Note thataop1bop2c doesn’t imply any kind of comparison betweena andc, so that, e.g.,x<y>z is perfectly legal (though perhaps notpretty).

The operators<,>,==,>=,<=, and!= compare thevalues of two objects. The objects need not have the same type. If both arenumbers, they are converted to a common type. Otherwise, the== and!=operatorsalways consider objects of different types to be unequal, while the<,>,>= and<= operators raise aTypeError whencomparing objects of different types that do not implement these operators forthe given pair of types. You can control comparison behavior of objects ofnon-built-in types by defining rich comparison methods like__gt__(),described in sectionBasic customization.

Comparison of objects of the same type depends on the type:

  • Numbers are compared arithmetically.

  • The valuesfloat('NaN') andDecimal('NaN') are special.The are identical to themselves,xisx but are not equal to themselves,x!=x. Additionally, comparing any value to a not-a-number valuewill returnFalse. For example, both3<float('NaN') andfloat('NaN')<3 will returnFalse.

  • Bytes objects are compared lexicographically using the numeric values of theirelements.

  • Strings are compared lexicographically using the numeric equivalents (theresult of the built-in functionord()) of their characters.[3] Stringand bytes object can’t be compared!

  • Tuples and lists are compared lexicographically using comparison ofcorresponding elements. This means that to compare equal, each element mustcompare equal and the two sequences must be of the same type and have the samelength.

    If not equal, the sequences are ordered the same as their first differingelements. For example,[1,2,x]<=[1,2,y] has the same value asx<=y. If the corresponding element does not exist, the shortersequence is ordered first (for example,[1,2]<[1,2,3]).

  • Mappings (dictionaries) compare equal if and only if they have the same(key,value) pairs. Order comparisons('<','<=','>=','>')raiseTypeError.

  • Sets and frozensets define comparison operators to mean subset and supersettests. Those relations do not define total orderings (the two sets{1,2}and {2,3} are not equal, nor subsets of one another, nor supersets of oneanother). Accordingly, sets are not appropriate arguments for functionswhich depend on total ordering. For example,min(),max(), andsorted() produce undefined results given a list of sets as inputs.

  • Most other objects of built-in types compare unequal unless they are the sameobject; the choice whether one object is considered smaller or larger thananother one is made arbitrarily but consistently within one execution of aprogram.

Comparison of objects of the differing types depends on whether either of thetypes provide explicit support for the comparison. Most numeric types can becompared with one another. When cross-type comparison is not supported, thecomparison method returnsNotImplemented.

The operatorsin andnotin test for membership.xins evaluates to true ifx is a member ofs, and false otherwise.xnotins returns the negation ofxins. All built-in sequences and set typessupport this as well as dictionary, for whichin tests whether a thedictionary has a given key. For container types such as list, tuple, set,frozenset, dict, or collections.deque, the expressionxiny is equivalenttoany(xiseorx==eforeiny).

For the string and bytes types,xiny is true if and only ifx is asubstring ofy. An equivalent test isy.find(x)!=-1. Empty strings arealways considered to be a substring of any other string, so""in"abc" willreturnTrue.

For user-defined classes which define the__contains__() method,xiny is true if and only ify.__contains__(x) is true.

For user-defined classes which do not define__contains__() but do define__iter__(),xiny is true if some valuez withx==z isproduced while iterating overy. If an exception is raised during theiteration, it is as ifin raised that exception.

Lastly, the old-style iteration protocol is tried: if a class defines__getitem__(),xiny is true if and only if there is a non-negativeinteger indexi such thatx==y[i], and all lower integer indices do notraiseIndexError exception. (If any other exception is raised, it is asifin raised that exception).

The operatornotin is defined to have the inverse true value ofin.

The operatorsis andisnot test for object identity:xisy is true if and only ifx andy are the same object.xisnotyyields the inverse truth value.[4]

6.10. Boolean operations

or_test ::=and_test |or_test "or"and_testand_test ::=not_test |and_test "and"not_testnot_test ::=comparison | "not"not_test

In the context of Boolean operations, and also when expressions are used bycontrol flow statements, the following values are interpreted as false:False,None, numeric zero of all types, and empty strings and containers(including strings, tuples, lists, dictionaries, sets and frozensets). Allother values are interpreted as true. User-defined objects can customize theirtruth value by providing a__bool__() method.

The operatornot yieldsTrue if its argument is false,Falseotherwise.

The expressionxandy first evaluatesx; ifx is false, its value isreturned; otherwise,y is evaluated and the resulting value is returned.

The expressionxory first evaluatesx; ifx is true, its value isreturned; otherwise,y is evaluated and the resulting value is returned.

(Note that neitherand noror restrict the value and typethey return toFalse andTrue, but rather return the last evaluatedargument. This is sometimes useful, e.g., ifs is a string that should bereplaced by a default value if it is empty, the expressionsor'foo' yieldsthe desired value. Becausenot has to invent a value anyway, it doesnot bother to return a value of the same type as its argument, so e.g.,not'foo' yieldsFalse, not''.)

6.11. Conditional expressions

conditional_expression ::=or_test ["if"or_test "else"expression]expression ::=conditional_expression |lambda_exprexpression_nocond ::=or_test |lambda_expr_nocond

Conditional expressions (sometimes called a “ternary operator”) have the lowestpriority of all Python operations.

The expressionxifCelsey first evaluates the condition,C (notx);ifC is true,x is evaluated and its value is returned; otherwise,y isevaluated and its value is returned.

SeePEP 308 for more details about conditional expressions.

6.12. Lambdas

lambda_expr ::=  "lambda" [parameter_list]:expressionlambda_expr_nocond ::=  "lambda" [parameter_list]:expression_nocond

Lambda expressions (sometimes called lambda forms) have the same syntactic position asexpressions. They are a shorthand to create anonymous functions; the expressionlambdaarguments:expression yields a function object. The unnamed objectbehaves like a function object defined with

def <lambda>(arguments):    return expression

See sectionFunction definitions for the syntax of parameter lists. Note thatfunctions created with lambda expressions cannot contain statements orannotations.

6.13. Expression lists

expression_list ::=expression ( ","expression )* [","]

An expression list containing at least one comma yields a tuple. The length ofthe tuple is the number of expressions in the list. The expressions areevaluated from left to right.

The trailing comma is required only to create a single tuple (a.k.a. asingleton); it is optional in all other cases. A single expression without atrailing comma doesn’t create a tuple, but rather yields the value of thatexpression. (To create an empty tuple, use an empty pair of parentheses:().)

6.14. Evaluation order

Python evaluates expressions from left to right. Notice that while evaluatingan assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order oftheir suffixes:

expr1,expr2,expr3,expr4(expr1,expr2,expr3,expr4){expr1:expr2,expr3:expr4}expr1+expr2*(expr3-expr4)expr1(expr2,expr3,*expr4,**expr5)expr3,expr4=expr1,expr2

6.15. Operator precedence

The following table summarizes the operator precedences in Python, from lowestprecedence (least binding) to highest precedence (most binding). Operators inthe same box have the same precedence. Unless the syntax is explicitly given,operators are binary. Operators in the same box group left to right (except forcomparisons, including tests, which all have the same precedence and chain fromleft to right — see sectionComparisons — and exponentiation, whichgroups from right to left).

OperatorDescription
lambdaLambda expression
ifelseConditional expression
orBoolean OR
andBoolean AND
notxBoolean NOT
in,notin,is,isnot,<,<=,>,>=,!=,==Comparisons, including membershiptests and identity tests
|Bitwise OR
^Bitwise XOR
&Bitwise AND
<<,>>Shifts
+,-Addition and subtraction
*,/,//,%Multiplication, division, remainder[5]
+x,-x,~xPositive, negative, bitwise NOT
**Exponentiation[6]
x[index],x[index:index],x(arguments...),x.attributeSubscription, slicing,call, attribute reference
(expressions...),[expressions...],{key:value...},{expressions...}Binding or tuple display,list display,dictionary display,set display

Footnotes

[1]Whileabs(x%y)<abs(y) is true mathematically, for floats it may not betrue numerically due to roundoff. For example, and assuming a platform on whicha Python float is an IEEE 754 double-precision number, in order that-1e-100%1e100 have the same sign as1e100, the computed result is-1e-100+1e100, which is numerically exactly equal to1e100. The functionmath.fmod() returns a result whose sign matches the sign of thefirst argument instead, and so returns-1e-100 in this case. Which approachis more appropriate depends on the application.
[2]If x is very close to an exact integer multiple of y, it’s possible forx//y to be one larger than(x-x%y)//y due to rounding. In suchcases, Python returns the latter result, in order to preserve thatdivmod(x,y)[0]*y+x%y be very close tox.
[3]While comparisons between strings make sense at the byte level, they maybe counter-intuitive to users. For example, the strings"\u00C7" and"\u0327\u0043" compare differently, even though they both represent thesame unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To comparestrings in a human recognizable way, compare usingunicodedata.normalize().
[4]Due to automatic garbage-collection, free lists, and the dynamic nature ofdescriptors, you may notice seemingly unusual behaviour in certain uses oftheis operator, like those involving comparisons between instancemethods, or constants. Check their documentation for more info.
[5]The% operator is also used for string formatting; the sameprecedence applies.
[6]The power operator** binds less tightly than an arithmetic orbitwise unary operator on its right, that is,2**-1 is0.5.

Table Of Contents

Previous topic

5. The import system

Next topic

7. Simple statements

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp