Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Python syntax and semantics

From Wikipedia, the free encyclopedia
Set of rules defining correctly structured programs
A snippet of Python code with keywords highlighted in bold yellow font

Thesyntax of thePython programming language is the set of rules that defines how a Python program will be written andinterpreted (by both theruntime system and by human readers). The Python language has many similarities toPerl,C, andJava. However, there are some definite differences between the languages. It supports multipleprogramming paradigms, including structured,object-oriented programming, andfunctional programming, and boasts a dynamictype system andautomatic memory management.

Python's syntax is simple and consistent, adhering to the principle that "There should be one—and preferably only one—obvious way to do it."[citation needed] The language incorporates built-indata types and structures,control flow mechanisms, first-class functions, and modules for bettercode reusability and organization. Python also uses English keywords where other languages use punctuation, contributing to its uncluttered visual layout.

The language provides robust error handling through exceptions, and includes adebugger in the standard library for efficient problem-solving. Python's syntax, designed for readability and ease of use, makes it a popular choice among beginners and professionals alike.

Design philosophy

[edit]

Python was designed to be a highlyreadable language.[1] It has a relatively uncluttered visual layout and uses English keywords frequently where other languagesuse punctuation. Python aims to be simple and consistent in the design of its syntax, encapsulated in the mantra "There should be one— and preferably only one —obvious way to do it", from theZen of Python.[2]

This mantra is deliberately opposed to thePerl andRuby mantra, "there's more than one way to do it".

Keywords

[edit]

Python has 35keywords orreserved words; they cannot be used asidentifiers.[3][4]

In addition, Python also has 3soft keywords. Unlike regularhard keywords, soft keywords are reserved words only in the limited contexts where interpreting them as keywords would make syntactic sense. These words can be used as identifiers elsewhere, in other words,match andcase are valid names for functions and variables.[6][7]

Notes
  1. ^abasync andawait were introduced in Python 3.5.[5]
  2. ^abTrue andFalse became keywords in Python 3.0. Previously they wereglobal variables.
  3. ^nonlocal was introduced in Python 3.0.
  4. ^abcmatch,case and_ were introduced as keywords in Python 3.10.

Indentation

[edit]

Python useswhitespace to delimitcontrol flow blocks (following theoff-side rule). Python borrows this feature from its predecessorABC: instead of punctuation or keywords, it uses indentation to indicate the run of ablock.

In so-called "free-format" languages—that use the block structure derived fromALGOL—blocks of code are set off with braces ({ }) or keywords. In mostcoding conventions for these languages, programmersconventionally indent the code within a block, to visually set it apart from the surrounding code.

Arecursivefunction namedfoo, which is passed a singleparameter,x, and if the parameter is 0 will call a different function namedbar and otherwise will callbaz, passingx, and also call itself recursively, passingx-1 as the parameter, could be implemented like this in Python:

deffoo(x):ifx==0:bar()else:baz(x)foo(x-1)

and could be written like this inC withK&R indent style:

voidfoo(intx){if(x==0){bar();}else{baz(x);foo(x-1);}}

Incorrectly indented code could be misread by a human reader differently than it would be interpreted by acompiler or interpreter. For example, if the function callfoo(x - 1) on the last line in the example above was erroneously indented to be outside theif/else block:

deffoo(x):ifx==0:bar()else:baz(x)foo(x-1)

it would cause the last line to always be executed, even whenx is 0, resulting in anendless recursion.

While bothspace andtab characters are accepted as forms of indentation and any multiple of spaces can be used, spaces are recommended[8] and 4 spaces (as in the above examples) are recommended and are by far the most commonly used.[9][10][unreliable source?] Mixing spaces and tabs on consecutive lines is not allowed starting with Python 3[11] because that can create bugs which are difficult to see, since many text editors do not visually distinguish spaces and tabs.

Data structures

[edit]
See also:Python (programming language) § Typing

Since Python is adynamically-typed language, Pythonvalues, not variables, carrytype information. Allvariables in Python holdreferences toobjects, and these references are passed to functions. Some people (including Python creatorGuido van Rossum himself) have called this parameter-passing scheme "call by object reference". An object reference means a name, and the passed reference is an "alias", i.e. a copy of the reference to the same object, just as in C/C++. The object's value may be changed in the called function with the "alias", for example:

>>>alist=['a','b','c']>>>defmy_func(al):...al.append('x')...print(al)...>>>my_func(alist)['a', 'b', 'c', 'x']>>>alist['a', 'b', 'c', 'x']

Functionmy_func changes the value ofalist with the formal argumental, which is an alias ofalist. However, any attempt to operate (assign a new object reference to) on the alias itself will have no effect on the original object.[clarification needed]

>>>alist=['a','b','c']>>>defmy_func(al):...# al.append('x')...al=al+['x']# a new list created and assigned to al means al is no more alias for alist...print(al)...>>>my_func(alist)['a', 'b', 'c', 'x']>>>print(alist)['a', 'b', 'c']

In Python, non-innermost-local and not-declared-global accessible names are all aliases.

Among dynamically-typed languages, Python is moderately type-checked. Implicitconversion is defined fornumeric types (as well asbooleans), so one may validly multiply acomplex number by aninteger (for instance) without explicitcasting. However, there is no implicit conversion between, for example, numbers andstrings; a string is an invalid argument to a mathematical function expecting a number.

Base types

[edit]

Python has a broad range of basic data types. Alongside conventional integer andfloating-point arithmetic, it transparently supportsarbitrary-precision arithmetic,complex numbers, anddecimal numbers.

Python supports a wide variety of string operations. Strings in Python areimmutable, meaning that string operations, such as replacement ofcharacters, return a new string; in other programming languages the string might be alteredin place. Performance considerations sometimes push for using special techniques in programs that modify strings intensively, such as joining character arrays into strings only as needed.

Collection types

[edit]

One of the very useful aspects of Python is the concept ofcollection (orcontainer) types. In general a collection is an object that contains other objects in a way that is easily referenced orindexed. Collections come in two basic forms:sequences andmappings.

The ordered sequential types are lists (dynamicarrays),tuples, and strings. All sequences are indexed positionally (0 throughlength - 1) and all but strings can contain any type of object, including multiple types in the same sequence. Both strings and tuples are immutable, making them perfect candidates for dictionary keys (see below). Lists, on the other hand, are mutable; elements can be inserted, deleted, modified, appended, or sortedin-place.

Mappings, on the other hand, are (often unordered) types implemented in the form ofdictionaries which "map" a set of immutable keys to corresponding elements (much like a mathematical function). For example, one could define a dictionary having a string"toast" mapped to the integer42 or vice versa. The keys in a dictionary must be of an immutable Python type, such as an integer or a string, because they are implemented via ahash function. This makes for much faster lookup times, but requires keys to remain unchanged.

Dictionaries are central to the internals of Python as they reside at the core of all objects and classes: the mappings between variable names (strings) and the values which the names reference are stored as dictionaries (seeObject system). Since these dictionaries are directly accessible (via an object's__dict__ attribute),metaprogramming is a straightforward and natural process in Python.

Aset collection type is an unindexed, unordered collection that contains no duplicates, and implementsset theoretic operations such asunion,intersection,difference,symmetric difference, andsubset testing. There are two types of sets:set andfrozenset, the only difference being thatset is mutable andfrozenset is immutable. Elements in a set must be hashable. Thus, for example, afrozenset can be an element of a regularset whereas the opposite is not true.

Python also provides extensive collection manipulating abilities such as built in containment checking and a generic iteration protocol.

Object system

[edit]

In Python, everything is an object, even classes. Classes, as objects, have a class, which is known as theirmetaclass. Python also supportsmultiple inheritance andmixins.

The language supports extensiveintrospection of types and classes. Types can be read and compared—types are instances oftype. The attributes of an object can be extracted as a dictionary.

Operators can beoverloaded in Python by defining special member functions—for instance, defining a method named__add__ on a class permits one to use the+ operator on objects of that class.

Literals

[edit]

Strings

[edit]

Python has various kinds ofstring literals.

Normal string literals

[edit]

Either single or double quotes can be used to quote strings. Unlike in Unix shell languages,Perl or Perl-influenced languages such asRuby orGroovy, single quotes and double quotes function identically, i.e. there is no string interpolation of$foo expressions. However, interpolation can be done in various ways: with "f-strings" (since Python 3.6[12]), using theformat method or the old% string-format operator.

For instance, all of these Python statements:

print(f"I just printed{num} pages to the printer{printer}")print("I just printed{} pages to the printer{}".format(num,printer))print("I just printed{0} pages to the printer{1}".format(num,printer))print("I just printed{num} pages to the printer{printer}".format(num=num,printer=printer))print("I just printed%s pages to the printer%s"%(num,printer))print("I just printed%(num)s pages to the printer%(printer)s"%{"num":num,"printer":printer})

are equivalent to the Perl statement:

print"I just printed $num pages to the printer $printer\n"

They build a string using the variablesnum andprinter.

Multi-line string literals

[edit]

There are also multi-line strings, which begin and end with a series of three single or double quotes and function likehere documents inPerl andRuby.

A simple example withvariable interpolation (using theformat method) is:

print('''Dear{recipient},I wish you to leave Sunnydale and never return.Not Quite Love,{sender}'''.format(sender="Buffy the Vampire Slayer",recipient="Spike"))

Raw strings

[edit]

Finally, all of the previously mentioned string types come in "raw" varieties (denoted by placing a literalr before the opening quote), which do no backslash-interpolation and hence are very useful forregular expressions; compare"@-quoting" inC#. Raw strings were originally included specifically for regular expressions. Due to limitations of thetokenizer, raw strings may not have a trailing backslash.[13] Creating a raw string holding aWindows path ending with a backslash requires some variety of workaround (commonly, using forward slashes instead of backslashes, since Windows accepts both).

Examples include:

>>># A Windows path, even raw strings cannot end in a backslash>>>r"C:\Foo\Bar\Baz\"  File"<stdin>", line1r"C:\Foo\Bar\Baz\"^SyntaxError:EOL while scanning string literal>>>dos_path=r"C:\Foo\Bar\Baz\ "# avoids the error by adding>>>dos_path.rstrip()# and removing trailing space'C:\\Foo\\Bar\\Baz\\'>>>quoted_dos_path=r'"{}"'.format(dos_path)>>>quoted_dos_path'"C:\\Foo\\Bar\\Baz\\ "'>>># A regular expression matching a quoted string with possible backslash quoting>>>re.match(r'"(([^"\\]|\\.)*)"',quoted_dos_path).group(1).rstrip()'C:\\Foo\\Bar\\Baz\\'>>>code='foo(2, bar)'>>># Reverse the arguments in a two-arg function call>>>re.sub(r'\(([^,]*?),([^ ,]*?)\)',r'(\2, \1)',code)'foo(2, bar)'>>># Note that this won't work if either argument has parens or commas in it.

Concatenation of adjacent string literals

[edit]

String literals appearing contiguously and only separated by whitespace (including new lines using backslashes), are allowed and are aggregated into a single longer string.[14]Thus

title="One Good Turn: " \'A Natural History of the Screwdriver and the Screw'

is equivalent to

title="One Good Turn: A Natural History of the Screwdriver and the Screw"

Unicode

[edit]

Since Python 3.0, the default character set isUTF-8 both for source code and the interpreter. In UTF-8, unicode strings are handled like traditional byte strings. This example will work:

s="Γειά"# Hello in Greekprint(s)

Numbers

[edit]

Numeric literals in Python are of the normal sort, e.g.0,-1,3.4,3.5e-8.

Python has arbitrary-length integers and automatically increases their storage size as necessary. Prior to Python 3, there were two kinds of integral numbers: traditional fixed size integers and "long" integers of arbitrary size. The conversion to "long" integers was performed automatically when required, and thus the programmer usually did not have to be aware of the two integral types. In newer language versions the distinction is completely gone and all integers behave like arbitrary-length integers.

Python supports normalfloating point numbers, which are created when a dot is used in a literal (e.g.1.1), when an integer and a floating point number are used in an expression, or as a result of some mathematical operations ("true division" via the/ operator, or exponentiation with a negative exponent).

Python also supportscomplex numbers natively. Theimaginary component of a complex number is indicated with theJ orj suffix, e.g.3 + 4j.

Lists, tuples, sets, dictionaries

[edit]

Python has syntactic support for the creation of container types.

Lists (classlist) are mutable sequences of items of arbitrary types, and can be created either with the special syntax

a_list=[1,2,3,"a dog"]

or using normal object creation

a_second_list=[]a_second_list.append(4)a_second_list.append(5)

Tuples (classtuple) are immutable sequences of items of arbitrary types. There is also a special syntax to create tuples

a_tuple=1,2,3,"four"a_tuple=(1,2,3,"four")

Although tuples are created by separating items with commas, the whole construct is usually wrapped in parentheses to increase readability. An empty tuple is denoted by(), while a tuple with a single value can be created with(1,).

Sets (classset) are mutable containers of hashable items[15] of arbitrary types, with no duplicates. The items are not ordered, but sets support iteration over the items. The syntax for set creation uses curly brackets

some_set={0,(),False}

Python sets are very much likemathematical sets, and support operations like setintersection andunion. Python also features afrozenset class for immutable sets, seeCollection types.

Dictionaries (classdict) are mutable mappings tying keys and corresponding values. Python has special syntax to create dictionaries ({key: value})

a_dictionary={"key 1":"value 1",2:3,4:[]}

The dictionary syntax is similar to the set syntax; the difference is the presence of colons. The empty literal{} results in an empty dictionary rather than an empty set, which is instead created using the non-literal constructor:set().

Operators

[edit]

Arithmetic

[edit]

Python includes the+,-,*,/ ("true division"),// (floor division),% (modulus), and** (exponentiation) operators, with their usualmathematical precedence.

In Python 3,x / y performs "true division", meaning that it always returns a float, even if bothx andy are integers that divide evenly.

>>>4/22.0

and// performsinteger division orfloor division, returning the floor of the quotient as an integer.

In Python 2 (and most other programming languages), unless explicitly requested,x / y performed integer division, returning a float only if either input was a float. However, because Python is a dynamically-typed language, it was not always possible to tell which operation was being performed, which often led to subtle bugs, thus prompting the introduction of the// operator and the change in semantics of the/ operator in Python 3.

Comparison operators

[edit]

The comparison operators, i.e.==,!=,<,>,<=,>=,is,is not,in andnot in[16] are used on all manner of values. Numbers, strings, sequences, and mappings can all be compared. In Python 3, disparate types (such as astr and anint) do not have a consistent relative ordering, and attempts to compare these types raises aTypeError exception. While it was possible to compare disparate types in Python 2 (for example, whether a string was greater-than or less-than an integer), the ordering was undefined; this was considered a historical design quirk and was ultimately removed in Python 3.

Chained comparison expressions such asa < b < c have roughly the meaning that they have in mathematics, rather than the unusual meaning found inC and similar languages. The terms are evaluated and compared in order. The operation hasshort-circuit semantics, meaning that evaluation is guaranteed to stop as soon as a verdict is clear: ifa < b is false,c is never evaluated as the expression cannot possibly be true anymore.

For expressions without side effects,a < b < c is equivalent toa < b and b < c. However, there is a substantial difference when the expressions have side effects.a < f(x) < b will evaluatef(x) exactly once, whereasa < f(x) and f(x) < b will evaluate it twice if the value ofa is less thanf(x) and once otherwise.

Logical operators

[edit]

In all versions of Python, boolean operators treat zero values or empty values such as"",0,None,0.0,[], and{} as false, while in general treating non-empty, non-zero values as true. The boolean valuesTrue andFalse were added to the language in Python 2.2.1 as constants (subclassed from1 and0) and were changed to be full blown keywords in Python 3. The binary comparison operators such as== and> return eitherTrue orFalse.

The boolean operatorsand andor useminimal evaluation. For example,y == 0 or x/y > 100 will never raise a divide-by-zero exception. These operators return the value of the last operand evaluated, rather thanTrue orFalse. Thus the expression(4 and 5) evaluates to5, and(4 or 5) evaluates to4.

Functional programming

[edit]

A strength of Python is the availability of afunctional programming style, which makes working with lists and other collections much more straightforward.

Comprehensions

[edit]
Main article:List comprehension

One such construction is thelist comprehension, which can be expressed with the following format:

L=[mapping_expressionforelementinsource_listiffilter_expression]

Using list comprehension to calculate the first five powers of two:

powers_of_two=[2**nforninrange(1,6)]

TheQuicksort algorithm can be expressed elegantly (albeit inefficiently) using list comprehensions:

defqsort(L):ifL==[]:return[]pivot=L[0]return(qsort([xforxinL[1:]ifx<pivot])+[pivot]+qsort([xforxinL[1:]ifx>=pivot]))

Python 2.7+[17] also supports set comprehensions[18] and dictionary comprehensions.[19]

First-class functions

[edit]

In Python, functions arefirst-class objects that can be created and passed around dynamically.

Python's limited support foranonymous functions is thelambda construct. An example is the anonymous function which squares its input, called with the argument of 5:

f=lambdax:x**2f(5)

Lambdas are limited to containing anexpression rather thanstatements, although control flow can still be implemented less elegantly within lambda by using short-circuiting,[20] and more idiomatically with conditional expressions.[21]

Closures

[edit]

Python has had support forlexical closures since version 2.2. Here's an example function that returns a function thatapproximates the derivative of the given function:

defderivative(f,dx):"""Return a function that approximates the derivative of f    using an interval of dx, which should be appropriately small.    """deffunction(x):return(f(x+dx)-f(x))/dxreturnfunction

Python's syntax, though, sometimes leads programmers of other languages to think that closures are not supported.Variable scope in Python is implicitly determined by the scope in which one assigns a value to the variable, unless scope is explicitly declared withglobal ornonlocal.[22]

Note that the closure's binding of a name to some value is not mutable from within the function. Given:

>>>deffoo(a,b):...print(f'a:{a}')...print(f'b:{b}')...defbar(c):...b=c...print(f'b*:{b}')...bar(a)...print(f'b:{b}')...>>>foo(1,2)a: 1b: 2b*: 1b: 2

and you can see thatb, as visible from the closure's scope, retains the value it had; the changed binding ofb inside the inner function did not propagate out. The way around this is to use anonlocal b statement inbar. In Python 2 (which lacksnonlocal), the usual workaround is to use a mutable value and change that value, not the binding. E.g., a list with one element.

Generators

[edit]

Introduced in Python 2.2 as an optional feature and finalized in version 2.3,generators are Python's mechanism forlazy evaluation of a function that would otherwise return a space-prohibitive or computationally intensive list.

This is an example to lazily generate the prime numbers:

fromitertoolsimportcountdefgenerate_primes(stop_at=None):primes=[]fornincount(start=2):ifstop_atisnotNoneandn>stop_at:return# raises the StopIteration exceptioncomposite=Falseforpinprimes:ifnotn%p:composite=Truebreakelifp**2>n:breakifnotcomposite:primes.append(n)yieldn

When calling this function, the returned value can be iterated over much like a list:

foriingenerate_primes(100):# iterate over the primes between 0 and 100print(i)foriingenerate_primes():# iterate over ALL primes indefinitelyprint(i)

The definition of a generator appears identical to that of a function, except the keywordyield is used in place ofreturn. However, a generator is an object with persistent state, which can repeatedly enter and leave the same scope. A generator call can then be used in place of a list, or other structure whose elements will be iterated over. Whenever thefor loop in the example requires the next item, the generator is called, and yields the next item.

Generators do not have to be infinite like the prime-number example above. When a generator terminates, an internal exception is raised which indicates to any calling context that there are no more values. Afor loop or other iteration will then terminate.

Generator expressions

[edit]
Further information:List comprehension

Introduced in Python 2.4, generator expressions are thelazy evaluation equivalent of list comprehensions. Using the prime number generator provided in the above section, we might define a lazy, but not quite infinite collection.

fromitertoolsimportisliceprimes_under_million=(iforiingenerate_primes()ifi<1000000)two_thousandth_prime=islice(primes_under_million,1999,2000).next()

Most of the memory and time needed to generate this many primes will not be used until the needed element is actually accessed. Unfortunately, you cannot perform simple indexing and slicing of generators, but must use theitertools module or "roll your own" loops. In contrast, a list comprehension is functionally equivalent, but isgreedy in performing all the work:

primes_under_million=[iforiingenerate_primes(2000000)ifi<1000000]two_thousandth_prime=primes_under_million[1999]

The list comprehension will immediately create a large list (with 78498 items, in the example, but transiently creating a list of primes under two million), even if most elements are never accessed. The generator comprehension is more parsimonious.

Dictionary and set comprehensions

[edit]

While lists and generators had comprehensions/expressions, in Python versions older than 2.7 the other Python built-in collection types (dicts and sets) had to be kludged in using lists or generators:

>>>dict((n,n*n)forninrange(5)){0:0,1:1,2:4,3:9,4:16}

Python 2.7 and 3.0 unified all collection types by introducing dictionary and set comprehensions, similar to list comprehensions:

>>>[n*nforninrange(5)]# regular list comprehension[0,1,4,9,16]>>>>>>{n*nforninrange(5)}# set comprehension{0,1,4,9,16}>>>>>>{n:n*nforninrange(5)}# dict comprehension{0:0,1:1,2:4,3:9,4:16}

Objects

[edit]

Python supports most object oriented programming (OOP) techniques. It allowspolymorphism, not only within aclass hierarchy but also byduck typing. Any object can be used for any type, and it will work so long as it has the proper methods and attributes. And everything in Python is an object, including classes, functions, numbers and modules. Python also has support formetaclasses, an advanced tool for enhancing classes' functionality. Naturally,inheritance, includingmultiple inheritance, is supported. Python has very limited support for private variables usingname mangling which is rarely used in practice asinformation hiding is seen by some asunpythonic, in that it suggests that the class in question contains unaesthetic or ill-planned internals. The slogan "we're all responsible users here" is used to describe this attitude.[23]

As is true for modules, classes in Python do not put an absolute barrier between definition and user, but rather rely on the politeness of the user not to "break into the definition."

— 9. Classes,The Python 2.6 Tutorial (2013)

OOP doctrines such as the use of accessor methods to read data members are not enforced in Python. Just as Python offers functional-programming constructs but does not attempt to demandreferential transparency, it offers an object system but does not demandOOP behavior. Moreover, it is always possible to redefine the class usingproperties (seeProperties) so that when a certain variable is set or retrieved in calling code, it really invokes a function call, so thatspam.eggs = toast might really invokespam.set_eggs(toast). This nullifies the practical advantage of accessor functions, and it remainsOOP because the propertyeggs becomes a legitimate part of the object's interface: it need not reflect an implementation detail.

In version 2.2 of Python, "new-style" classes were introduced. With new-style classes, objects and types were unified, allowing the subclassing of types.Even entirely new types can be defined, complete with custom behavior for infix operators. This allows for many radical things to be done syntactically within Python. A newmethod resolution order for multiple inheritance was also adopted with Python 2.3. It is also possible to run custom code while accessing or setting attributes, though the details of those techniques have evolved between Python versions.

With statement

[edit]

Thewith statement handles resources, and allows users to work with the Context Manager protocol.[24] One function (__enter__()) is called when entering scope and another (__exit__()) when leaving. This prevents forgetting to free the resource and also handles more complicated situations such as freeing the resource when an exception occurs while it is in use. Context Managers are often used with files, database connections, test cases, etc.

Properties

[edit]

Properties allow specially defined methods to be invoked on an object instance by using the same syntax as used for attribute access. An example of a class defining some properties is:

classMyClass:def__init__(self):self._a=None@propertydefa(self):returnself._a@a.setter# makes the property writabledefa(self,value):self._a=value

Descriptors

[edit]

A class that defines one or more of the three special methods__get__(self, instance, owner),__set__(self, instance, value),__delete__(self, instance) can be used as a descriptor. Creating an instance of a descriptor as a class member of a second class makes the instance a property of the second class.[25]

Class and static methods

[edit]

Python allows the creation of class methods and static methods via the use of the@classmethod and@staticmethoddecorators. The first argument to a class method is the class object instead of the self-reference to the instance. A static method has no special first argument. Neither the instance, nor the class object is passed to a static method.

Exceptions

[edit]

Python supports (and extensively uses)exception handling as a means of testing for error conditions and other "exceptional" events in a program.

Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.

Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, theMailman mailing list software, written in Python, uses exceptions to jump out of deeply nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval.

Exceptions are often used as an alternative to theif-block, especially inthreaded situations. A commonly invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than Permission,"[26] which is attributed toGrace Hopper.[27][28] The alternative, known as LBYL, or "Look Before You Leap", explicitly tests for pre-conditions.[29]

In this first code sample, following the LBYL approach, there is an explicit check for the attribute before access:

ifhasattr(spam,'eggs'):ham=spam.eggselse:handle_missing_attr()

This second sample follows the EAFP paradigm:

try:ham=spam.eggsexceptAttributeError:handle_missing_attr()

These two code samples have the same effect, although there will be performance differences. Whenspam has the attributeeggs, the EAFP sample will run faster. Whenspam does not have the attributeeggs (the "exceptional" case), the EAFP sample will run slower. The Pythonprofiler can be used in specific cases to determine performance characteristics. If exceptional cases are rare, then the EAFP version will have superioraverage performance than the alternative. In addition, it avoids the whole class oftime-of-check-to-time-of-use (TOCTTOU) vulnerabilities, otherrace conditions,[28][30] and is compatible withduck typing. A drawback of EAFP is that it can be used only with statements; an exception cannot be caught in a generator expression, list comprehension, or lambda function.

Comments and docstrings

[edit]

There are two ways to annotate Python code. One is by using comments to indicate what some part of the code does. Single-line comments begin with the hash character (#) and continue until the end of the line. Comments spanning more than one line are achieved by inserting a multi-line string (with""" or''' as the delimiter on each end) that is not used in assignment or otherwise evaluated, but sits in between other statements.

Commenting a piece of code:

importsysdefgetline():returnsys.stdin.readline()# Get one line and return it

Commenting a piece of code with multiple lines:

defgetline():"""This function gets one line and returns it.    As a demonstration, this is a multiline docstring.    This full string can be accessed as getline.__doc__.    """returnsys.stdin.readline()

Docstrings (documentation strings), that is, strings that are located alone without assignment as the first indented line within a module, class, method or function, automatically set their contents as an attribute named__doc__, which is intended to store a human-readable description of the object's purpose, behavior, and usage. The built-inhelp function generates its output based on__doc__ attributes. Such strings can be delimited with" or' for single line strings, or may span multiple lines if delimited with either""" or''' which is Python's notation for specifying multi-line strings. However, the style guide for the language specifies that triple double quotes (""") are preferred for both single and multi-line docstrings.[31]

Single-line docstring:

defgetline():"""Get one line from stdin and return it."""returnsys.stdin.readline()

Multi-line docstring:

defgetline():"""Get one line       from stdin       and return it.    """returnsys.stdin.readline()

Docstrings can be as large as the programmer wants and containline breaks. In contrast with comments, docstrings are themselves Python objects and are part of the interpreted code that Python runs. That means that a running program can retrieve its own docstrings and manipulate that information, but the normal usage is to give other programmers information about how to invoke the object being documented in the docstring.

There are tools available that can extract the docstrings from Python code and generate documentation. Docstring documentation can also be accessed from the interpreter with thehelp() function, or from the shell with thepydoc commandpydoc.

Thedoctest standard module uses interactions copied from Python shell sessions into docstrings to create tests, whereas thedocopt module uses them to define command-line options.

Function annotations

[edit]

Function annotations (type hints) are defined in PEP 3107.[32] They allow attaching data to the arguments and return of a function. The behaviour of annotations is not defined by the language, and is left to third party frameworks. For example, a library could be written to handle static typing:[32]

defhaul(item:Haulable,*vargs:PackAnimal)->Distance

Decorators

[edit]
See also:Advice (programming)

A decorator is any callable Python object that is used to modify a function, method or class definition. A decorator is passed the original object being defined and returns a modified object, which is then bound to the name in the definition. Python decorators were inspired in part byJava annotations, and have a similar syntax; the decorator syntax is puresyntactic sugar, using@ as the keyword:

@viking_chorusdefmenu_item():print("spam")

is equivalent to

defmenu_item():print("spam")menu_item=viking_chorus(menu_item)

Decorators are a form ofmetaprogramming; they enhance the action of the function or method they decorate. For example, in the sample below,viking_chorus might causemenu_item to be run 8 times (seeSpam sketch) for each time it is called:

defviking_chorus(myfunc):definner_func(*args,**kwargs):foriinrange(8):myfunc(*args,**kwargs)returninner_func

Canonical uses of function decorators are for creatingclass methods orstatic methods, adding function attributes,tracing, settingpre- andpostconditions, andsynchronization,[33] but can be used for far more, includingtail recursion elimination,[34]memoization and even improving the writing of other decorators.[35]

Decorators can be chained by placing several on adjacent lines:

@invincible@favourite_colour("Blue")defblack_knight():pass

is equivalent to

defblack_knight():passblack_knight=invincible(favourite_colour("Blue")(black_knight))

or, using intermediate variables

defblack_knight():passblue_decorator=favourite_colour("Blue")decorated_by_blue=blue_decorator(black_knight)black_knight=invincible(decorated_by_blue)

In the example above, thefavourite_colour decoratorfactory takes an argument. Decorator factories must return a decorator, which is then called with the object to be decorated as its argument:

deffavourite_colour(colour):defdecorator(func):defwrapper():print(colour)func()returnwrapperreturndecorator

This would then decorate theblack_knight function such that the colour,"Blue", would be printed prior to theblack_knight function running.Closure ensures that the colour argument is accessible to the innermost wrapper function even when it is returned and goes out of scope, which is what allows decorators to work.

Despite the name, Python decorators are not an implementation of thedecorator pattern. The decorator pattern is adesign pattern used instatically-typedobject-oriented programming languages to allow functionality to be added to objects at run time; Python decorators add functionality to functions and methods at definition time, and thus are a higher-level construct than decorator-pattern classes. The decorator pattern itself is trivially implementable in Python, because the language isduck typed, and so is not usually considered as such.[clarification needed]

Easter eggs

[edit]

Users ofcurly bracket languages, such asC orJava, sometimes expect or wish Python to follow a block-delimiter convention. Brace-delimited block syntax has been repeatedly requested, and consistently rejected by core developers. The Python interpreter contains aneaster egg that summarizes its developers' feelings on this issue. The codefrom __future__ import braces raises the exceptionSyntaxError: not a chance. The__future__ module is normally used toprovide features from future versions of Python.

Another hidden message, theZen of Python (a summary ofPython design philosophy), is displayed when trying toimport this.

The messageHello world! is printed when the import statementimport __hello__ is used. In Python 2.7, instead ofHello world! it printsHello world....

Importing theantigravity module opens a web browser toxkcd comic353 that portrays a humorous fictional use for such a module, intended to demonstrate the ease with which Python modules enable additional functionality.[36] In Python 3, this module also contains an implementation of the "geohash" algorithm, a reference toxkcd comic426.[37]

References

[edit]
  1. ^"Readability counts." -PEP 20 - The Zen of PythonArchived 2014-12-05 at theWayback Machine
  2. ^"PEP 20 - The Zen of Python". Python Software Foundation. 2004-08-23.Archived from the original on 2008-12-03. Retrieved2008-11-24.
  3. ^"2. Lexical analysis".Python 3 documentation. Python Software Foundation. Retrieved2021-03-11.
  4. ^"2. Lexical analysis".Python v2.7.18 documentation. Python Software Foundation. Retrieved2021-03-11.
  5. ^"New Keywords".Python v3.5 documentation. Docs.python.org.Archived from the original on 2016-06-18. Retrieved2016-06-01.
  6. ^"2. Lexical analysis".Python 3 documentation. Python Software Foundation. Retrieved2022-01-22.
  7. ^"PEP 622 -- Structural Pattern Matching". 2020-06-23. Retrieved2022-01-22.
  8. ^"PEP 8 -- Style Guide for Python Code".Python.org. Retrieved2021-03-17.
  9. ^Hoffa, Felipe (2017-07-26)."400,000 GitHub repositories, 1 billion files, 14 terabytes of code: Spaces or Tabs?".Medium. Retrieved2021-03-11.
  10. ^"Tabs or Spaces".ukupat.github.io. Retrieved2021-03-11.
  11. ^"PEP 8 -- Style Guide for Python Code".Python.org. Retrieved2021-03-11.
  12. ^"PEP 498 - Literal String Interpolation".What’s New In Python 3.6. 2016-12-23.Archived from the original on 2017-03-30. Retrieved2017-03-29.
  13. ^"2. Lexical analysis".Python v2.7.5 documentation. Docs.python.org.Archived from the original on 2012-10-23. Retrieved2013-08-16.
  14. ^"2. Lexical analysis".Python v2.7.5 documentation. Docs.python.org.Archived from the original on 2012-10-23. Retrieved2013-08-16.
  15. ^Hashable items are usually immutable, but not necessarily so by definition. Seepython.org/3/glossary.htm
  16. ^"6. Expressions — Python 3.9.2 documentation".docs.python.org. Retrieved2021-03-17.
  17. ^"Python 2.7.0 Release".Archived from the original on 2016-01-27. Retrieved2016-01-19.
  18. ^"5. Data Structures — Python 2.7.18 documentation".Archived from the original on 2016-01-26. Retrieved2016-01-19.
  19. ^"5. Data Structures — Python 2.7.18 documentation".Archived from the original on 2016-01-26. Retrieved2016-01-19.
  20. ^David Mertz."Functional Programming in Python". IBM developerWorks. Archived fromthe original on 2007-02-20. Retrieved2007-08-27.
  21. ^"PEP 308 -- Conditional Expressions".Archived from the original on 2016-03-13. Retrieved2016-04-14.
  22. ^Thenonlocal keyword was adopted byPEP 3104Archived 2014-12-02 at theWayback Machine
  23. ^"Python Style Guide". docs.python-guide.org.Archived from the original on 2015-03-09. Retrieved2015-03-08.
  24. ^"PEP 343 -- The "with" Statement".Archived from the original on 2014-12-14. Retrieved2014-08-15.
  25. ^"Glossary — Python 3.9.2 documentation".docs.python.org. Retrieved2021-03-23.
  26. ^EAFPArchived 2012-10-26 at theWayback Machine, Python Glossary
  27. ^Hamblen, Diane."Only the Limits of Our Imagination: An exclusive interview with RADM Grace M. Hopper". Department of the Navy Information Technology Magazine. Archived fromthe original on January 14, 2009. Retrieved2007-01-31.
  28. ^abPython in a nutshell,Alex Martelli,p. 134
  29. ^LBYLArchived 2018-01-21 at theWayback Machine, Python Glossary
  30. ^Alex Martelli (19 May 2003)."EAFP v. LBYL". python-list mailing list.Archived from the original on 14 July 2012. Retrieved18 July 2011.
  31. ^"PEP 8 -- Style Guide for Python Code".Python.org. Retrieved2021-03-23.
  32. ^ab"PEP 3107 -- Function Annotations".Archived from the original on 2015-01-06. Retrieved2014-08-15.
  33. ^"Python 2.4 Decorators: Reducing code duplication and consolidating knowledge".Dr. Dobb's. 2005-05-01.Archived from the original on 2007-02-06. Retrieved2007-02-08.
  34. ^"New Tail Recursion Decorator".ASPN: Python Cookbook. 2006-11-14.Archived from the original on 2007-02-09. Retrieved2007-02-08.
  35. ^"The decorator module".Archived from the original on 2007-02-10. Retrieved2007-02-08.
  36. ^cpython: The Python programming language, Python, 2017-10-15,archived from the original on 2017-09-15, retrieved2017-10-15
  37. ^"Another hidden treasure. · python/cpython@b1614a7".GitHub. Retrieved2017-10-15.

External links

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Python_syntax_and_semantics&oldid=1300495648"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp