Python (programming language): Difference between revisions
wikify object-oriented |
|||
Line 194: | Line 194: | ||
In contrast to some lower-level languages, Python's design does not emphasize runtime speed. While Python implementations are generally comparable to that of other bytecode interpreted languages, a concern for clarity of code always comes first in Python's design. In the Python community, one sometimes hears the slogan, "Speed is not a problem until it is a problem". This sentiment is not unique to Python programmers, but they emphasize it more than some other language communities.{{Fact|date=January 2007}} |
In contrast to some lower-level languages, Python's design does not emphasize runtime speed. While Python implementations are generally comparable to that of other bytecode interpreted languages, a concern for clarity of code always comes first in Python's design. In the Python community, one sometimes hears the slogan, "Speed is not a problem until it is a problem". This sentiment is not unique to Python programmers, but they emphasize it more than some other language communities.{{Fact|date=January 2007}} |
||
In the relatively rare cases where optimization is genuinely necessary, the ''Pythonic'' solution comes in several stages: (0) Initial profiling to find out where the genuine bottlenecks are; (1) improving algorithms within the code; (2) improving data structures within the code, perhaps using popular extension types; (3) employing existing libraries |
In the relatively rare cases where optimization is genuinely necessary, the ''Pythonic'' solution comes in several stages: (0) Initial profiling to find out where the genuine bottlenecks are; (1) improving algorithms within the code; (2) improving data structures within the code, perhaps using popular extension types; (3) employing existing libraries designed to do special tasks quickly; (4) running the program using the [[Psyco]] [[just-in-time]] compiler (on [[x86]] platforms); (5) rewriting performance-critical parts of code with [[Pyrex (programming language)|Pyrex]] or with [[SWIG]]/C or another non-Python wrapped language. |
||
== Influences of Python on other languages == |
== Influences of Python on other languages == |
Revision as of 05:20, 28 January 2007
File:Python logo.svg | |
Paradigm | Multi-paradigm |
---|---|
Designed by | Guido van Rossum |
Developer | Python Software Foundation |
First appeared | 1990 |
Stable release | 2.5
/ September 19 2006 |
Typing discipline | Strong, dynamic ("duck typing") |
OS | Cross-platform |
License | Python Software Foundation License |
Website | http://www.python.org/ |
Major implementations | |
CPython, Jython, IronPython, PyPy | |
Dialects | |
Stackless Python | |
Influenced by | |
ABC C | |
Influenced | |
Ruby, Boo |
Python is an object-oriented high-level programming language created by Guido van Rossum in 1990. Python has a fully dynamic type system and uses automatic memory management; it is thus similar to Perl, Ruby, Scheme, Smalltalk, and Tcl.
The philosophy behind Python is noteworthy among high-level programming languages because it emphasizes the importance of programmer effort over computer effort, and because it rejects more arcane language features, prioritizing readability over speed or expressiveness. Python is often characterised as minimalist, although this only applies to the core language's syntax and semantics; the standard library provides the language with a large number of additional libraries and extensions.
Miscellaneous parts of the language have formal specifications and standards, but not the language as a whole. The de facto standard for the language is the CPython implementation, which is a bytecode compiler and interpreter, although there are other implementations available. CPython is developed as an open source project, managed by the non-profit Python Software Foundation, and is available under a free software license from the project website.
History
Python was created in the early 1990s 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.[2] 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).
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. Python 1.6 was the last of the versions released by CNRI.
Following the release of Python 1.6, 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 enabling 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.[3]
In 2000, 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. After Python 2.0 was released by BeOpen.com, Guido van Rossum and the other PythonLabs developers joined Digital Creations.
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, modelled after the Apache Software Foundation.[3]
The current production version is 2.5.
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.[4] Outstanding PEPs are reviewed and commentated by the BDFL.[5]
Python developers have an ongoing discussion of a future version 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 a PEP (Python Enhancement Proposal) that details planned changes exists.[6]
Planned changes include:
- move map, filter and reduce out of the built-in namespace (the rationale being that map and filter are expressed more clearly as list comprehensions, and reduce more clearly as an accumulation loop)
- add support for optional type declarations
- unify the
str
/unicode
types, and introduce a separate mutablebytes
type - convert built-ins to returning iterators (instead of lists), where appropriate
- remove backwards-compatibility features like classic classes, classic division, string exceptions, implicit relative imports
Usage
The Python programming language is actively used in industry and academia for a wide variety of purposes. Some of the largest projects that utilise Python are the Zope application server, the Mnet distributed file store, and BitTorrent file sharing system. It is also extensively used by Google[7] and NASA.[8]
Python is a required component of some operating systems; Gentoo uses it extensively in its package management system, Portage, and the standard tool to access it, emerge.
Syntax and semantics
Python was designed to be a highly readable language. It aims toward an uncluttered 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. Python uses indentation, rather than curly braces, 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 withelse
andelif
(a contraction of else-if). - The
while
statement, which runs a block of code until a condition isFalse
. - 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.
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.[9] However, better support for coroutine-like functionality is provided in 2.5, by extending Python's generators.[10] Prior to 2.5, generators were lazy iterators — information was passed monodirectionally out of the generator.
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 several simple data types, including int
for representing integers and float
for floating-point numbers. The language also includes a bool
type for Boolean operations. There is also a complex
type for complex numbers.
In addition to those four numeric data types, Python includes a number of built-in types used for a variety of purposes. This list describes the most commonly-used types; Python provides many more.[1]
Type | Kind | Notes | Syntax Example |
---|---|---|---|
str
|
String | Immutable | 'Wikipedia'
|
unicode
|
String | Unicode version of str
|
u'Wikipedia'
|
list
|
Sequence | Mutable, can contain mixed types | [4.0, 'string', True]
|
tuple
|
Sequence | Immutable, often used as "record" | (4.0, 'string', True)
|
set
|
Set | Unordered, contains no duplicates | set([4.0, 'string', True])
|
dict
|
Mapping | Group of key and value pairs | {'key1': 1.0, 'key2': False}
|
int
|
Integer | Fixed-precision | 42
|
long
|
Integer | Arbitrary-precision | 42L or 45666786151987643L
|
float
|
Number | Floating point | 3.1415927
|
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)
. This is why Python methods must 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 or Ruby).[11] This is more closely related to multiple dispatch than the traditional object-oriented message passing model; every parameter is passed to the function in the same way, rather than special casing the receiver object.
Other features
The standard Python interpreter also supports an interactive mode in which it acts as a kind of shell: expressions can be entered one at a time, and the result of their evaluation is 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 proper program. As well, the Python shell is often used to interactively perform system tasks, such as modifying files.
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.
Implementations
The mainstream Python implementation, also known as CPython, is written in C, 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 most modern Unices and Microsoft Windows; see the full list for more. The codebase is written in compliant C89, and is easily portable to most operating systems, especially POSIX-compliant or Unix-like operating systems.
Python was originally developed as a scripting language for the Amoeba distributed operating system which was capable of making system calls; however, that version is no longer maintained. 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.[12]
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 and object code. Several other experimental implementations have been created, but have not yet been widely adopted.
Several programs exist to package Python programs into standalone executables, including py2exe 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.
Standard library
Python has a large standard library, 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.[13] Python also includes a unit testing framework for creating exhaustive test suites.
It is currently being debated whether or not third-party but open source Python modules such as Twisted, NumPy, or wxPython should be included in the standard library, in accordance with the batteries included philosophy.
The standard library is commonly cited as one of Python's greatest strengths.[citation needed] Although (barring a few exceptions) the standard library is solely defined by its CPython implementation, the bulk of it is cross-platform Python code.
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 reference counting for memory management. An important feature of Python is dynamic name resolution, which binds method and variable names during program execution.
Another target of the language's design is ease of extensibility. 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.
Though the design of Python is somewhat hostile to functional programming and the Lisp tradition (no tail-call elimination nor good support for anonymous closures), there are significant parallels between the philosophy of Python and that of minimalist Lisp-family languages such as Scheme.
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 favour of advocating a single "right" approach to problem solving.[14]
In contrast to some lower-level languages, Python's design does not emphasize runtime speed. While Python implementations are generally comparable to that of other bytecode interpreted languages, a concern for clarity of code always comes first in Python's design. In the Python community, one sometimes hears the slogan, "Speed is not a problem until it is a problem". This sentiment is not unique to Python programmers, but they emphasize it more than some other language communities.[citation needed]
In the relatively rare cases where optimization is genuinely necessary, the Pythonic solution comes in several stages: (0) Initial profiling to find out where the genuine bottlenecks are; (1) improving algorithms within the code; (2) improving data structures within the code, perhaps using popular extension types; (3) employing existing libraries designed to do special tasks quickly; (4) running the program using the Psyco just-in-time compiler (on x86 platforms); (5) rewriting performance-critical parts of code with Pyrex or with SWIG/C or another non-Python wrapped language.
Influences of Python 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.
- ECMAScript of which javascript is an extension, is borrowing iterators, generators and list comprehensions from Python's implementation.
- Ruby is influenced by Python.
- Groovy was motivated by the desire to bring the Python design philosophy to Java.
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); PyUI, a GUI encoded entirely in Python; PyQt, Qt bindings for Python; PyGTK, GTK toolkit bindings; and PySol, a series of solitaire card games programmed in Python; or pyMPI, a parallel, distributed version of CPython with MPI bindings.
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. For example, the metasyntactic variables often used in Python literature are spam and eggs, instead of the traditional foo and bar.
References
- ^ Computer Languages History
- ^ "Why was Python created in the first place?". Python FAQ.
- ^ a b http://docs.python.org/lib/node951.html
- ^ http://www.python.org/dev/peps
- ^ http://www.python.org/doc/essays/pepparade.html
- ^ http://www.python.org/peps/pep-3000.html
- ^ http://python.org/Quotes.html
- ^ http://www.python.org/about/success/usa/
- ^ http://www.artima.com/weblogs/viewpost.jsp?thread=147358
- ^ http://www.python.org/peps/pep-0342.html
- ^ "Why must 'self' be used explicitly in method definitions and calls?". Python FAQ.
- ^ http://www.oreilly.com/pub/a/oreilly/frank/rossum_1099.html
- ^ http://www.python.org/peps/pep-0327.html
- ^ http://www.python.org/dev/peps/pep-0020/
See also
Additional Reading
- The Python Language Reference Manual by Guido van Rossum and Fred L. Drake, Jr. (ISBN 0-9541617-8-5)
- 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 0-9716775-0-6)
- Text Processing in Python by David Mertz is an intermediate Python book, available both online for free and for money from Addison-Wesley. (ISBN 0-321-11254-7)
- A Byte of Python is a beginner's book on Python. Also available online as a wiki.
- Dive into Python demonstrates clever and useful Python paradigms for readers who know how to program already. It is available online, or hardcopy may be purchased.
- Core Python Programming, 2nd Edition by Wesley Chun (ISBN 0-13-226993-7)
- Py, "The Python Online Technical Journal".
External links
- Python Official Website
- Python FAQTs
- The Architecture of Python discusses Python internals.
- Charming Python — Series of articles on Python topics by David Mertz.
- Norm Matloff's Quick Python Tutorials — UC Davis Professor Norm Matloff's published Python web resources for his students and Python explorers.
- Useless Python - A repository of Python code, mostly semi-serious or throwaway code that has lived longer than expected.
- Python 2.4 Quick Reference - Compact overview of the core language features
- Template:Dmoz
- Google Tech Talk: Python 3000 - Video recorded 21 July 2006, spoken by Guido van Rossum