Python (programming language) and 535: Difference between pages

(Difference between pages)
Content deleted Content added
Less silly generator example
 
m robot Adding: da
 
Line 1:
{| align=right cellpadding=3 id=toc style="margin-left: 15px;"
'''Python''' is an [[Interpreter (computer software)|interpreted]], interactive [[programming language]] created by [[Guido van Rossum]] in [[1990]]. Python is fully [[dynamic typing|dynamically typed]] and uses [[memory management|automatic memory management]]; it is thus similar to [[Perl]], [[Ruby programming language|Ruby]], [[Scheme programming language|Scheme]], [[Smalltalk]], and [[Tcl]]. Python is developed as an [[open source]] project, managed by the non-profit [[Python Software Foundation]]. Python 2.4.1 was released on [[March 30]], [[2005]].
|-
| align="center" colspan=2 | <small>'''Years:'''</small><br> [[531]] [[532]] [[533]] [[534]] - [[535]] - [[536]] [[537]] [[538]] [[539]]
|-
| align="center" colspan=2 | <small>'''[[Decades]]:'''</small> <br> [[500s]] [[510s]] [[520s]] - '''[[530s]]''' - [[540s]] [[550s]] [[560s]]
|-
| align="center" | <small>'''[[Centuries]]:'''</small> <br> [[5th century]] - '''[[6th century]]''' - [[7th century]]
|}
 
{{Infobox_Software |
name = Python |
screenshot = [[Image:PythonProgLogo.gif|150px]] |
caption = Python logo |
developer = Python Software Foundation |
latest_release_version = 2.4.1 |
latest_release_date = [[March 30]], [[2005]] |
operating_system = [[Cross-platform]] |
genre = [[Programming language]] |
license = [http://www.python.org/2.4.1/license.html Python Software Foundation License] |
website = [http://www.python.org www.python.org] |
}}
 
==History==
Python was created in the early [[1990s]] by [[Guido van Rossum]] at [[Stichting Mathematisch Centrum]] (CWI) in the [[Netherlands]] as a successor of the [[ABC programming language]]. Guido is Python's principal author, although it includes many contributions from others. Guido's continuing central role in deciding the direction of Python is jokingly acknowledged by referring to him as its [[Benevolent Dictator for Life]] (BDFL).
 
==Events==
The last version released from CWI was Python 1.2. In 1995, Guido continued his work on Python at the [[Corporation for National Research Initiatives]] (CNRI) in [[Reston, Virginia]] where he released several versions of the software. Python 1.6 was the last of the versions released by CNRI. In 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. Python 2.0 was the first and only release from BeOpen.com.
*Beginning of the [[Western Wei Dynasty]] in China. First ruler is [[Western Wei Wen Di]].
*[[Pope John II]] (533-535) is succeeded by [[Pope Agapetus I]].
*[[Justinian I]] orders [[Belisarius]] to start the reconquest of [[Italy]]; [[Mundus]] simultaneously invades [[Dalmatia]].
*[[Anthimus I of Constantinople|Anthimus]] becomes [[Patriarch of Constantinople]].
 
==Environmental Change==
Following the release of Python 1.6, and after Guido van Rossum left CNRI to work with commercial software developers, it became clear that the ability to use Python with software available under the [[GNU General Public License]] (GPL) was very desirable. CNRI and the Free Software Foundation (FSF) interacted to develop enabling wording changes to the Python license. Python 1.6.1 is essentially the same as Python 1.6, with a few minor bug fixes, and with a different license that enables later versions to be GPL-compatible. Python 2.1 is a derivative work of Python 1.6.1, as well as of Python 2.0.
*Weather is reported to be unusually cold and dark; see [[climate changes of 535-536]]
 
==Births==
After Python 2.0 was released by BeOpen.com, Guido van Rossum and the other PythonLabs developers joined Digital Creations. All intellectual property added from this point on, starting with Python
2.1 and its alpha and beta releases, is owned by the Python Software Foundation (PSF), a non-profit modeled after the Apache Software Foundation.
 
== Philosophy Deaths==
*[[May 8]] - [[Pope John II]]
*[[June 5]] - [[Epiphanius of Constantinople|Epiphanius]], [[Patriarch of Constantinople]]
*[[Amalasuntha]], queen of the [[Ostrogoths]] (killed in exile)
 
[[Category:535]]
Python is a [[Multi-paradigm programming language|multi-paradigm language]]. This means that, rather than forcing coders to adopt one particular style of coding, it permits several. [[Object orientation]], [[structured programming]], [[functional programming]], [[aspect-oriented programming]], and more recently, [[design by contract]] are all supported. Python is [[dynamic typing|dynamically type-checked]] and uses [[garbage collection (computer science)|garbage collection]] for [[memory management]]. An important feature of Python is [[dynamic name resolution]], which binds method and variable names during program execution.
 
[[af:535]]
While offering choice in coding methodology, Python's designers reject exuberant syntax, such as in Perl, in favor of a more sparse, less cluttered one. As with Perl, Python's developers expressly [http://python.org/dev/culture.html promote a particular "culture" or ideology] based on what they want the language to be, favoring language forms they see as "beautiful", "explicit" and "simple". For the most part, Perl and Python users differ in their interpretation of these terms and how they are best implemented (see [http://c2.com/cgi/wiki?ThereIsMoreThanOneWayToDoIt TIMTOWTDI] and [http://c2.com/cgi/wiki?PythonPhilosophy PythonPhilosophy]).
[[ast:535]]
 
[[bg:535]]
Another important goal of the Python developers is making Python fun to use. This is reflected in the origin of the name (after the television series ''[[Monty Python's Flying Circus]]''); in the common practice of using Monty Python references in example code; and in an occasionally playful approach to tutorials and reference materials.
[[ca:535]]
 
[[cs:535]]
Although Python is sometimes classified as a "[[scripting programming language]]", it has been used to develop many large software projects such as the [[Zope]] application server and the [[Mnet]] and [[BitTorrent]] file sharing systems. It is also extensively used by [[Google]]. Python proponents prefer to call it a high level [[dynamic programming language]], on the grounds that "scripting language" implies a language that is only used for simple [[shell script]]s or that refers to a language like [[JavaScript]]: much simpler and, for most purposes, less capable than "real" programming languages such as Python.
[[da:535]]
 
[[de:535]]
Another important goal of the language is ease of extensibility. New built-in modules are easily written in [[C programming language|C]] or [[C plus plus|C++]]. Python can also be used as an extension language for existing modules and applications that need a programmable interface.
[[el:535]]
 
[[es:535]]
Though the designer of Python is somewhat hostile to [[functional programming]] and the [[Lisp programming language|Lisp]] tradition, there are significant parallels between the philosophy of Python and that of minimalist Lisp-family languages such as [[Scheme programming language|Scheme]].
[[eo:535]]
Many past Lisp programmers have found Python appealing for this reason.
[[eu:535]]
 
[[fr:535]]
== Data types and structures ==
[[ko:535년]]
Since Python is a [[dynamic typing|dynamically typed]] language, Python ''values,'' not variables, carry type. This has implications for many aspects of the way the language functions.
[[hr:535]]
 
[[io:535]]
All values in Python are references to objects, and these references are passed to functions by value; a function cannot change the value a variable references in its calling function. Some people (including Guido van Rossum himself) have called this parameter-passing scheme "Call by object reference."
[[it:535]]
 
[[lb:535]]
Among dynamically typed languages, Python is moderately type-checked. Implicit conversion is defined for numeric types, so one may validly multiply a complex number by a long integer (for instance) without explicit casting. However, there is no implicit conversion between (e.g.) numbers and strings; a string is an invalid argument to a mathematical function expecting a number.
[[nl:535]]
 
[[no:535]]
===Base types===
[[nn:535]]
Python has a broad range of basic data types. Alongside conventional integer and floating point arithmetic, it transparently supports [[bignum|arbitrarily large integers]] and [[complex numbers]].
[[pl:535]]
 
[[pt:535]]
It supports the usual panoply of string operations, with one caveat: strings in Python are [[immutable object]]s. This means that any string operation, such as a substitution of characters, that in other programming languages might alter a string will instead return a new string in Python.
[[ro:535]]
 
[[ru:535]]
=== Collection types ===
[[sk:535]]
 
[[sl:535]]
One of the very useful aspects of Python is the concept of ''collection'' (or ''container'') types. In general a collection is an object that contains other objects in a way that is easily referenced or ''indexed''. Collections come in two basic forms: ''sequences'' and ''mappings''.
[[sr:535]]
 
[[fi:535]]
The ordered sequential types are lists (dynamic [[arrays]]), tuples, and strings. All sequences are indexed positionally (0 through ''length'' &minus; 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 sorted ''in place''.
[[sv:535]]
 
[[tt:535]]
On the other side of the collections coin are mappings, which are unordered types implemented in the form of ''dictionaries'' which "map" a set of immutable keys, to corresponding elements much like a mathematical function. The keys in a dictionary must be of an immutable Python type such as an integer or a string.
[[uk:535]]
For example, one could define a dictionary having a string <code>"foo"</code> mapped to the integer 42 or vice versa. This is done under the covers via a [[hash function]] which makes for faster lookup times, but is also the culprit for a dictionary's lack of order and is the reason mutable objects (i.e. other dictionaries or lists) cannot be used as keys.
[[zh:535年]]
Dictionaries are also central to the internals of the language as they reside at the core of all Python objects and classes: the mapping between variable names (strings) and the values which the names reference is stored as a dictionary (see [[Python programming language#Object system|Object system]]). Since these dictionaries are directly accessible (via an object's <code>__dict__</code> attribute), [[Metaprogramming (programming)|meta-programming]] is a surprisingly straightforward and natural process in Python.
 
A [[set]] collection type was added to the core language in version 2.4. A set is an unindexed, unordered collection that contains no duplicates. This container type has many applications where only ''membership'' information is required and acts essentially like a dictionary without values. There are two types of sets: ''set'' and ''frozenset'', the only difference being that ''set'' is mutable and ''frozenset'' is immutable. Elements in a set must be hashable and immutable. Thus, for example, a ''frozenset'' can be an element of a regular ''set'' 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 ===
 
In Python, everything is an object, even classes. Classes, as objects, have a class, which is known as their metaclass. Python also supports [[multiple inheritance]] and [[Mixin|mixins]] (see also [[wiki:MixinsForPython|MixinsForPython]]).
 
The language supports extensive introspection of types and classes. Types can be read and compared&mdash; types are instances of a type.
The attributes of an object can be extracted as a dictionary.
 
Operators can be overloaded in Python by defining special member functions&mdash;for instance, defining <code>__add__</code> on a class permits one to use the <code>+</code> operator on members of that class.
 
== Syntax ==
 
Python was designed to be highly readable. It has a simple visual layout, uses English keywords frequently where other languages use punctuation, and has notably fewer syntactic constructions than many structured languages such as C, Perl, or Pascal.
 
For instance, Python has only two structured loop forms:
#<code>for</code>, which loops over elements of a list or iterator (like Perl <code>foreach</code>)
#<code>while</code>, which loops as long as a boolean expression is true.
 
It thus lacks C-style complex <code>for</code>, a <code>do</code>...<code>while</code>, though of course equivalents can be expressed. Likewise, it has only <code>if</code>...<code>elif</code>...<code>else</code> for branching&mdash;no <code>switch</code> or labeled <code>goto</code> (goto was [http://www.entrian.com/goto/ implemented] as a joke for April 1st 2004, in an add-on module).
 
=== Syntactical significance of indentation ===
 
One unusual aspect of Python's syntax is its use of the [[Off-side rule|off-side rule]] to delimit program blocks. Sometimes termed "the [[whitespace]] thing", it is one aspect of Python syntax that many programmers otherwise unfamiliar with Python have heard of, since it is nearly unique among currently widespread languages.
 
In so-called "free-format" languages, that use the block structure ultimately derived from [[ALGOL]], blocks of code are set off with braces (<code>{ }</code>) or keywords. In all these languages, however, programmers conventionally indent the code within a block, to set it off visually from the surrounding code.
 
Python, instead, borrows a feature from the lesser-known language [[ABC programming language|ABC]]&mdash;instead of punctuation or keywords, it uses this indentation itself to indicate the run of a block. A brief example will make this clear.
Here are C and Python [[recursive function]]s which do the same thing&mdash;computing the [[factorial]] of an integer:
 
''Factorial function in C:''
int factorial(int x) {
if (x == 0) {
return 1;
} else {
return x * factorial(x-1);
}
}
 
''Factorial function in Python:''
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x-1)
 
Some programmers used to ALGOL-style languages, in which whitespace is semantically empty, at first find this confusing or even offensive.
A few have drawn unflattering comparison to the column-oriented style used on punched-card [[Fortran]] systems. When ALGOL was new, it was a major development to have "free-form" languages in which only symbols mattered and not their position on the line.
 
To Python programmers, however, "the whitespace thing" is simply the enforcement of a convention that programmers in ALGOL-style languages already follow anyway. They also point out that the free-form syntax has the disadvantage that, since indentation is ignored, good indentation cannot be enforced. Thus, incorrectly indented code may be misleading, since a human reader and a compiler could interpret it differently.
 
The whitespace thing has minor disadvantages. Both space characters and tab characters are currently accepted as forms of indentation. Since they are not visually distinguishable (in many tools), mixing spaces and tabs can create bugs that are particularly difficult to find (a perennial suggestion among Python users has been removing tabs as block markers&mdash;except, of course, among those Python users who propound removing spaces instead).
 
Because whitespace is syntactically significant, it is not always possible for a program to automatically correct the indentation on Python code as can be done with C or Lisp code. Moreover, formatting routines which remove whitespace&mdash;for instance, many [[Internet forum]]s&mdash;can completely destroy the syntax of a Python program, whereas a program in a bracketed language would merely become more difficult to read.
 
=== Comments and docstrings ===
 
Python has two ways to annotate Python code. One is by using comments to indicate what some part of the code does.
 
def getline():
return sys.stdin.readline() # Get one line and return it
 
Comments begin with the hash character ("#") and are terminated by the end of line. Python does not support comments that span more than one line. The other way is to use [[docstring]]s (documentation string), that is a string that is located alone without assignment as the first line within a module, class, method or function. Such strings can be delimited with <code>"</code> or <code><nowiki>'</nowiki></code> for single line strings, or may span multiple lines if delimited with either <code>"""</code> or <code><nowiki>'''</nowiki></code> which is Python's notation for specifying multi-line strings. However, the style guide for the language specifies that triple double quotes (<code>"""</code>) are preferred for both single and multi-line docstrings.
 
Single line docstring:
def getline():
"""Get one line from stdin and return it."""
return sys.stdin.readline()
 
Multi-line docstring:
def getline():
"""Get one line
from stdin
and return it."""
return sys.stdin.readline()
 
Docstrings can be as large as the programmer wants and contain [[line break]]s (if multi-line strings are used). 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 do manipulations with that info. 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 to generate an [[API]] documentation from the code. Docstring documentation can also be accessed from the interpreter with the <code>help()</code> function, or from the shell with the <code>pydoc</code> command.
 
=== Functional programming ===
 
As mentioned above, another strength of Python is the availability of a [[functional programming]] style. As may be expected, this makes working with lists and other collections much more straightforward. One such construction is the [[list comprehension]], as seen here in calculating the first five powers of two:
 
numbers = [1, 2, 3, 4, 5]
powers_of_two = [2**n for n in numbers]
 
The [[Quicksort]] algorithm can be expressed elegantly using list comprehensions:
 
def qsort(L):
if L == []: return []
return qsort([x for x in L[1:] if x< L[0] ]) + L[0:1] + \
qsort([x for x in L[1:] if x>=L[0] ])
 
Although naive execution of this form of Quicksort is less space-efficient than forms which alter the sequence in-place, it is often cited as an example of the expressive power of list comprehensions.
 
Because Python permits functions as arguments, it is also possible to partially simulate more subtle functional constructs, such as the [[continuation]].
 
==== Lambda ====
 
Python's <code>lambda</code> keyword may be misleading for some functional-programming fans. Python <code>lambda</code> blocks may only contain expressions, not statements.
Thus, they are not the most general way to return a function for use in higher-order functions.
Instead, the usual practice is to define and return a function using a locally scoped name, as in the following example of a simple [[currying|curried]] function:
 
def add_and_print_maker(x):
def temp(y):
print "%d + %d = %d" % (x, y, x+y)
return temp
 
The function can also be implemented with nested <code>lambda</code>s. To do this requires working around the Python <code>lambda</code>'s limitation, by defining a function to encapsulate the <code>print</code> statement:
 
def print_func(obj):
print obj
 
add_and_print_maker = \
lambda(x): lambda(y): \
print_func("%d + %d = %d" % (x, y, x+y))
 
The resulting <code>add_and_print_maker</code> functions perform identically: given a number ''x'' they return a function which, when given a number ''y'', will print a sentence of arithmetic. Although the first style may be more common, the second can be clearer to programmers with a functional-programming background.
 
Python's short-circuit semantics of the binary boolean operators <code>and</code> and <code>or</code> creates another useful functional feature. Using those two operators, any type of control flow can be implemented within lambda expressions [http://www-106.ibm.com/developerworks/linux/library/l-prog.html].
They are usually used for simpler purposes, however.
See the heading [[#Logical operators|logical operators]] below.
 
==== Closures ====
 
Python has had support for [[Closure (computer science)|lexical closures]] since version 2.2. See the examples in the above section on lambda for sample closure use.
 
Python's syntax, though, sometimes leads programmers of other languages to think that closures are not supported. They might try the following, for example:
 
def foo(initial_value=0):
var = initial_value
def var_setter(newval):
var = newval
def var_getter():
return var
return var_setter, var_getter
setter, getter = foo()
setter(19)
getter() # <- would return 0
 
..and they then assume closures do not work in Python. The problem, however, is a misunderstanding of Python's naming and binding rules. When a name-binding operation occurs anywhere in a function body (e.g., an assignment), that name is made local to the function and can not be a free variable. However, the same functionality can be had by using part of a mutable object as the store, for example:
 
def foo(initial_value=0):
varholder = [initial_value] # put the value into a list
def var_setter(newval):
varholder[0] = newval
def var_getter():
return varholder[0]
return var_setter, var_getter
setter, getter = foo()
setter(21)
getter() # <- would return 21
 
Since the name of the variable from the enclosing scope (<code>varholder</code>) is not rebound in <code>var_setter</code>, <code>varholder</code> becomes a free variable in <code>var_setter</code> and <code>var_setter</code> becomes a closure.
 
==== Generators ====
 
Introduced in Python 2.2 as optional feature and finalized in version 2.3, [[Generator (computer science)|generators]] are Python's mechanism for [[lazy 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:
 
import sys
def generate_primes(max=sys.maxint):
primes = []
n = 2
while n < max:
composite = False
for p in primes:
if not n % p:
composite = True
break
if not composite:
primes.append(n)
yield n
n += 1
 
To use this function simply call, e.g.:
for i in generate_primes(100):
print i,You can now use the generator generate_ints:
 
The definition of a generator appears identical to that of a function, except the keyword <code>yield</code> is used in place of <code>return</code>. However, a generator is an object with persistent state, which can repeatedly enter and leave the same dynamic extent. A generator call can then be used in place of a list, or other structure whose elements will be iterated over. Whenever the <code>for</code>-loop in the example requires the next item, the generator is called, and yields the next item.
 
==== Generator Expressions ====
Introduced in Python 2.4, Generator Expressions are the lazy evaluation equivalent of List Comprehensions. Either you could write a specific generator for it
def generate_ints(N):
for i in xrange(N):
yield i
for x in generate_ints(100):
print x
or write a slightly more concise
for x in (i for i in xrange(100)):
print x
 
Note that the example given is purely to demonstrate Generator Expressions- since xrange is an iterable itself, for the example above
for x in xrange(100):
print x
is actually simpler.
 
=== Logical operators ===
 
In Python 2.2 and earlier, the expressions <code>""</code>, <code>0</code>, <code>0.0</code>, <code>0e0</code>, <code>0j</code>, <code>None</code>, <code>False</code>, <code>()</code>, <code>[]</code>, <code>{}</code>, etc. are false, and everything else is true. When using binary Boolean operators in Python, the syntax is to have the operator be in between the two statements in question.
So to see if the statements <code>x==5</code> and <code>3</code> are true, one would write "<code>x==5 and 3</code>". To evaluate this, the interpreter would first check if <code>x==5</code> returned true. If it did not, it would return 0, but since it did, it goes on to the next statement. Next, it checks if 3 is true. Since 3 is true, 3 is returned. If three were not true, 0 would be returned. If the order of all of this were reversed to <code>3 and x==5</code>, 1 would be returned because that is what <code>x==5</code> evaluates to (because 1 is the default truth value). The <code>or</code> function works similarly. To find out if "<code>2/3 or 5</code>" is true, the interpreter first finds the truth value of 2/3. Since 2/3 evaluates to 0, as described above, it would return false. If it had returned true, then its value would be returned. Next, the interpreter looks at the second expression. Since, in this case, it returns true, 5 would be returned. It is common in Python to write statements such as <code>print p or q</code> to take advantage of this feature.
 
Later in Python 2.2.1 the constants <code>True</code> and <code>False</code> were added and, as a result, all of the binary comparison operators (<code>==</code>, <code>&gt;</code>, etc) return either <code>True</code> or <code>False</code>, while the rest of the aforementioned boolean operations (<code>and</code>, etc) still return the value that the last expression evaluated to.
Thus the expression "<code>2 == 2</code>" will return the value <code>True</code> and "<code>2 == 2 and 5</code>" still returns the integer <code>5</code>.
 
(Under the hood, in Python 2.3 and 2.4, <code>True</code> and <code>False</code> are builtin objects of type <code>bool</code>, a subclass of <code>int</code>. To keep backwards-compatibility, <code>True</code> and <code>False</code> only differ from 0 and 1 in type and string representation. Thus, statements treating the result of comparisons as ints still work. Ex. <code>print intAsStr+(" "*(fieldWidth-len(intAsStr)))</code> In 2.2.1&ndash;2.2.3, they are names for the <code>int</code> objects 1 and 0, respectively.)
 
===Comparison operators===
 
The basic comparison operators such as <code>==<code>, <code><</code>, <code>>=</code>, and so forth, are used on all manner of values. Numbers, strings, sequences, and mappings can all be compared. Objects of dissimilar type (such as a string and a number) can be compared; the result is arbitrary, but consistent.
 
Chained comparison expressions such as <code>a < b < c</code> have roughly the meaning that they have in mathematics, rather than the unusual meaning found in [[C programming language|C]] and similar languages. The terms are evaluated and compared in order. The operation is [[lazy evaluation#minimal evaluation|short circuit]], meaning that evaluation stops as soon as the expression is proven false: if <code>a < b</code> is false, <code>c</code> is never evaluated.
 
For expressions without side effects, <code>a < b < c</code> is equivalent to <code>a < b and b < c</code>. However, there is a substantial difference when the expressions have side effects. <code>a < f(x) < b</code> will evaluate <code>f(x)</code> exactly once, whereas <code>a < f(x) and f(x) < b</code> may evaluate it once or twice.
 
=== Object-oriented programming ===
 
Python's support for object oriented programming paradigm is vast. It supports [[Polymorphism_(computer_science)|polymorphism]], not only within a [[class hierarchy]] but also by [[duck 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 for [[metaclass]]es, an advanced tool for enhancing classes' functionality. Naturally, [[inheritance]], including [[multiple inheritance]], is supported. It has limited support for private variables using [[name mangling]]. See [http://www.python.org/doc/current/tut/node11.html#SECTION0011600000000000000000 the "Classes" section of the tutorial] for details.
Many Python users don't feel the need for private variables, though.
The slogan "We're all consenting adults here" is used to describe this attitude.
Some consider [[information hiding]] to be [[#Neologisms|unpythonic]], in that it suggests that the class in question contains unaesthetic or ill-planned internals.
 
From the tutorial: ''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."''
 
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 demand [[referential transparency]], it offers (and extensively uses!) its object system but does not demand OOP behavior. Moreover, it is always possible to redefine the class using ''properties'' so that when a certain variable is set or retrieved in calling code, it really invokes a function call, so that <code>foo.x = y</code> might really invoke <code>foo.set_x(y)</code>. This nullifies the practical advantage of accessor functions, and it remains OOP because the property 'x' 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 new types entirely can be defined, complete with custom behavior for infix operators. This allows for many radical things to be done syntactically within Python. A new [[multiple inheritance]] model was adopted with new-style classes, making a much more logical order of inheritance.
The new method <code>__getattribute__</code> was also defined for unconditional handling of attribute access.
 
=== Exception handling ===
 
Python supports (and extensively uses) [[exception handling]] as a means of testing for error conditions and other "exceptional" events in a program. Indeed, it is even possible to trap the exception caused by a [[syntax error]].
 
Python style calls for the use of exceptions whenever an error condition might arise. Indeed, 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, the [[GNU Mailman|Mailman]] 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, especially in [[Thread (computer science)|threaded]] situations, used as an alternative to the <code>if</code>-block. A commonly-invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than to ask for Permission." Consider these two equivalent pieces of code:
 
try:
baz = foo.bar
except AttributeError:
handle_error()
 
if hasattr(foo, 'bar'):
baz = foo.bar
else:
handle_error()
 
== Standard library ==
 
[[Image:Python batteries included.jpg|thumb|300px|Python comes with "batteries included"]]
 
Python has a large [[standard library]], which makes it well suited to many tasks. This comes from a so-called "batteries included" philosophy for Python modules.
The modules of the standard library can be augmented with custom modules written in either C or Python. The standard library is particularly well tailored to writing Internet-facing applications, with a large number of standard formats and protocols (such as [[MIME]] and [[HTTP]]) supported. Modules for creating [[graphical user interface]]s, connecting to [[relational database]]s, arithmetic with [http://www.python.org/peps/pep-0327.html arbitrarily precise decimals], and manipulating [[regular expression]]s are also included.
 
The standard library is one of Python's greatest strengths. The bulk of it is cross-platform compatible, meaning that even heavily leveraged Python programs can often run on Unix, Windows, Macintosh, and other platforms without change.
 
It is currently being debated whether or not third-party but open source Python modules such as [[Twisted]], [[Numerical Python|NumPy]], or [[wxPython]] should be included in the standard library, in accordance with the batteries included philosophy.
 
== Other features ==
The Python interpreter also supports an ''interactive mode'' in which expressions can be entered from the terminal and results seen immediately. This is a boon for those learning the language and experienced developers alike: snippets of code can be tested in interactive mode before integrating them into a program proper.
 
Python also includes a [[unit testing]] framework for creating exhaustive test suites. While [[Static_typing|static typing]] aficionados see this as a replacement for a static type-checking system, Python programmers largely do not share this view.
 
Standard Python does not support [[continuations]] (and never will, according to [[Guido van Rossum]]), but there is a variant known as [[Stackless Python]] that does. However, support for [[coroutine]]s (based on generators) is planned, see [http://www.python.org/peps/pep-0342.html].
 
== Neologisms ==
 
A few [[neologism]]s have come into common use within the Python community.
One of the most common is '''"pythonic"''', which can have a wide range of meanings related to program style. To say that a piece of code is pythonic is to say that it uses Python idioms well; that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms; that its use meshes well with the rest of the language.
 
In contrast, a mark of '''unpythonic''' code is that it attempts to "write C++ (or Lisp, or Perl) code in Python"&mdash;that is, provides a rough transcription rather than an idiomatic translation of forms from another language.
 
The prefix ''Py-'' can be used to show that something is related to Python. Examples of the use of this prefix in names of Python applications or libraries include [[Pygame]], a binding of [[Simple DirectMedia Layer|SDL]] to Python; [http://pyui.sourceforge.net/ PyUI], a GUI encoded entirely in Python; PySol, a series of card games programmed in Python; and PyAlaMode, an IDE for Python created by [[Orbtech]], a company specializing in Python.
 
Users and admirers of Python&mdash;most especially those considered knowledgeable or experienced&mdash;are often referred to as '''Pythonistas'''.
 
==Supported platforms==
 
The most popular (and therefore best maintained) platforms Python runs on are [[Linux]], [[BSD]], [[Mac OS X]], [[Microsoft Windows]] and [[Java virtual machine|Java]] (this JVM version is a separate implementation). Other supported platforms include:
 
* [[Amiga]]
* [[AROS]]
* [[AS/400]]
* [[BeOS]]
* [[Berkeley Software Distribution|BSD]]
* [[FreeBSD]]
* [[Mac OS 9]]
* [[NetBSD]]
* [[OpenBSD]]
* [[OS/2]]
* [[OS/390]]
* Other [[Unix]]es, e.g. [[Irix]]
* [[Palm OS]]
* [[Plan 9]]
* [[PlayStation 2]]
* [[Psion]]
* [[QNX]]
* [[RISC OS]] (formerly Acorn)
* [[Sharp Zaurus]]
* [[SPARC]] [[Solaris Operating Environment|Solaris]]
* [[Symbian OS]]
* [[VMS]]
* [[VxWorks]]
* [[Windows CE]]/[[Pocket PC]]
* [[Xbox]] (Used primarily in the [[XBMC]] project)
* [[z/OS]]
 
Most of the third-party libraries for Python (and even some first-party ones) are only available on Windows, Linux, BSD, and Mac OS X.
 
Python was originally developed as a [[scripting]] language for the [[Amoeba distributed operating system|Amoeba]] operating system capable of making [[system call]]s; that version is no longer maintained.
 
==Python usage==
Python is actively used by many people, both in industry and academia for a wide variety of purposes. [http://pythonology.com/success Pythonology] lists numerous Python success stories in many types of application and problem domains.
 
===Major organizations using Python===
* [[Google]] uses Python for many tasks including the backends of web apps such as [[Gmail]] and [[Google Maps]] and for many of its search-engine internals.
 
===Software written in Python===
 
* [[BitTorrent]], the original implementation and several derivatives.
* [[Chandler (PIM)|Chandler]] is a personal information manager including calendar, email, tasks and notes support.
* [[GNOME]], the [[Desktop environment|desktop environment]], makes use of python for building graphical interfaces with the [[GTK]] toolkit.
* [[GNU Mailman|Mailman]], one of the more popular packages for running email mailing lists.
* [[MoinMoin]], a popular wiki engine in Python.
* [[OpenRPG]] provides a virtual table on which to play Role Playing Games over the internet.
* [[Portage (software)|Portage]], the heart of Gentoo Linux. An advanced package management system based on the *BSD style ports system.
* [[Solipsis|Solipsis]], a system for massively shared virtual world.
* [[Trac]] - bug/issue tracking database, integrated with [[MoinMoin]] wiki and [[Subversion (software)|Subversion]] source version control
* [[ViewCVS]], a web-based interface for browsing [[Concurrent Versions System|CVS]] repositories
* [[Wikipedia]] has a Python framework for creating [http://meta.wikimedia.org/wiki/Category:Pywikipedia webbots].
* [[Zope]], an object-oriented web-application platform. Zope includes an application server with an integrated object-oriented database and a built-in web-based management interface.
 
===Packages for Python===
 
The [http://www.python.org/pypi Python Cheese Shop] and [http://www.vex.net/parnassus/ Vaults of Parnassus] are two primary directories of hundereds of Python packages.
 
* [[matplotlib]], http://matplotlib.sf.net ,an extension providing matlab-like plotting and mathematical functions
* [[mod_python]], an [[Apache server|Apache]] module allowing direct integration of Python scripts with the Apache web server.
* [[Numeric Python]], a language extension that adds support for large, multi-dimensional arrays and matrices.
* [[Pygame]] http://www.pygame.org Python game development
* [[PyGTK]], http://www.pygtk.org/, a popular cross-platform GUI library based on GTK+
* [[Python Imaging Library]], a module for working with images
* [http://www.riverbankcomputing.co.uk/pyqt/ PyQt], another popular cross-platform GUI library based on Qt
* [http://www.mems-exchange.org/software/quixote/ Quixote] a framework for developing Web applications in Python
* [[SciPy]], a library of scientific and numerical routines
* [[Twisted]], a networking framework for Python
* [http://www.wxpython.org/ wxPython], a port of [[wxWidgets]] and a popular cross-platform GUI library for Python
* [http://zope.org/Wikis/ZODB/FrontPage/guide/zodb.html ZODB] a Python-specific object-oriented database
 
=== Python Implementations ===
* [http://www.python.org CPython] - Python default/reference implementation
* [[Jython]] - Python coded in Java
* [[IronPython]] - Python for [[Microsoft .NET|.NET]] and [[Mono development platform|Mono]] platforms
* [[Boo programming language|Boo]] - Python-based but with [[static typing]], for [[Microsoft .NET|.NET]] and [[Mono development platform|Mono]]
* [http://www.stackless.com/ Stackless Python]
* [http://codespeak.net/pypy/ PyPy] - Python coded in Python
* [[Parrot virtual machine|Parrot]] - Virtual machine being developed mainly as the runtime for Perl 6, but with the intent to also support dynamic languages like Python, Ruby, Tcl, etc. Can currently execute a subset of Python.
* [http://livelogix.net/logix/ Logix] - Python alternate front-end with macros
 
==External links and references==
{{wikibookspar|Programming|Python}}
===Books===
* [http://www.techbooksforfree.com/perlpython.shtml Free downloads of Python books]
*[http://www.network-theory.co.uk/python/language/ The Python Language Reference Manual] by Guido van Rossum and Fred L. Drake, Jr. (ISBN 0-9541617-8-5)
*[http://www.byteofpython.info/ ''A Byte of Python''] is a beginner's book on Python.
*[http://www.greenteapress.com/thinkpython/ ''How to Think Like a Computer Scientist: Learning with Python''] is an introduction to function-based programming constructs using Python - free download available or hardcopy may be purchased. (ISBN 0971677506)
*[http://www.gnosis.cx/TPiP/ Text Processing in Python] by [[David Mertz]] is an intermediate Python book, available both online for free and for money from [[Addison-Wesley]]. (ISBN 0321112547)
*''[[Dive into Python]]'' demonstrates clever and useful Python paradigms for readers who know how to program already. It is [http://www.diveintopython.org/toc.html available online], or hardcopy may be purchased.
*[http://www.fbeedle.com/99-6.html ''Python Programming: An Introduction to Computer Science''] by John Zelle is an introduction to programming using Python, and is suitable for beginning programmers.
 
===Web resources===
* [http://www.python.org/ Python.org] &mdash; Official project home.
* [http://www.python.org/doc/versions.html Python Documentation]
* [http://www.python.org/doc/ Python Tutorials and References] &mdash; Several are available from Python.org.
* [http://www.python.org/cgi-bin/moinmoin Python Wiki]
* [http://www.faqts.com/knowledge_base/index.phtml/fid/199 Python FAQTs]
* [http://wiki.cs.uiuc.edu/cs427/python The Architecture of Python] discusses Python internals.
* [http://www.pyzine.com/ ''Py''], "The Python Online Technical Journal".
* [http://www.codesampler.com/python.htm Samples to extend and embed Python with C/C++]
* [http://www.pycode.com/ PyCode] &mdash; Python Resources and Modules collection.
* [http://dmoz.org/Computers/Programming/Languages/Python Open Directory: Python] &mdash; Many Python resources.
* The [http://www.vex.net/parnassus/ Vaults of Parnassus] &mdash; Links to resources.
* [http://www.vex.net/parnassus/parnassus-story.html Vaults story] &mdash; Python humor.
* [http://xahlee.org/perl-python/python.html A-Python-A-Day] &mdash; Mailing list with daily examples of Python use. Home page has links to many past tips. Examples given in Python and Perl to help Perl programmers learn Python.
* [http://wiki.python.org/moin/PythonSpeed/PerformanceTips Python Performance Tips] &mdash; Tips and tricks to help you improve the performance of python programs.
* [http://pythonphotos.org/ PythonPhotos.org] &mdash; Public photo archive for the Python developer community.
* [http://www.ibiblio.org/obp/pyBiblio/pythonvideo.php Python Bibliotheca] &mdash; Features video: "Introducing Python" with "A Python Love Story", also books, practice problems, workshops, communities, poetry, all are open content.
* [http://gnosis.cx/publish/tech_index_cp.html Charming Python] &mdash; Series of articles on Python topics by [[David Mertz]].
* [http://heather.cs.ucdavis.edu/~matloff/python.html Norm Matloff's Quick Python Tutorials ] &mdash; UC Davis Professor Norm Matloff's published Python web resources for his students and Python explorers.
 
===Non-English resources===
*[http://www.pythonbrasil.com.br/ Python Wiki in Portuguese]
*[http://www.pythonwiki.de/ Python Wiki in German]
 
 
{{Major programming languages small}}
 
[[Category:Object-oriented programming languages]]
[[Category:Dynamically-typed programming languages]]
[[Category:Scripting languages]]
[[Category:Python programming language]]
[[Category:Free software]]
 
[[ar:بيثون]]
[[bg:Python]]
[[ca:Python]]
[[cs:Python]]
[[da:Python (programmeringssprog)]]
[[de:Python (Programmiersprache)]]
[[es:Lenguaje de programación Python]]
[[eo:Python (programlingvo)]]
[[fr:Python (langage)]]
[[gl:Python]]
[[ko:파이썬]]
[[it:Python]]
[[he:Python]]
[[lt:Python]]
[[hu:Python programozási nyelv]]
[[nl:Python (programmeertaal)]]
[[ja:Python]]
[[no:Python]]
[[pl:Python]]
[[pt:Python]]
[[ru:Python]]
[[sk:Python (programovací jazyk)]]
[[sl:Python (programski jezik)]]
[[sr:Python]]
[[fi:Python]]
[[sv:Python (programspråk)]]
[[th:ภาษาไพธอน]]
[[tr:Python]]
[[zh:Python]]