Python (programming language)

From Wikipedia, the free encyclopedia

  (Redirected from Python philosophy)
Jump to: navigation, search
Python (programming language)
Paradigm Multi-paradigm
Appeared in 1991
Designed by Guido van Rossum
Developer Python Software Foundation
Latest release 2.5.1/ 18 April 2007
Latest unstable release 3.0a2/ 7 December 2007
Typing discipline Strong, dynamic ("duck typing")
Major implementations CPython, Jython, IronPython, PyPy
Dialects Stackless Python, RPython
Influenced by ABC, ALGOL 68,[1] C, Haskell, Icon, Lisp, Modula-3, Perl, Java
Influenced Boo, Groovy, Ruby
OS Cross-platform
License Python Software Foundation License

Python is a general-purpose, high-level programming language. Its design philosophy emphasizes programmer productivity and code readability.[2] Python's core syntax and semantics are minimalist, while the standard library is large and comprehensive.

Python supports multiple programming paradigms (primarily functional, object oriented and imperative), and features a fully dynamic type system and automatic memory management; it is thus similar to Perl, Ruby, Scheme, and Tcl.

Python was first released by Guido van Rossum in 1991.[3] The language has an open, community-based development model managed by the non-profit Python Software Foundation. While various parts of the language have formal specifications and standards, the language as a whole is not formally specified. The de facto standard for the language is the CPython implementation.


[edit] History

Python logo, 1990s-2005
Python logo, 1990s-2005

Python was conceived in the late 1980s[4] by Guido van Rossum at CWI in the Netherlands as a successor of the ABC programming language capable of exception handling and interfacing with the Amoeba operating system.[5] Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is acknowledged by referring to him as its Benevolent Dictator for Life (BDFL).

In 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.[3] Already present at this stage in development were classes with inheritance, exception handling, functions, and the core datatypes of list, dict, str and so on. Also in this initial release was a module system borrowed from Modula-3; van Rossum describes the module as "one of Python's major programming units".[4] Python's exception model also resembles Modula-3's, with the addition of an else clause.[5] In 1994, comp.lang.python, the primary discussion forum for Python, was formed, marking a milestone in the growth of Python's userbase.

Python reached version 1.0 in January 1994. A major set of features included in this release were the functional programming tools lambda, map, filter and reduce. Van Rossum states that "Python acquired lambda, reduce(), filter() and map(), courtesy of (I believe) a Lisp hacker who missed them and submitted working patches."[6] The actual contributor was Amrit Prem; no specific mention of any Lisp heritage is mentioned in the release notes at the time.

The last version released from CWI was Python 1.2. In 1995, van Rossum continued his work on Python at the Corporation for National Research Initiatives (CNRI) in Reston, Virginia where he released several versions of the software.

By version 1.4, Python had acquired several new features. Notable among these are the Modula-3 inspired keyword arguments (which are also similar to Common Lisp's keyword arguments), and built-in support for complex numbers. Also included is a basic form of data hiding by name mangling, though this is easily bypassed.[7]

During van Rossum's stay at CNRI, he launched the Computer Programming for Everybody (CP4E) initiative, intending to make programming more accessible to more people, with a basic 'literacy' in programming languages, similar to the basic English literacy and mathematics skills required by most employers. Python served a central role in this: because of its focus on clean syntax, it was already suitable, and CP4E's goals bore similarities to its predecessor, ABC. The project was funded by DARPA.[8] As of 2007, the CP4E project is inactive, and while Python attempts to be easily learnable and not too arcane in its syntax and semantics, reaching out to non-programmers is not an active concern.[9]

In 2000, the Python core development team moved to to form the BeOpen PythonLabs team. CNRI requested that a version 1.6 be released, summarizing Python's development up to the point where the development team left CNRI. Consequently, the release schedules for 1.6 and 2.0 had a significant amount of overlap.[10] Python 2.0 was the first and only release from After Python 2.0 was released by, Guido van Rossum and the other PythonLabs developers joined Digital Creations.

Python 2.0 borrowed a major feature from the functional programming language Haskell: list comprehensions. Python's syntax for this construct is very similar to Haskell's, apart from Haskell's preference for punctuation characters and Python's preference for alphabetic keywords. Python 2.0 also introduced a garbage collection system capable of collecting reference cycles.[10]

Following this double release, and after van Rossum left CNRI to work with commercial software developers, it became clear that the ability to use Python with software available under the GPL was very desirable. The license used at that time, the Python License, included a clause stating that the license was governed by the State of Virginia, which made it, in the view of the Free Software Foundation's (FSF) lawyers, incompatible with the GNU GPL. CNRI and the FSF interacted to develop wording changes to Python's free software license that would make it GPL-compatible. That year (2001), van Rossum was awarded the FSF Award for the Advancement of Free Software.

Python 1.6.1 is essentially the same as Python 1.6, with a few minor bug fixes, and with the new GPL-compatible license.[11]

Python 2.1 was a derivative work of Python 1.6.1, as well as of Python 2.0. Its license was renamed Python Software Foundation License. All code, documentation and specifications added, from the time of Python 2.1's alpha release on, is owned by the Python Software Foundation (PSF), a non-profit organization formed in 2001, modeled after the Apache Software Foundation.[11] Included in this release (though off by default and not mandatory until several versions later) was an implementation of scoping more similar to static scoping rules.[12]

A major innovation in Python 2.2 was the unification of Python's types (types written in C), and classes (types written in Python) into one hierarchy. This single unification made Python's object model purely and consistently object oriented.[13] Also added were generators which were inspired by Icon.[14]

Python's standard library additions and syntactical choices were strongly influenced by Java in some cases: the logging package,[15] introduced in version 2.3,[16] the SAX parser, introduced in 2.0, and the decorator syntax that uses @,[17] added in version 2.4[18]

[edit] Future development

A Python Enhancement Proposal (or "PEP") is a standardized design document providing general information related to Python, including proposals, descriptions, and explanations for language features. PEPs are intended as the primary channel for proposing new features, and for documenting the underlying design rationale for all major elements of Python.[19] Outstanding PEPs are reviewed and commented by the BDFL.[20]

[edit] Python 3000

There are plans for a future version, to be called Python 3.0 (the project is called "Python 3000" or "Py3K") that will break backwards compatibility with the 2.x series in order to repair perceived flaws in the language. The guiding principle is to "reduce feature duplication by removing old ways of doing things". There is no definite schedule for Python 3.0, but Python 3.0a1, the first alpha release, was released on August 31, 2007,[21] and a PEP (Python Enhancement Proposal) that details planned changes exists.[22] The second alpha release, 3.0a2, was released on December 7, 2007.[23]

[edit] Philosophy

Python 3.0 is being developed with the same philosophy as in prior versions, so any reference to Python philosophy will apply to Python 3.0 as well. However, as Python has accumulated new and redundant ways to program the same task, Python 3.0 has an emphasis on removing duplicative constructs and modules, in keeping with "There should be one—and preferably only one—obvious way to do it".

Nonetheless, Python 3.0 will remain a multi-paradigm language. Coders will still have options among object orientation, structured programming, functional programming, and aspect-oriented programming and other paradigms; but within such broad choices, the details are intended to be more obvious in Python 3.0 than they have become in Python 2.x.

[edit] Timeline and compatibility

Python 3.0a1, the first alpha release of Python 3.0, was released on August 31, 2007.[21] A final release is, as of November 2007, planned for August 2008. The Python 2.x and Python 3.x series will coexist for several releases in parallel, where the 2.x series exists largely for compatibility and with some new features being backported from the 3.x series. PEP 3000 contains more information about the release schedule.

Like Perl 6, Python 3.0 will break backward compatibility. There is no requirement that Python 2.x code will run unmodified on Python 3.0. There are basic changes such as changing the print statement into a print function (so any use of the print statement will cause the program to fail), and switching to Unicode for all text strings. Python's dynamic typing combined with the plans to change the semantics of certain methods of dictionaries, for example, makes perfect mechanical translation from Python 2.x to Python 3.0 very difficult. However, a tool called "2to3" does most of the job of translation, pointing out areas where it wasn't sure using comments or warnings. Even in an alpha stage 2to3 appears to be fairly successful at performing the translation.[24] PEP 3000 recommends keeping one source (for the 2.x series), and producing releases for the Python 3.x platform using 2to3. The resulting code should not be edited until the program no longer needs to run on Python 2.x.

Python 2.6 will include forward compatibility features, as well as a "warnings" mode that will warn of potential transition problems. Warnings will be reported for builtins which will no longer exist in 3.0, as well as various old Python 2.x features that Python 3.0 will remove (see PEP 361 for more information).

[edit] Features

Some of the major changes scheduled for Python 3.0 are:

  • Changing print so that it is a built-in function, not a statement. This makes it easier to change a module to use a different print function, as well as making the syntax more regular. In Python 2.6 this can be enabled by entering from __future__ import print_function.[25]
  • Moving reduce (but not map or filter) out of the built-in namespace and into functools (the rationale being that reduce is expressed more clearly as an accumulation loop);[26]
  • Adding support for optional function annotations that can be used for informal type declarations or other purposes;[27]
  • Unifying the str/unicode types, representing text, and introducing a separate immutable bytes type; and a mostly corresponding mutable buffer type, which both represent arrays of bytes;[28]
  • Removing backward-compatibility features, including old-style classes, integer-truncating division, string exceptions, and implicit relative imports.

[edit] Usage

Main article: Python software

Some of the largest projects that use Python are the Zope application server, the Mnet distributed file store, Youtube, and the original BitTorrent client. Large organizations that make use of Python include Google[29] and NASA.[30] Air Canada's reservation management system is written in Python.[31]

Python has also seen extensive use in the information security industry. Notably, in several of the tools offered by Immunity Security,[32][33] in several of the tools offered by Core Security,[34] in the Web application security scanner Wapiti,[35] and in the fuzzer TAOF.[36] Python is commonly used in exploit development.[37][38]

Python has been successfully embedded in a number of software products as a scripting language. It is commonly used in 3D animation packages, as in Maya, Softimage XSI, Modo, Nuke and Blender. It is also used in Paint Shop Pro.[39] ESRI is now promoting Python as the best choice for writing scripts in ArcGIS.[40] It is also used in Civilization IV as the control language for modding and event interaction.[41] Eve Online, an MMORPG, is also built using Python.[42]

For many operating systems, Python is a standard component; it ships with most Linux distributions, with FreeBSD, NetBSD, and OpenBSD, and with Mac OS X. Red Hat Linux and Fedora use the pythonic Anaconda. Gentoo Linux uses Python in its package management system, Portage, and the standard tool to access it, emerge. Pardus uses it for administration and during system boot.[43]

[edit] Syntax and semantics

Syntax-highlighted Python code.
Syntax-highlighted Python code.

Python was designed to be a highly readable language. It aims toward an uncluttered visual layout, using English keywords frequently where other languages use punctuation. Python requires less boilerplate than traditional statically-typed structured languages such as C or Pascal, and has a smaller number of syntactic exceptions and special cases than either of these.[44] Python uses indentation/whitespace, rather than curly braces or keywords, to delimit statement blocks. An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block. Python's statements include:

  • The if statement, which conditionally executes a block of code, along with else and elif (a contraction of else-if).
  • The for statement, which iterates over an iterable, capturing each element to a local variable for use by the attached block.
  • The class statement, which executes a block of code and attaches its local namespace to a class, for use in object oriented programming.
  • The def statement, which defines a function.
  • The with statement which encloses a block code within a context manager (for example, acquiring a lock before the block of code is run, and releasing the lock afterwards).

Each statement has its own semantics: for example, the def statement does not execute its block immediately, unlike most other statements.

CPython does not support continuations, and according to Guido van Rossum, never will.[45] However, better support for coroutine-like functionality is provided in 2.5, by extending Python's generators.[46] Prior to 2.5, generators were lazy iterators — information was passed unidirectionally out of the generator. As of Python 2.5, it is possible to pass information back into a generator function.

Python uses duck typing, also known as latent typing. Type constraints are not checked at compile time; rather, operations on an object may fail, signifying that the given object is not of a suitable type. Despite not enforcing static typing, Python is strongly typed, forbidding operations which make little sense (for example, adding a number to a string) rather than silently attempting to make sense of them.

Python includes a number of built-in types used for a variety of purposes:

Type Description Syntax Example
str, unicode An immutable sequence of characters 'Wikipedia', u'Wikipedia'
list Mutable, can contain mixed types [4.0, 'string', True]
tuple Immutable, can contain mixed types (4.0, 'string', True)
set, frozenset Unordered, contains no duplicates set([4.0, 'string', True])
frozenset([4.0, 'string', True])
dict Group of key and value pairs {'key1': 1.0, 'key2': False}
int A fixed precision number
(may be transparently expanded to long, which is of unlimited length)
float Floating point 3.1415927
complex A complex number with real number and imaginary unit 3+2j
bool Boolean. True or False

Python also allows programmers to define their own types. This is in the form of classes, most often used for an object-oriented style of programming. New instances of classes are constructed by calling the class (ie, like FooClass()), and the classes themselves are instances of class type (itself an instance of itself), allowing metaprogramming and reflection.

Methods on objects are functions attached to the object's class; the syntax instance.method(argument) is, for normal methods and functions, syntactic sugar for Class.method(instance, argument). Python methods have an explicit self parameter to access instance data, in contrast to the implicit self in some other object-oriented programming languages (for example, Java, C++ or Ruby).[47]

[edit] Implementations

The mainstream Python implementation, also known as CPython, is written in C compliant to the C89 standard,[48] and is distributed with a large standard library written in a mixture of C and Python. CPython ships for a large number of supported platforms, including Microsoft Windows and most modern Unix-like systems. CPython was intended from almost its very conception to be cross-platform; its use and development on esoteric platforms such as Amoeba alongside more conventional ones like Unix or Macintosh has greatly helped in this regard.[49]

Stackless Python is a significant fork of CPython that implements microthreads. It can be expected to run on approximately the same platforms that CPython runs on.

There are two other major implementations: Jython for the Java platform, and IronPython for the .NET platform. PyPy is an experimental self-hosting implementation of Python, in Python, that can output a variety of types of bytecode, object code and intermediate languages.

Several programs exist to package Python programs into standalone executables, including py2exe, PyInstaller, cx_Freeze and py2app.

Many Python programs can run on different Python implementations, on such disparate operating systems and execution environments, without change. In the case of the implementations running on top of the Java virtual machine or the Common Language Runtime, the platform-independence of these systems is harnessed by their respective Python implementation.

Many third-party libraries for Python (and even some first-party ones) are only available on Windows, Linux, BSD, and Mac OS X.

In 2005 Nokia released a Python interpreter for Series 60 mobile phones called PyS60. This includes many of the modules from the regular implementations but also some additional modules for integration with the Symbian operating system. This project has been kept up to date to run on all variants of the S60 platform and there are several third party modules available such as Miso and uitricks

ChinesePython (中蟒) is a Python programming language using Chinese language lexicon.

[edit] Interpretational semantics

Most Python implementations (including CPython, the dominant implementation) can function as a command-line interpreter, where the user enters statements sequentially and receives the results immediately; in short, acting as a shell. While the semantics of the other modes of execution (bytecode compilation, or compilation to native code) preserve the sequential semantics, they offer a speed boost at the cost of interactivity, so they are only used outside of a command-line interaction (for example, importing a module).

Other shells add capabilities beyond those in the basic interpreter, including IDLE and IPython. While generally following the visual style of the Python shell, they implement features like auto-completion, retention of session state, and syntax highlighting.

Some implementations are able to compile to not only bytecode, but to turn Python code into machine code. So far, this has only been done for restricted subsets of Python. PyPy takes this approach, naming its restricted compilable version of Python RPython. Shed Skin is a similar experimental compiler.

Psyco is a specialising just in time compiler which transforms bytecode to machine code at runtime. The produced code is specialised for certain data types. Psyco is compatible with all Python code, not only a subset.[50]

[edit] Standard library

Python has a large standard library, commonly cited as one of Python's greatest strengths,[51] providing tools suited to many disparate 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. Recently, Boost C++ Libraries includes a library, python, to enable interoperability between C++ and Python. Because of the wide variety of tools provided by the standard library combined with the ability to use a lower-level language such as C and C++, which is already capable of interfacing between other libraries, Python can be a powerful glue language between languages and tools.

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 interfaces, connecting to relational databases, arithmetic with arbitrarily precise decimals, and manipulating regular expressions are also included.[52] Python also includes a unit testing framework for creating exhaustive test suites.

Some parts of the standard library are covered by specifications (for example, the WSGI implementation wsgiref follows PEP 333), but the majority of modules are defined by nothing other than their code, documentation and test suite. However, because most of the standard library is cross-platform Python code, there are only a small number of modules which must be altered or completely rewritten by alternative implementations.

[edit] Programming philosophy

Python is a multi-paradigm programming language. This means that, rather than forcing programmers to adopt a particular style of programming, it permits several styles: object orientation and structured programming are fully supported, and there are a number of language features which support functional programming and aspect-oriented programming. Many other paradigms are supported using extensions, such as pyDBC and Contracts for Python which allow Design by Contract. Python uses dynamic typing and a combination of reference counting and a cycle detecting garbage collector for memory management. An important feature of Python is dynamic name resolution, which binds method and variable names during program execution (also known as late binding).

Another target of the language's design is ease of extensibility, rather than having everything built into the language core. New built-in modules are easily written in C or C++. Python can also be used as an extension language for existing modules and applications that need a programmable interface. This design, of a small core language with a large standard library and an easily-extensible interpreter, was intended by van Rossum from the very start, due to his frustrations with ABC, which espoused the opposite mindset.[4]

The design of Python offers limited support for functional programming in the Lisp tradition. However, there are significant parallels between the philosophy of Python and that of minimalist Lisp-family languages such as Scheme. The library has two modules (itertools and functools) that implement proven functional tools borrowed from Haskell and Standard ML.[53]

While offering choice in coding methodology, the Python philosophy rejects exuberant syntax, such as in Perl, in favor of a sparser, less cluttered one. As with Perl, Python's developers expressly 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". As Alex Martelli put it in his Python Cookbook (2nd ed., p.230): "To describe something as clever is NOT considered a compliment in the Python culture." Python's philosophy rejects the Perl "there is more than one way to do it" approach to language design in favor of "there should be one—and preferably only one—obvious way to do it".[54]

Python eschews premature optimization, and moreover, rejects patches to non-critical parts of CPython which would offer a marginal increase in speed at the cost of clarity.[55] It is sometimes described as 'slow',[56] but its speed is rarely a problem since most code is not speed critical; bottlenecks can often be optimized greatly either by improvements to algorithms or data structures, or by implementing small portions in "closer to the metal" languages.[57]

[edit] Neologisms

A common neologism in the Python community 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"—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability. Unreadable code or incomprehensible idioms are unpythonic.

Users and admirers of Python—most especially those considered knowledgeable or experienced—are often referred to as Pythonists, Pythonistas, and Pythoneers.

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 SDL to Python (commonly used to create games); PyS60, an implementation for the Symbian Series 60 Operating System; PyQt and PyGTK, which bind Qt and GTK, respectively, to Python; and PyPy, a Python implementation written in Python. The prefix is also used outside of naming software packages: the major Python conference is named PyCon.

An 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.[58] For example, the metasyntactic variables often used in Python literature are spam and eggs, instead of the traditional foo and bar.

[edit] Influences on other languages

Python's design and philosophy have influenced several programming languages:

  • Boo's Python heritage is more explicit — it also uses indentation, a similar syntax, and a similar object model. Boo, however, uses static typing and is closely integrated with the .NET framework.[59]
  • Cobra is also similar to Python, using indentation for blocks. It also uses static typing and generates code designed for .NET/Mono. Cobra directly supports design-by-contract contracts.[60]
  • ECMAScript borrowed iterators, generators and list comprehensions from Python's implementation.[61]
  • Groovy was motivated by the desire to bring the Python design philosophy to Java.[62]

Python's development practices have also been emulated by other languages. The system of requiring a document describing the rationale for and issues surrounding a change to the language (ie, a PEP) is also used in Tcl directly due to Python's influence.[63]

[edit] See also

[edit] References

  1. ^ Interview with Guido van Rossum (July 1998). Retrieved on 29, 2007.
  2. ^ What is Python? Executive Summary. Python documentation. Python Foundation. Retrieved on 2007-03-21.
  3. ^ a b HISTORY. Python source distribution. Python Foundation. Retrieved on 2007-03-21.
  4. ^ a b c The Making of Python. Artima Developer. Retrieved on 2007-03-22.
  5. ^ a b Why was Python created in the first place?. Python FAQ. Retrieved on 2007-03-22.
  6. ^ Guido van Rossum. The fate of reduce() in Python 3000. Artima Developer. Retrieved on 2007-03-22.
  7. ^ LJ #37: Python 1.4 Update. Retrieved on 2007-04-29.
  8. ^ Guido van Rossum. Computer Programming for Everybody. Retrieved on 2007-03-22.
  9. ^ Computer Programming for Everybody. Python Software Foundation. Retrieved on 2007-03-22.
  10. ^ a b A.M. Kuchling and Moshe Zadka. What's New in Python 2.0. Retrieved on 2007-03-22.
  11. ^ a b History of the software. Python Library Reference. Retrieved on 2007-03-22.
  12. ^ Jeremy Hylton. Statically Nested Scopes. Retrieved on 2007-03-22.
  13. ^
  14. ^
  15. ^
  16. ^
  17. ^
  18. ^
  19. ^
  20. ^
  21. ^ a b Python 3.0a1 Release
  22. ^
  23. ^ Python 3.0a2 Release
  24. ^ Sam Ruby, 2to3, September 1, 2007
  25. ^ PEP 3105
  26. ^ Thread on Artima programmer blog
  27. ^ PEP 3197
  28. ^ PEP 3137: Immutable Bytes and Mutable Buffer
  29. ^
  30. ^
  31. ^
  32. ^
  33. ^
  34. ^ CORE Security Technologies' open source software repository
  35. ^
  36. ^
  37. ^
  38. ^
  39. ^ Documentation of the PSP Scripting API can be found at Jasc® Paint Shop Pro™ 9: Additional Download Resources
  40. ^ About getting started with writing geoprocessing scripts (Nov 2006).
  41. ^
  42. ^
  43. ^
  44. ^ Is Python a good language for beginning programmers?. General Python FAQ. Python Foundation (7 March 2005). Retrieved on 2007-03-21.
  45. ^ van Rossum, Guido (9 February 2006). Language Design Is Not Just Solving Puzzles. Artima forums. Artima. Retrieved on 2007-03-21.
  46. ^ van Rossum, Guido (21 April 2006). Coroutines via Enhanced Generators. Python Enhancement Proposals. Python Foundation. Retrieved on 2007-03-21.
  47. ^ Why must 'self' be used explicitly in method definitions and calls?. Python FAQ. Python Foundation.
  48. ^
  49. ^
  50. ^ Introduction to Psyco
  51. ^
  52. ^
  53. ^
  54. ^
  55. ^
  56. ^
  57. ^
  58. ^
  59. ^
  60. ^ Comparison to Python,
  61. ^
  62. ^ James Strachan (2003-08-29). Groovy - the birth of a new dynamic language for the Java platform.
  63. ^

[edit] External links

Wikibooks has a book on the topic of
Wikimedia Commons has media related to:
At Wikiversity, you can learn about:

Personal tools