Old 12-09-2008, 01:34 PM
  post #1
ေမာင္ဧက
ကေလးေပါက္စ
 
အသင္း၀င္ေန႔စြဲ: Sep 2008
ေရးသားခ်က္မ်ား: 32
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 4
ပို႔စ္ 11 ခုအတြက္ 43 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
ေမာင္ဧက is on a distinguished road
phython

ကြၽန္ေတာ္ကအခုမွေလ့လာရမွာေလ
ၾကားဘူးေနတာၾကာၿပီေလ အခုမွေလ့လာခ်င္စိတ္ေပၚတာနဲ႔တင္
ebook ေတြရွာေနတာေလ သိပ္မေတြ႕ေသးဘူးဗ် နည္းနည္းပဲေတြ႔ေသးတာ
website ေတြကေနေတြ႔ရတဲ႔ သူ႔အေၾကာင္းေလးေတြကုိ တင္ျပေပးပါ႔မယ္
sharing လုပ္ၾကတာေပါ႔ဗ်ာ
ေမာင္ဧက is offline   Reply With Quote
Old 12-09-2008, 01:40 PM
  post #2
akaris
ထိပ္တန္းပညာရွင္
 
အသင္း၀င္ေန႔စြဲ: Apr 2008
တည္ေနရာ: NPT
ေရးသားခ်က္မ်ား: 889
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 94
ပို႔စ္ 196 ခုအတြက္ 356 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
akaris is on a distinguished road
ျပန္စာ - phython

အိုေကေလ...
ေရးမယ္ဆိုလည္း စၿပီးေရးပါေတာ႔ ...
ဘာလဲဆိုတာ စိတ္ဝင္စားပါတယ္....

[COLOR="Blue"][SIZE="3"]ရံုးထြက္ဖို႔ ခက္တဲ႔ ဘဝ သံသရာထဲမွာ ႀကိဳးစားရုန္းကန္မႈေတြ နဲ႔
စိန္ေခၚမႈေတြကို ရင္ဆိုင္မယ္....![/SIZE][/COLOR]:tbc:
akaris is offline   Reply With Quote
Old 12-09-2008, 01:49 PM
  post #3
ေမာင္ဧက
ကေလးေပါက္စ
 
အသင္း၀င္ေန႔စြဲ: Sep 2008
ေရးသားခ်က္မ်ား: 32
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 4
ပို႔စ္ 11 ခုအတြက္ 43 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
ေမာင္ဧက is on a distinguished road
ျပန္စာ - phython

ဟုတ္ကဲ႔ပါခင္ဗ်ာ
ေရးေပးပါမယ့္ခင္ဗ်ာ ebook ေတြကုိ အရင္ ရွာေနလုိ႔ပါ
ေနာက္ၿပီး အခုမွစေရးဘူးတာဆုိေတာ့ မွားသြားမွာလဲေၾကာက္လုိ႔ ေသခ်ာေအာင္ျပင္ဆင္ေနလုိ႔ပါ ခင္ဗ်ာ
ခြင့္လႊတ္ေပးၾကပါခင္ဗ်ာ
ေမာင္ဧက is offline   Reply With Quote
Old 12-09-2008, 03:11 PM
  post #4
ေမာင္ဧက
ကေလးေပါက္စ
 
အသင္း၀င္ေန႔စြဲ: Sep 2008
ေရးသားခ်က္မ်ား: 32
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 4
ပို႔စ္ 11 ခုအတြက္ 43 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
ေမာင္ဧက is on a distinguished road
Table ျပန္စာ - phython

့ Online စြယ္စုံက်မ္းႀကီးကေန ရွာေဖြထားတာေလးပါ


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

Publication
In 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources. 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". Python's exception model also resembles Modula-3's, with the addition of an else clause. In 1994 comp.lang.python, the primary discussion forum for Python, was formed, marking a milestone in the growth of Python's userbase

Version 1.0
Python reached version 1.0 in January 1994. The major new features included in this release were the functional programming tools lambda, map, filter and reduce. Van Rossum stated that “Python acquired lambda, reduce(), filter() and map(), courtesy of (I believe) a Lisp hacker who missed them and submitted working patches.”

The last version released while van Rossum was at 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 from which he released several versions.

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.

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. As of 2007[update], 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.
In 2000, the Python core development team moved to BeOpen.com 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.[11] 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.

The Python 1.6 release included a new CNRI license that was substantially longer than the CWI license that had been used for earlier releases. The new license included a clause stating that the license was governed by the laws of the State of Virginia. The Free Software Foundation argued that the choice-of-law clause was incompatible with the GNU GPL. BeOpen, CNRI, and the FSF negotiated a change to Python's free software license that would make it GPL-compatible. 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.

Version 2.0
Python 2.0 introduced list comprehensions, a feature borrowed from the functional programming languages SETL and Haskell. 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.

Python 2.1 was close to Python 1.6.1, as well as 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. The release included a change to the language specification to support nested scopes, like other statically scoped languages. (The feature was turned off by default, and not required, until Python 2.2.)

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. Also added were generators which were inspired by Icon.

Version 3.0
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". Python 3.0a1, the first alpha release, was released on August 31, 2007, and a PEP (Python Enhancement Proposal) that details planned changes exists. The last beta release, 3.0b3, was released on August 20, 2008.
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.
Python 3.0a1, the first alpha release of Python 3.0, was released on August 31, 2007. A final release is, as of July 2008[update], planned for October 1, 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.

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 print as a 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 of uncertainty using comments or warnings. Even in an alpha stage, 2to3 appears to be fairly successful at performing the translation. 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
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.
* Moving reduce (but not map or filter) out of the built-in namespace and into functools (the rationale being that operations using reduce are expressed more clearly using an accumulation loop);
* Adding support for optional function annotations that can be used for informal type declarations or other purposes;
* Unifying the str/unicode types, representing text, and introducing a separate immutable bytes type; and a mostly corresponding mutable bytearray type, which both represent arrays of bytes;
* Removing backward-compatibility features, including old-style classes, integer-truncating division, string exceptions, and implicit relative imports.
Usage
Some of the largest projects that use Python are the Zope application server, YouTube, and the original BitTorrent client. Large organizations that make use of Python include Google, Yahoo!, CERN and NASA. ITA uses Python for some of its components.

Information Security
Python has also seen extensive use in the information security industry. Notably, in several of the tools offered by Immunity Security, in several of the tools offered by Core Security, in the Web application security scanner Wapiti, and in the fuzzer TAOF. Python is commonly used in exploit development.

Embedding
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 Houdini, Maya, Softimage XSI, TrueSpace, Poser, Modo, Nuke and Blender. It is also used in GIMP, Inkscape, Scribus and Paint Shop Pro. ESRI is now promoting Python as the best choice for writing scripts in ArcGIS. It is also used in Civilization IV as the control language for modding and event interaction. Eve Online, an MMORPG, is also built using Python.

Availability
For many operating systems, Python is a standard component; it ships with most Linux distributions, with NetBSD, and OpenBSD, and with Mac OS X. Red Hat Linux and Fedora both use the pythonic Anaconda installer. 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.

Syntax and semantics
Python was intended to be a highly readable language. It aims toward an uncluttered visual layout, frequently using English keywords 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.

-Intentation
Python uses whitespace indentation, rather than curly braces or keywords, to delimit statement blocks (a feature also known as the off-side rule). An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block.

-Statements and control flow
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 object, 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 code block 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 it never will. However, better support for coroutine-like functionality is provided in 2.5, by extending Python's generators.[51] 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.

-Methods
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).

-Typing
Python uses duck typing and has typed objects but untyped variable names. 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 nonsense operations (for example, adding a number to a string) rather than silently attempting to make sense of them.
Type Description Syntax Example
(i) str,unicode An immutable sequence of characters 'mgaeka', u'mgaeka'
(ii) list Mutable,can contain mixed types [4.0m, 'string' , True]
(iii) set, frozenset Unordered, contaions no duplicates set([4.0, 'string' ,True]), frozenset([4.0, 'string' , True])
(iv) dict Group of key and value pairs {'key1' : 1.0, 'key2' : false}
(v) int A fixed precision number 24, 242424
(vi) float A real number 24.242424
(vii)complex A complex number with real number and imaginary parts 2+4j
(viii)bool truth value True or False
Python also allows programmers to define their own types. This is done using classes, which are most often used for an object-oriented style of programming. New instances of classes are constructed by calling the class (eg, FooClass()), and the classes themselves are instances of the class type (itself an instance of itself), allowing metaprogramming and reflection.

Implementations
The mainstream Python implementation, also known as CPython, is written in C meeting the C89 standard. CPython compiles the Python program into intermediate byte code, which is then executed by the virtual machine. It is distributed with a large standard library written in a mixture of C and Python. CPython ships in versions for many 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.
Stackless Python is a significant fork of CPython that implements microthreads; it does not use the C memory stack and will be better suited for use on microcontrollers or other limited resource platforms. It can be expected to run on approximately the same platforms that CPython runs on.
Jython compiles the Python program into Java byte code, which can then be executed by every Java Virtual Machine implementation. This also enables the utilization of Java class library functions from the Python program. IronPython follows a similar approach in order to run Python programs on the .NET Common Language Runtime.
PyPy is an experimental self-hosting implementation of Python, written in Python, that can output several types of bytecode, object code and intermediate languages.
Several programs exist to package the Python interpreter with application programs (or scripts) as standalone UNIX, Linux, Windows or Mac OS X executables, including Freeze, a pure Python utility that ships with Python, or py2exe, PyInstaller, cx_Freeze and py2app, all of which are available separately. 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 the Series 60 mobile phones called PyS60. It includes many of the modules from the CPython 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. Besides reserved words and variable names, most data type operations can be coded in Chinese as well.

Interpretational semantics
Most Python implementations (including CPython, the primary implementation) can function as a command line interpreter, for which the user enters statements sequentially and receives the results immediately. In short, Python acts 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 usually only used outside of a command-line interaction (eg, when 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 can compile not only to bytecode, but can 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 and is faster than standard Python code. Psyco is compatible with all Python code, not only a subset

Standard library
Python has a large standard library, commonly cited as one of Python's greatest strengths, providing pre-written tools suited to many tasks. This is deliberate and has been described as a "batteries included" Python philosophy. 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, Boost.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) already supported. Modules for creating graphical user interfaces, connecting to relational databases, arithmetic with arbitrary precision decimals, and manipulating regular expressions are also included. Python also includes a unit testing framework for creating 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 the modules are not. They are specified by their code, internal documentation, and test suite (if supplied). However, because most of the standard library is cross-platform Python code, there are only a few modules must be altered or completely rewritten by alternative implementations.

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 oriented 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.
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.
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".
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. It is sometimes described as 'slow'. However, most problems are not speed critical, and as computer hardware continues to become exponentially faster, languages do have more hardware resources available. When speed is a problem, Python programmers tend to try to optimize bottlenecks by algorithm improvements or data structure changes, by using a JIT compiler such as Psyco, or by rewriting the time-critical functions in "closer to the metal" languages such as C.

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 and avoiding the "there's more than one way to do it" approach. 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 (based on 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.[65] For example, the metasyntactic variables often used in Python literature are spam and eggs, instead of the traditional foo and bar.

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

* Boo uses indentation, a similar syntax, and a similar object model. However, Boo uses static typing and is closely integrated with the .NET framework.
* Cobra is also similar to Python, using indentation for blocks. It offers optional static typing and generates code designed for .NET/Mono. Cobra directly supports design-by-contract contracts.
* ECMAScript borrowed iterators, generators and list comprehensions from Python.
* Groovy was motivated by the desire to bring the Python design philosophy to Java.
* Converge is syntactically similar to Python, but has an interesting approach to generators and backtracking as well as macros and compile-time metaprogramming.
Python's development practices have also been emulated by other languages. The practice of requiring a document describing the rationale for, and issues surrounding, a change to the language (ie, a PEP) is also used in Tcl because of Python's influence.




Python Software
Integrated development enviroments
* Boa Constructor, a cross-platform IDE for Python development
* Eric, an IDE for Python and Ruby
* Stani's Python Editor (SPE), a cross-platform IDE for Python development
* Webware for Python a suite of programming tools for constructing web-based applications in Python.
* Wing IDE, an IDE for Python

Applications
* ArcGIS, a prominent GIS platform, allows extensive modelling using Python
* Bazaar, a free distributed revision control system
* BitTorrent original client, along with several derivatives
* Blender, a popular open source 3D modeler with a Python scripting engine
* Chandler, a personal information manager including calendar, email, tasks and notes support that is currently under development
* Decibel Audio Player, an open source audio player
* Deluge, a bittorrent client for GNOME
* Exaile, an open source audio player
* Gajim, an instant messaging client for the XMPP protocol
* GNU Mailman, one of the more popular packages for running email mailing lists
* GRAMPS, an open source genealogy software
* Juice, a popular podcast downloader
* Listen, an open source media player
* Maya, professional 3D modeler allows Python scripting as an alternative to MEL as of version 8.5
* Mercurial a cross-platform, distributed source management tool
* MoinMoin, a popular wiki engine
* Morpheus, file-sharing client/server software operated by the company StreamCast
* MusicBrainz Picard, a cross-platform MusicBrainz tag editor
* Nicotine, a PyGTK SoulSeek client.
* Plone, a user-friendly and powerful open source Content Management System
* Portage, the heart of Gentoo Linux. An advanced package management system based on the BSD-style ports system
* Poser, a 3D rendering and animation software program, that uses for scripting a special dialect of Python, called PoserPython.
* PyMOL, a popular molecular viewer that embeds Python for scripting and integration
* Quake Army Knife, an environment for developing 3D maps for games based on the Quake engine
* Quod Libet, an open source audio player.
* Resolver One, a spreadsheet
* SAGE (sagemath) combines more than 20 main opensource math packages and provides easy to use web interface with the help of python
* SCons, a tool for building software
* Sipie, a command line player for online streaming of Sirius Satellite Radio stations
* Sonata, a MPD client.
* SPSS, Statistical analysis package. SPSS Programmability Extension allows users to extend the SPSS command syntax language with Python.
* Stoq, a open source ERP and CRM
* Trac, web-based bug/issue tracking database, wiki, and version control front-end
* ViewVC, a web-based interface for browsing CVS and SVN repositories
* Yum, a package management utility for RPM-compatible Linux operating systems.

Web frameworks
* CherryPy, an object-oriented web application server and framework
* Django, an MVC (model, view, controller) web framework
* Zope, an application server, commonly used to build content management systems

Develpment package
* matplotlib, an extension providing MATLAB-like plotting and mathematical functions
* NumPy, a language extension that adds support for large and fast, multi-dimensional arrays and matrices
* SciPy, a library of scientific and numerical routines
* SimPy, a discrete-event simulation package;
* BioPython, a Python molecular biology suite.
* Soya 3D, a high-level 3D game engine for Python
* Pygame, python bindings for Simple DirectMedia Layer
* Pyglet, a cross-platform windowing and multimedia library for Python
* Python Imaging Library, a module for working with images
* PyGTK, a popular cross-platform GUI library based on GTK+; furthermore, other GNOME libraries also have bindings for Python
* PyQt, another cross-platform GUI library based on Qt; as above, KDE libraries have bindings too
* wxPython, a port of wxWidgets and a cross-platform GUI library for Python
* PyObjC, a Python-Objective C bridge that allows one to write Mac OS X software in Python
* CherryPy, a Python-powered web framework
* Django, another Python-powered web framework
* Pylons, another Python-powered web framework
* Topsite Templating System, another Python-powered web framework
* TurboGears, a web framework combining CherryPy, SQLObject, and Kid
* Zope Object Database, a Python-specific object-oriented database
* Cheetah, a Python-powered template engine and code-generation tool
* mod_python, an Apache module allowing direct integration of Python scripts with the Apache web server
* Quixote a framework for developing Web applications in Python
* Twisted, a networking framework for Python
* IPython, a powerful development shell both written in and designed for Python

Embedded as a scripting language
Python is, or can be used as, the scripting language in these software products.
* Amarok
* Blender
* Epiphany
* EventScripts - plugin for Valve's Source engine
* gedit
* GIMP
* Inkscape
* AMESim
* Maya
* Modo
* Corel Paint Shop Pro
* Poser
* Rhythmbox
* Scribus
* Softimage|XSI
* SPSS statistical software
* Totem
* Vim
* VisIt

Commercial uses
* CCP hf uses Stackless Python in both its server and client side applications for its MMO Eve Online.[1]
* Google uses Python for many tasks including the backends of web apps such as Google Groups, Gmail, and Google Maps, as well as for some of its search-engine internals.
* NASA is using Python to implement a CAD/CAE/PDM repository and model management, integration, and transformation system which will be the core infrastructure for its next-generation collaborative engineering environment.
* Reddit was originally written in Common Lisp, but was rewritten in Python in 2005.[2]
* Youtube uses Python "to produce maintainable features in record times, with a minimum of developers".[3]
* Yahoogroups uses Python "to maintain its discussion groups"

Python implementations
* Python – The reference implementation, also known as CPython
* Jython – Python coded in Java
* IronPython – Python for .NET and Mono platforms
* Stackless Python - Python with coroutines
* Psyco - not an implementation, but JIT compiler for CPython
* PyPy – Python coded in Python
* 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
ေမာင္ဧက is offline   Reply With Quote
Old 12-09-2008, 03:17 PM
  post #5
ေမာင္ဧက
ကေလးေပါက္စ
 
အသင္း၀င္ေန႔စြဲ: Sep 2008
ေရးသားခ်က္မ်ား: 32
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 4
ပို႔စ္ 11 ခုအတြက္ 43 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
ေမာင္ဧက is on a distinguished road
ျပန္စာ - phython

ကဲ သူရဲ႕ အဓိက လိပ္စာကေတာ့

http://www.python.org

ေတာ္ေတာ္ကုိ အစုံအလင္ပါတယ္
code ေတြကုိ ေလ့လာခ်င္ရင္
http://code.activestate.com/recipes/langs/python/

Last edited by ေမာင္ဧက; 12-09-2008 at 03:28 PM..
ေမာင္ဧက is offline   Reply With Quote
Old 12-09-2008, 03:33 PM
  post #6
ေမာင္ဧက
ကေလးေပါက္စ
 
အသင္း၀င္ေန႔စြဲ: Sep 2008
ေရးသားခ်က္မ်ား: 32
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 4
ပို႔စ္ 11 ခုအတြက္ 43 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
ေမာင္ဧက is on a distinguished road
ျပန္စာ - phython

www.python.org ထဲကေနကူးထားတာပါ
What is python တဲ႔ မဆုိးဘူး ေကာင္းတယ္ ျခဳံၿပီးေလ့လာလုိ႔ရတယ္
1 General Information
1.1 What is Python?

Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

To find out more, start with the Beginner's Guide to Python.
1.2 Why was Python created in the first place?

Here's a very brief summary of what started it all, written by Guido van Rossum:

I had extensive experience with implementing an interpreted language in the ABC group at CWI, and from working with this group I had learned a lot about language design. This is the origin of many Python features, including the use of indentation for statement grouping and the inclusion of very-high-level data types (although the details are all different in Python).

I had a number of gripes about the ABC language, but also liked many of its features. It was impossible to extend the ABC language (or its implementation) to remedy my complaints -- in fact its lack of extensibility was one of its biggest problems. I had some experience with using Modula-2+ and talked with the designers of Modula-3 and read the Modula-3 report. Modula-3 is the origin of the syntax and semantics used for exceptions, and some other Python features.

I was working in the Amoeba distributed operating system group at CWI. We needed a better way to do system administration than by writing either C programs or Bourne shell scripts, since Amoeba had its own system call interface which wasn't easily accessible from the Bourne shell. My experience with error handling in Amoeba made me acutely aware of the importance of exceptions as a programming language feature.

It occurred to me that a scripting language with a syntax like ABC but with access to the Amoeba system calls would fill the need. I realized that it would be foolish to write an Amoeba-specific language, so I decided that I needed a language that was generally extensible.

During the 1989 Christmas holidays, I had a lot of time on my hand, so I decided to give it a try. During the next year, while still mostly working on it in my own time, Python was used in the Amoeba project with increasing success, and the feedback from colleagues made me add many early improvements.

In February 1991, after just over a year of development, I decided to post to USENET. The rest is in the Misc/HISTORY file.

1.3 What is Python good for?

Python is a high-level general-purpose programming language that can be applied to many different classes of problems.

The language comes with a large standard library that covers areas such as string processing (regular expressions, Unicode, calculating differences between files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing, logging, profiling, parsing Python code), and operating system interfaces (system calls, filesystems, TCP/IP sockets). Look at the table of contents for the Library Reference to get an idea of what's available. A wide variety of third-party extensions are also available. Consult the Python Package Index to find packages of interest to you.
1.4 How does the Python version numbering scheme work?

Python versions are numbered A.B.C or A.B. A is the major version number -- it is only incremented for really major changes in the language. B is the minor version number, incremented for less earth-shattering changes. C is the micro-level -- it is incremented for each bugfix release. See PEP 6 for more information about bugfix releases.

Not all releases are bugfix releases. In the run-up to a new major release, a series of development releases are made, denoted as alpha, beta, or release candidate. Alphas are early releases in which interfaces aren't yet finalized; it's not unexpected to see an interface change between two alpha releases. Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs.

Alpha, beta and release candidate versions have an additional suffix. The suffix for an alpha version is "aN" for some small number N, the suffix for a beta version is "bN" for some small number N, and the suffix for a release candidate version is "cN" for some small number N. In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0cN, and those precede 2.0.

You may also find version numbers with a "+" suffix, e.g. "2.2+". These are unreleased versions, built directly from the Subversion trunk. In practice, after a final minor release is made, the Subversion trunk is incremented to the next minor version, which becomes the "a0" version, e.g. "2.4a0".

See also the documentation for sys.version, sys.hexversion, and sys.version_info.
1.5 Are there copyright restrictions on the use of Python?

Not really. You can do anything you want with the source, as long as you leave the copyrights in and display those copyrights in any documentation about Python that you produce. If you honor the copyright rules, it's OK to use Python for commercial use, to sell copies of Python in source or binary form (modified or unmodified), or to sell products that incorporate Python in some form. We would still like to know about all commercial use of Python, of course.

See the PSF license page to find further explanations and a link to the full text of the license.
1.6 How do I obtain a copy of the Python source?

The latest Python source distribution is always available from python.org, at http://www.python.org/download/. The latest development sources can be obtained via anonymous Subversion from SourceForge, at http://svn.python.org/projects/python/trunk

The source distribution is a gzipped tar file containing the complete C source, LaTeX documentation, Python library modules, example programs, and several useful pieces of freely distributable software. This will compile and run out of the box on most UNIX platforms.

Consult the Developer FAQ for more information on getting the source code and compiling it.
1.7 How do I get documentation on Python?

All documentation is available on-line, starting at http://www.python.org/doc/.

The standard documentation for the current stable version of Python is also available at http://docs.python.org/. PDF and downloadable HTML versions are also available.

The documentation is written using the Sphinx documentation tool. The Sphinx source for the documentation is part of the Python source distribution.
1.8 I've never programmed before. Is there a Python tutorial?

There are numerous tutorials and books available. Consult the Beginner's Guide to find information for beginning Python programmers, including lists of tutorials.
1.9 Are there other FTP sites that mirror the Python distribution?

Mirroring has been discontinued as of March 15, 2007. Please download here.
1.10 Is there a newsgroup or mailing list devoted to Python?

There is a newsgroup, comp.lang.python, and a mailing list, python-list. The newsgroup and mailing list are gatewayed into each other -- if you can read news it's unnecessary to subscribe to the mailing list. comp.lang.python is high-traffic, receiving hundreds of postings every day, and Usenet readers are often more able to cope with this volume.

Announcements of new software releases and events can be found in comp.lang.python.announce, a low-traffic moderated list that receives about five postings per day. It's available as the python-announce mailing list.

More info about other mailing lists and newsgroups can be found at http://www.python.org/community/lists/.
1.11 How do I get a beta test version of Python?

Alpha and beta releases are available from http://www.python.org/download/. All releases are announced on the comp.lang.python and comp.lang.python.announce newsgroups and on the Python home page, at http://www.python.org/; an RSS feed of news is available.

You can also access the development version of Python through Subversion. See http://www.python.org/dev/devfaq.html#subversion-svn for details.
1.12 How do I submit bug reports and patches for Python?

To report a bug or submit a patch, please use the Roundup installation at http://bugs.python.org/.

You must have a Roundup account to report bugs; this makes it possible for us to contact you if we have follow-up questions. It will also enable Roundup to send you updates as we act on your bug. If you had previously used SourceForge to report bugs to Python, you can obtain your Roundup password through Roundup's password reset procedure.

For more information on how Python is developed, consult the Python Developer's Guide.
1.13 Are there any published articles about Python that I can reference?

It's probably best to cite your favorite book about Python.

The very first article about Python is this very old article that's now quite outdated.

Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4 (December 1991), Amsterdam, pp 283-303.

1.14 Are there any books on Python?

Yes, there are many, and more are being published. See the python.org wiki at http://wiki.python.org/moin/PythonBooks for a list.

You can also search online bookstores for "Python" and filter out the Monty Python references; or perhaps search for "Python" and "language".
1.15 Where in the world is www.python.org located?

It's currently in Amsterdam, graciously hosted by XS4ALL. Thanks to Thomas Wouters for his work in arranging python.org's hosting.
1.16 Why is it called Python?

At the time when he began implementing Python, Guido van Rossum was also reading the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from the seventies, in the unlikely case you didn't know). It occurred to him that he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.
1.17 Do I have to like "Monty Python's Flying Circus"?

No, but it helps. :)
2 Python in the real world
2.1 How stable is Python?

Very stable. New, stable releases have been coming out roughly every 6 to 18 months since 1991, and this seems likely to continue. Currently there are usually around 18 months between major releases.

With the introduction of retrospective "bugfix" releases the stability of existing releases is being improved. Bugfix releases, indicated by a third component of the version number (e.g. 2.1.3, 2.2.2), are managed for stability; only fixes for known problems are included in a bugfix release, and it's guaranteed that interfaces will remain the same throughout a series of bugfix releases.

The 2.5.2 release is the most stable version at this point in time.
2.2 How many people are using Python?

Probably tens of thousands of users, though it's difficult to obtain an exact count. Python is available for free download, so there are no sales figures, and it's available from many different sites and packaged with many Linux distributions, so download statistics don't tell the whole story either. The comp.lang.python newsgroup is very active, but not all Python users post to the group or even read it. Overall there is no accurate estimate of the number of subscribers or Python users.
2.3 Have any significant projects been done in Python?

See http://python.org/about/success for a list of projects that use Python. Consulting the proceedings for past Python conferences will reveal contributions from many different companies and organizations.

High-profile Python projects include the Mailman mailing list manager and the Zope application server. Several Linux distributions, most notably Red Hat, have written part or all of their installer and system administration software in Python. Companies that use Python internally include Google, Yahoo, and Industrial Light & Magic.
2.4 What new developments are expected for Python in the future?

See http://www.python.org/dev/peps/ for the Python Enhancement Proposals (PEPs). PEPs are design documents describing a suggested new feature for Python, providing a concise technical specification and a rationale. PEP 1 explains the PEP process and PEP format; read it first if you want to submit a PEP.

New developments are discussed on the python-dev mailing list.
2.5 Is it reasonable to propose incompatible changes to Python?

In general, no. There are already millions of lines of Python code around the world, so any change in the language that invalidates more than a very small fraction of existing programs has to be frowned upon. Even if you can provide a conversion program, there's still the problem of updating all documentation; many books have been written about Python, and we don't want to invalidate them all at a single stroke.

Providing a gradual upgrade path is necessary if a feature has to be changed. PEP 5 describes the procedure followed for introducing backward-incompatible changes while minimizing disruption for users.
2.6 What is the Python Software Foundation?

The Python Software Foundation is an independent non-profit organization that holds the copyright on Python versions 2.1 and newer. The PSF's mission is to advance open source technology related to the Python programming language and to publicize the use of Python. The PSF's home page is at http://www.python.org/psf/.

Donations to the PSF are tax-exempt in the US. If you use Python and find it helpful, please contribute via the PSF donation page.
2.7 Is Python Y2K (Year 2000) Compliant?

As of August, 2003 no major problems have been reported and Y2K compliance seems to be a non-issue.

Python does very few date calculations and for those it does perform relies on the C library functions. Python generally represents times either as seconds since 1970 or as a (year, month, day, ...) tuple where the year is expressed with four digits, which makes Y2K bugs unlikely. So as long as your C library is okay, Python should be okay. Of course, it's possible that a particular application written in Python makes assumptions about 2-digit years.

Because Python is available free of charge, there are no absolute guarantees. If there are unforeseen problems, liability is the user's problem rather than the developers', and there is nobody you can sue for damages. The Python copyright notice contains the following disclaimer:

4. PSF is making Python 2.3 available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

The good news is that if you encounter a problem, you have full source available to track it down and fix it. This is one advantage of an open source programming environment.
2.8 Is Python a good language for beginning programmers?

Yes.

It is still common to start students with a procedural (subset of a) statically typed language such as Pascal, C, or a subset of C++ or Java. Students may be better served by learning Python as their first language. Python has a very simple and consistent syntax and a large standard library and, most importantly, using Python in a beginning programming course lets students concentrate on important programming skills such as problem decomposition and data type design. With Python, students can be quickly introduced to basic concepts such as loops and procedures. They can probably even work with user-defined objects in their very first course.

For a student who has never programmed before, using a statically typed language seems unnatural. It presents additional complexity that the student must master and slows the pace of the course. The students are trying to learn to think like a computer, decompose problems, design consistent interfaces, and encapsulate data. While learning to use a statically typed language is important in the long term, it is not necessarily the best topic to address in the students' first programming course.

Many other aspects of Python make it a good first language. Like Java, Python has a large standard library so that students can be assigned programming projects very early in the course that do something. Assignments aren't restricted to the standard four-function calculator and check balancing programs. By using the standard library, students can gain the satisfaction of working on realistic applications as they learn the fundamentals of programming. Using the standard library also teaches students about code reuse. Third-party modules such as PyGame are also helpful in extending the students' reach.

Python's interactive interpreter enables students to test language features while they're programming. They can keep a window with the interpreter running while they enter their program's source in another window. If they can't remember the methods for a list, they can do something like this:

>>> L = []
>>> dir(L)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>> help(L.append)
Help on built-in function append:

append(...)
L.append(object) -- append object to end
>>> L.append(1)
>>> L
[1]

With the interpreter, documentation is never far from the student as he's programming.

There are also good IDEs for Python. IDLE is a cross-platform IDE for Python that is written in Python using Tkinter. PythonWin is a Windows-specific IDE. Emacs users will be happy to know that there is a very good Python mode for Emacs. All of these programming environments provide syntax highlighting, auto-indenting, and access to the interactive interpreter while coding. Consult http://www.python.org/editors/ for a full list of Python editing environments.

If you want to discuss Python's use in education, then you may be interested in joining the edu-sig mailing list.
3 Upgrading Python
3.1 What is this bsddb185 module my application keeps complaining about?

Starting with Python2.3, the distribution includes the PyBSDDB package <http://pybsddb.sf.net/> as a replacement for the old bsddb module. It includes functions which provide backward compatibility at the API level, but requires a newer version of the underlying Berkeley DB library. Files created with the older bsddb module can't be opened directly using the new module.

Using your old version of Python and a pair of scripts which are part of Python 2.3 (db2pickle.py and pickle2db.py, in the Tools/scripts directory) you can convert your old database files to the new format. Using your old Python version, run the db2pickle.py script to convert it to a pickle, e.g.:

python2.2 <pathto>/db2pickley.py database.db database.pck

Rename your database file:

mv database.db olddatabase.db

Now convert the pickle file to a new format database:

python2.3 <pathto>/pickle2db.py database.db database.pck

The precise commands you use will vary depending on the particulars of your installation. For full details about operation of these two scripts check the doc string at the start of each one.
4 Python's Design
4.1 Why does Python use indentation for grouping of statements?

Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the average Python program. Most people learn to love this feature after awhile.

Since there are no begin/end brackets there cannot be a disagreement between grouping perceived by the parser and the human reader. Occasionally C programmers will encounter a fragment of code like this:

if (x <= y)
x++;
y--;
z++;

Only the x++ statement is executed if the condition is true, but the indentation leads you to believe otherwise. Even experienced C programmers will sometimes stare at it a long time wondering why y is being decremented even for x > y.

Because there are no begin/end brackets, Python is much less prone to coding-style conflicts. In C there are many different ways to place the braces. If you're used to reading and writing code that uses one style, you will feel at least slightly uneasy when reading (or being required to write) another style.

Many coding styles place begin/end brackets on a line by themself. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program. Ideally, a function should fit on one screen (say, 20-30 lines). 20 lines of Python can do a lot more work than 20 lines of C. This is not solely due to the lack of begin/end brackets -- the lack of declarations and the high-level data types are also responsible -- but the indentation-based syntax certainly helps.
4.2 Why am I getting strange results with simple arithmetic operations?

See the next question.
4.3 Why are floating point calculations so inaccurate?

People are often very surprised by results like this:

>>> 1.2-1.0
0.199999999999999996

and think it is a bug in Python. It's not. This has nothing to do with Python, but with how the underlying C platform handles floating point numbers, and ultimately with the inaccuracies introduced when writing down numbers as a string of a fixed number of digits.

The internal representation of floating point numbers uses a fixed number of binary digits to represent a decimal number. Some decimal numbers can't be represented exactly in binary, resulting in small roundoff errors.

In decimal math, there are many numbers that can't be represented with a fixed number of decimal digits, e.g. 1/3 = 0.3333333333.......

In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. .2 equals 2/10 equals 1/5, resulting in the binary fractional number 0.001100110011001...

Floating point numbers only have 32 or 64 bits of precision, so the digits are cut off at some point, and the resulting number is 0.199999999999999996 in decimal, not 0.2.

A floating point number's repr() function prints as many digits are necessary to make eval(repr(f)) == f true for any float f. The str() function prints fewer digits and this often results in the more sensible number that was probably intended:

>>> 0.2
0.20000000000000001
>>> print 0.2
0.2

One of the consequences of this is that it is error-prone to compare the result of some computation to a float with ==. Tiny inaccuracies may mean that == fails. Instead, you have to check that the difference between the two numbers is less than a certain threshold:

epsilon = 0.0000000000001 # Tiny allowed error
expected_result = 0.4

if expected_result-epsilon <= computation() <= expected_result+epsilon:
...

Please see the chapter on floating point arithmetic in the Python tutorial for more information.
4.4 Why are Python strings immutable?

There are several advantages.

One is performance: knowing that a string is immutable means we can allocate space for it at creation time, and the storage requirements are fixed and unchanging. This is also one of the reasons for the distinction between tuples and lists.

Another advantage is that strings in Python are considered as "elemental" as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string "eight" to anything else.
4.5 Why must 'self' be used explicitly in method definitions and calls?

The idea was borrowed from Modula-3. It turns out to be very useful, for a variety of reasons.

First, it's more obvious that you are using a method or instance attribute instead of a local variable. Reading self.x or self.meth() makes it absolutely clear that an instance variable or method is used even if you don't know the class definition by heart. In C++, you can sort of tell by the lack of a local variable declaration (assuming globals are rare or easily recognizable) -- but in Python, there are no local variable declarations, so you'd have to look up the class definition to be sure. Some C++ and Java coding standards call for instance attributes to have an m_ prefix, so this explicitness is still useful in those languages, too.

Second, it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class. In C++, if you want to use a method from a base class which is overridden in a derived class, you have to use the :: operator -- in Python you can write baseclass.methodname(self, <argument list>). This is particularly useful for __init__() methods, and in general in cases where a derived class method wants to extend the base class method of the same name and thus has to call the base class method somehow.

Finally, for instance variables it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value assigned in a function body (and that aren't explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons). C++ does this through declarations, but Python doesn't have declarations and it would be a pity having to introduce them just for this purpose. Using the explicit "self.var" solves this nicely. Similarly, for using instance variables, having to write "self.var" means that references to unqualified names inside a method don't have to search the instance's directories. To put it another way, local variables and instance variables live in two different namespaces, and you need to tell Python which namespace to use.
4.6 Why can't I use an assignment in an expression?

Many people used to C or Perl complain that they want to use this C idiom:

while (line = readline(f)) {
...do something with line...
}

where in Python you're forced to write this:

while True:
line = f.readline()
if not line:
break
...do something with line...

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}

The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.

Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.

An interesting phenomenon is that most experienced Python programmers recognize the "while True" idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language.

There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution:

line = f.readline()
while line:
...do something with line...
line = f.readline()

The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into sys.stdin.readline()) you have to remember to change two places in your program -- the second occurrence is hidden at the bottom of the loop.

The best approach is to use iterators, making it possible to loop through objects using the for statement. For example, in the current version of Python file objects support the iterator protocol, so you can now write simply:

for line in f:
... do something with line...

4.7 Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

The major reason is history. Functions were used for those operations that were generic for a group of types and which were intended to work even for objects that didn't have methods at all (e.g. tuples). It is also convenient to have a function that can readily be applied to an amorphous collection of objects when you use the functional features of Python (map(), apply() et al).

In fact, implementing len(), max(), min() as a built-in function is actually less code than implementing them as methods for each type. One can quibble about individual cases but it's a part of Python, and it's too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.

Note that for string operations Python has moved from external functions (the string module) to methods. However, len() is still a function.
4.8 Why is join() a string method instead of a list or tuple method?

Strings became much more like other standard types starting in Python 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. Most of these new methods have been widely accepted, but the one which appears to make some programmers feel uncomfortable is:

", ".join(['1', '2', '4', '8', '16'])

which gives the result:

"1, 2, 4, 8, 16"

There are two common arguments against this usage.

The first runs along the lines of: "It looks really ugly using a method of a string literal (string constant)", to which the answer is that it might, but a string literal is just a fixed value. If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literals.

The second objection is typically cast as: "I am really telling a sequence to join its members together with a string constant". Sadly, you aren't. For some reason there seems to be much less difficulty with having split() as a string method, since in that case it is easy to see that

"1, 2, 4, 8, 16".split(", ")

is an instruction to a string literal to return the substrings delimited by the given separator (or, by default, arbitrary runs of white space). In this case a Unicode string returns a list of Unicode strings, an ASCII string returns a list of ASCII strings, and everyone is happy.

join() is a string method because in using it you are telling the separator string to iterate over a sequence of strings and insert itself between adjacent elements. This method can be used with any argument which obeys the rules for sequence objects, including any new classes you might define yourself.

Because this is a string method it can work for Unicode strings as well as plain ASCII strings. If join() were a method of the sequence types then the sequence types would have to decide which type of string to return depending on the type of the separator.

If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write

string.join(['1', '2', '4', '8', '16'], ", ")

4.9 How fast are exceptions?

A try/except block is extremely efficient. Actually executing an exception is expensive. In versions of Python prior to 2.0 it was common to use this idiom:

try:
value = dict[key]
except KeyError:
dict[key] = getvalue(key)
value = dict[key]

This only made sense when you expected the dict to have the key almost all the time. If that wasn't the case, you coded it like this:

if dict.has_key(key):
value = dict[key]
else:
dict[key] = getvalue(key)
value = dict[key]

(In Python 2.0 and higher, you can code this as value = dict.setdefault(key, getvalue(key)).)
4.10 Why isn't there a switch or case statement in Python?

You can do this easily enough with a sequence of if... elif... elif... else. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 for complete details and the current status.

For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:

def function_1 (...):
...

functions = {'a': function_1,
'b': function_2,
'c': self.method_1, ...}

func = functions[value]
func()

For calling methods on objects, you can simplify yet further by using the getattr() built-in to retrieve methods with a particular name:

def visit_a (self, ...):
...
...

def dispatch (self, value):
method_name = 'visit_' + str(value)
method = getattr(self, method_name)
method()

It's suggested that you use a prefix for the method names, such as visit_ in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.
4.11 Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for each Python stack frame. Also, extensions can call back into Python at almost random moments. Therefore, a complete threads implementation requires thread support for C.

Answer 2: Fortunately, there is Stackless Python, which has a completely redesigned interpreter loop that avoids the C stack. It's still experimental but looks very promising. Although it is binary compatible with standard Python, it's still unclear whether Stackless will make it into the core -- maybe it's just too revolutionary.
4.12 Why can't lambda forms contain statements?

Python lambda forms cannot contain statements because Python's syntactic framework can't handle statements nested inside expressions. However, in Python, this is not a serious problem. Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you're too lazy to define a function.

Functions are already first class objects in Python, and can be declared in a local scope. Therefore the only advantage of using a lambda form instead of a locally-defined function is that you don't need to invent a name for the function -- but that's just a local variable to which the function object (which is exactly the same type of object that a lambda form yields) is assigned!
4.13 Can Python be compiled to machine code, C or some other language?

Not easily. Python's high level data types, dynamic typing of objects and run-time invocation of the interpreter (using eval() or exec) together mean that a "compiled" Python program would probably consist mostly of calls into the Python run-time system, even for seemingly simple operations like x+1.

Several projects described in the Python newsgroup or at past Python conferences have shown that this approach is feasible, although the speedups reached so far are only modest (e.g. 2x). Jython uses the same strategy for compiling to Java bytecode. (Jim Hugunin has demonstrated that in combination with whole-program analysis, speedups of 1000x are feasible for small demo programs. See the proceedings from the 1997 Python conference for more information.)

Internally, Python source code is always translated into a bytecode representation, and this bytecode is then executed by the Python virtual machine. In order to avoid the overhead of repeatedly parsing and translating modules that rarely change, this byte code is written into a file whose name ends in ".pyc" whenever a module is parsed. When the corresponding .py file is changed, it is parsed and translated again and the .pyc file is rewritten.

There is no performance difference once the .pyc file has been loaded, as the bytecode read from the .pyc file is exactly the same as the bytecode created by direct translation. The only difference is that loading code from a .pyc file is faster than parsing and translating a .py file, so the presence of precompiled .pyc files improves the start-up time of Python scripts. If desired, the Lib/compileall.py module can be used to create valid .pyc files for a given set of modules.

Note that the main script executed by Python, even if its filename ends in .py, is not compiled to a .pyc file. It is compiled to bytecode, but the bytecode is not saved to a file. Usually main scripts are quite short, so this doesn't cost much speed.

There are also several programs which make it easier to intermingle Python and C code in various ways to increase performance. See, for example, Psyco, Pyrex, PyInline, Py2Cmod, and Weave.
4.14 How does Python manage memory?

The details of Python memory management depend on the implementation. The standard C implementation of Python uses reference counting to detect inaccessible objects, and another mechanism to collect reference cycles, periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. The gc module provides functions to perform a garbage collection, obtain debugging statistics, and tune the collector's parameters.

Jython relies on the Java runtime so the JVM's garbage collector is used. This difference can cause some subtle porting problems if your Python code depends on the behavior of the reference counting implementation.

Sometimes objects get stuck in tracebacks temporarily and hence are not deallocated when you might expect. Clear the tracebacks with:

import sys
sys.exc_clear()
sys.exc_traceback = sys.last_traceback = None

Tracebacks are used for reporting errors, implementing debuggers and related things. They contain a portion of the program state extracted during the handling of an exception (usually the most recent exception).

In the absence of circularities and tracebacks, Python programs need not explicitly manage memory.

Why doesn't Python use a more traditional garbage collection scheme? For one thing, this is not a C standard feature and hence it's not portable. (Yes, we know about the Boehm GC library. It has bits of assembler code for most common platforms, not for all of them, and although it is mostly transparent, it isn't completely transparent; patches are required to get Python to work with it.)

Traditional GC also becomes a problem when Python is embedded into other applications. While in a standalone Python it's fine to replace the standard malloc() and free() with versions provided by the GC library, an application embedding Python may want to have its own substitute for malloc() and free(), and may not want Python's. Right now, Python works with anything that implements malloc() and free() properly.

In Jython, the following code (which is fine in CPython) will probably run out of file descriptors long before it runs out of memory:

for file in <very long list of files>:
f = open(file)
c = f.read(1)

Using the current reference counting and destructor scheme, each new assignment to f closes the previous file. Using GC, this is not guaranteed. If you want to write code that will work with any Python implementation, you should explicitly close the file; this will work regardless of GC:

for file in <very long list of files>:
f = open(file)
c = f.read(1)
f.close()

4.15 Why isn't all memory freed when Python exits?

Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.

If you want to force Python to delete certain things on deallocation use the sys.exitfunc() hook to run a function that will force those deletions.
4.16 Why are there separate tuple and list data types?

Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.

Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. For example, os.listdir('.') returns a list of strings representing the files in the current directory. Functions which operate on this output would generally not break if you added another file or two to the directory.

Tuples are immutable, meaning that once a tuple has been created, you can't replace any of its elements with a new value. Lists are mutable, meaning that you can always change a list's elements. Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.
4.17 How are lists implemented?

Python's lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array's length in a list head structure.

This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.

When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don't require an actual resize.
4.18 How are dictionaries implemented?

Python's dictionaries are implemented as resizable hash tables. Compared to B-trees, this gives better performance for lookup (the most common operation by far) under most circumstances, and the implementation is simpler.

Dictionaries work by computing a hash code for each key stored in the dictionary using the hash() built-in function. The hash code varies widely depending on the key; for example, "Python" hashes to -539294296 while "python", a string that differs by a single bit, hashes to 1142331976. The hash code is then used to calculate a location in an internal array where the value will be stored. Assuming that you're storing keys that all have different hash values, this means that dictionaries take constant time -- O(1), in computer science notation -- to retrieve a key. It also means that no sorted order of the keys is maintained, and traversing the array as the .keys() and .items() do will output the dictionary's content in some arbitrary jumbled order.
4.19 Why must dictionary keys be immutable?

The hash table implementation of dictionaries uses a hash value calculated from the key value to find the key. If the key were a mutable object, its value could change, and thus its hash could also change. But since whoever changes the key object can't tell that it was being used as a dictionary key, it can't move the entry around in the dictionary. Then, when you try to look up the same object in the dictionary it won't be found because its hash value is different. If you tried to look up the old value it wouldn't be found either, because the value of the object found in that hash bin would be different.

If you want a dictionary indexed with a list, simply convert the list to a tuple first; the function tuple(L) creates a tuple with the same entries as the list L. Tuples are immutable and can therefore be used as dictionary keys.

Some unacceptable solutions that have been proposed:

*

Hash lists by their address (object ID). This doesn't work because if you construct a new list with the same value it won't be found; e.g.:

d = {[1,2]: '12'}
print d[[1,2]]

would raise a KeyError exception because the id of the [1,2] used in the second line differs from that in the first line. In other words, dictionary keys should be compared using ==, not using 'is'.
*

Make a copy when using a list as a key. This doesn't work because the list, being a mutable object, could contain a reference to itself, and then the copying code would run into an infinite loop.
*

Allow lists as keys but tell the user not to modify them. This would allow a class of hard-to-track bugs in programs when you forgot or modified a list by accident. It also invalidates an important invariant of dictionaries: every value in d.keys() is usable as a key of the dictionary.
*

Mark lists as read-only once they are used as a dictionary key. The problem is that it's not just the top-level object that could change its value; you could use a tuple containing a list as a key. Entering anything as a key into a dictionary would require marking all objects reachable from there as read-only -- and again, self-referential objects could cause an infinite loop.

There is a trick to get around this if you need to, but use it at your own risk: You can wrap a mutable structure inside a class instance which has both a __cmp__ and a __hash__ method. You must then make sure that the hash value for all such wrapper objects that reside in a dictionary (or other hash based structure), remain fixed while the object is in the dictionary (or other structure).:

class ListWrapper:
def __init__(self, the_list):
self.the_list = the_list
def __cmp__(self, other):
return self.the_list == other.the_list
def __hash__(self):
l = self.the_list
result = 98767 - len(l)*555
for i in range(len(l)):
try:
result = result + (hash(l[i]) % 9999999) * 1001 + i
except:
result = (result % 7777777) + i * 333
return result

Note that the hash computation is complicated by the possibility that some members of the list may be unhashable and also by the possibility of arithmetic overflow.

Furthermore it must always be the case that if o1 == o2 (ie o1.__cmp__(o2)==0) then hash(o1)==hash(o2) (ie, o1.__hash__() == o2.__hash__()), regardless of whether the object is in a dictionary or not. If you fail to meet these restrictions dictionaries and other hash based structures will misbehave.

In the case of ListWrapper, whenever the wrapper object is in a dictionary the wrapped list must not change to avoid anomalies. Don't do this unless you are prepared to think hard about the requirements and the consequences of not meeting them correctly. Consider yourself warned.
4.20 Why doesn't list.sort() return the sorted list?

In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won't be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around.

In Python 2.4 a new builtin - sorted() - has been added. This function creates a new list from a provided iterable, sorts it and returns it. For example, here's how to iterate over the keys of a dictionary in sorted order:

for key in sorted(dict.iterkeys()):
...do whatever with dict[key]...

4.21 How do you specify and enforce an interface spec in Python?

An interface specification for a module as provided by languages such as C++ and Java describes the prototypes for the methods and functions of the module. Many feel that compile-time enforcement of interface specifications helps in the construction of large programs.

Python 2.6 adds an abc module that lets you define Abstract Base Classes (ABCs). You can then use isinstance() and issubclass to check whether an instance or a class implements a particular ABC. The collections modules defines a set of useful ABCs such as Iterable, Container, and MutableMapping.

For Python, many of the advantages of interface specifications can be obtained by an appropriate test discipline for components. There is also a tool, PyChecker, which can be used to find problems due to subclassing.

A good test suite for a module can both provide a regression test and serve as a module interface specification and a set of examples. Many Python modules can be run as a script to provide a simple "self test." Even modules which use complex external interfaces can often be tested in isolation using trivial "stub" emulations of the external interface. The doctest and unittest modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module.

An appropriate testing discipline can help build large complex applications in Python as well as having interface specifications would. In fact, it can be better because an interface specification cannot test certain properties of a program. For example, the append() method is expected to add new elements to the end of some internal list; an interface specification cannot test that your append() implementation will actually do this correctly, but it's trivial to check this property in a test suite.

Writing test suites is very helpful, and you might want to design your code with an eye to making it easily tested. One increasingly popular technique, test-directed development, calls for writing parts of the test suite first, before you write any of the actual code. Of course Python allows you to be sloppy and not write test cases at all.
4.22 Why are default values shared between objects?

This type of bug commonly bites neophyte programmers. Consider this function:

def foo(D={}): # Danger: shared reference to one dict for all calls
... compute something ...
D[key] = value
return D

The first time you call this function, D contains a single item. The second time, D contains two items because when foo() begins executing, D starts out with an item already in it.

It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.

By definition, immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.

Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use None as the default value and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is. For example, don't write:

def foo(dict={}):
...

but:

def foo(dict=None):
if dict is None:
dict = {} # create a new dict for local namespace

This feature can be useful. When you have a function that's time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called "memoizing", and can be implemented like this:

# Callers will never provide a third parameter for this function.
def expensive (arg1, arg2, _cache={}):
if _cache.has_key((arg1, arg2)):
return _cache[(arg1, arg2)]

# Calculate the value
result = ... expensive computation ...
_cache[(arg1, arg2)] = result # Store result in the cache
return result

You could use a global variable containing a dictionary instead of the default value; it's a matter of taste.
4.23 Why is there no goto?

You can use exceptions to provide a "structured goto" that even works across function calls. Many feel that exceptions can conveniently emulate all reasonable uses of the "go" or "goto" constructs of C, Fortran, and other languages. For example:

class label: pass # declare a label

try:
...
if (condition): raise label() # goto label
...
except label: # where to goto
pass
...

This doesn't allow you to jump into the middle of a loop, but that's usually considered an abuse of goto anyway. Use sparingly.
4.24 Why can't raw strings (r-strings) end with a backslash?

More precisely, they can't end with an odd number of backslashes: the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string.

Raw strings were designed to ease creating input for processors (chiefly regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose.

If you're trying to build Windows pathnames, note that all Windows system calls accept forward slashes too:

f = open("/mydir/file.txt") # works fine!

If you're trying to build a pathname for a DOS command, try e.g. one of

dir = r"\this\is\my\dos\dir" "\\"
dir = r"\this\is\my\dos\dir\ "[:-1]
dir = "\\this\\is\\my\\dos\\dir\\"

4.25 Why doesn't Python have a "with" statement for attribute assignments?

Python has a 'with' statement that wraps the execution of a block, calling code on the entrance and exit from the block. Some language have a construct that looks like this:

with obj:
a = 1 # equivalent to obj.a = 1
total = total + 1 # obj.total = obj.total + 1

In Python, such a construct would be ambiguous.

Other languages, such as Object Pascal, Delphi, and C++, use static types, so it's possible to know, in an unambiguous way, what member is being assigned to. This is the main point of static typing -- the compiler always knows the scope of every variable at compile time.

Python uses dynamic types. It is impossible to know in advance which attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This makes it impossible to know, from a simple reading, what attribute is being referenced: a local one, a global one, or a member attribute?

For instance, take the following incomplete snippet:

def foo(a):
with a:
print x

The snippet assumes that "a" must have a member attribute called "x". However, there is nothing in Python that tells the interpreter this. What should happen if "a" is, let us say, an integer? If there is a global variable named "x", will it be used inside the with block? As you see, the dynamic nature of Python makes such choices much harder.

The primary benefit of "with" and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of:

function(args).dict[index][index].a = 21
function(args).dict[index][index].b = 42
function(args).dict[index][index].c = 63

write this:

ref = function(args).dict[index][index]
ref.a = 21
ref.b = 42
ref.c = 63

This also has the side-effect of increasing execution speed because name bindings are resolved at run-time in Python, and the second version only needs to perform the resolution once. If the referenced object does not have a, b and c attributes, of course, the end result is still a run-time exception.
4.26 Why are colons required for the if/while/def/class statements?

The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:

if a==b
print a

versus

if a==b:
print a

Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in the second line of this FAQ answer; it's a standard usage in English.

Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.
4.27 Why does Python allow commas at the end of lists and tuples?

Python lets you add a trailing comma at the end of lists, tuples, and dictionaries:

[1, 2, 3,]
('a', 'b', 'c',)
d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}

There are several reasons to allow this.

When you have a literal value for a list, tuple, or dictionary spread across multiple lines, it's easier to add more elements because you don't have to remember to add a comma to the previous line. The lines can also be sorted in your editor without creating a syntax error.

Accidentally omitting the comma can lead to errors that are hard to diagnose. For example:

x = [
"fee",
"fie"
"foo",
"fum"
]

This list looks like it has four elements, but it actually contains three: "fee", "fiefoo" and "fum". Always adding the comma avoids this source of error.

Allowing the trailing comma may also make programmatic code generation easier.


ရွင္းရွင္းလင္းလင္းေလးၾကည့္ခ်င္တယ္ဆုိရင္ေတာ့
http://www.python.org/doc/faq/genera...ython-good-for
ေမာင္ဧက is offline   Reply With Quote
Old 12-09-2008, 11:47 PM
  post #7
ေမာင္ဧက
ကေလးေပါက္စ
 
အသင္း၀င္ေန႔စြဲ: Sep 2008
ေရးသားခ်က္မ်ား: 32
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 4
ပို႔စ္ 11 ခုအတြက္ 43 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
ေမာင္ဧက is on a distinguished road
ျပန္စာ - phython

www.python.org ထဲကေန ယူထားတာပါ
Python library reference တဲ့ တကယ္ကုိစုံတယ္ ေတာ္ေတာ္ကုိေလ့လာရအုံးမွာ ကြၽမ္းက်င္ဖုိ႔ကုိေလ

Python Library Refrence

Introduction
The ``Python library'' contains several different kinds of components.

It contains data types that would normally be considered part of the ``core'' of a language, such as numbers and lists. For these types, the Python language core defines the form of literals and places some constraints on their semantics, but does not fully define the semantics. (On the other hand, the language core does define syntactic properties like the spelling and priorities of operators.)

The library also contains built-in functions and exceptions -- objects that can be used by all Python code without the need of an import statement. Some of these are defined by the core language, but many are not essential for the core semantics and are only described here.

The bulk of the library, however, consists of a collection of modules. There are many ways to dissect this collection. Some modules are written in C and built in to the Python interpreter; others are written in Python and imported in source form. Some modules provide interfaces that are highly specific to Python, like printing a stack trace; some provide interfaces that are specific to particular operating systems, such as access to specific hardware; others provide interfaces that are specific to a particular application domain, like the World Wide Web. Some modules are available in all versions and ports of Python; others are only available when the underlying system supports or requires them; yet others are available only when a particular configuration option was chosen at the time when Python was compiled and installed.

This manual is organized ``from the inside out:'' it first describes the built-in data types, then the built-in functions and exceptions, and finally the modules, grouped in chapters of related modules. The ordering of the chapters as well as the ordering of the modules within each chapter is roughly from most relevant to least important.

This means that if you start reading this manual from the start, and skip to the next chapter when you get bored, you will get a reasonable overview of the available modules and application areas that are supported by the Python library. Of course, you don't have to read it like a novel -- you can also browse the table of contents (in front of the manual), or look for a specific function, module or term in the index (in the back). And finally, if you enjoy learning about random subjects, you choose a random page number (see module random) and read a section or two. Regardless of the order in which you read the sections of this manual, it helps to start with chapter 2, ``Built-in Types, Exceptions and Functions,'' as the remainder of the manual assumes familiarity with this material.

Built-in Objects
Names for built-in exceptions and functions and a number of constants are found in a separate symbol table. This table is searched last when the interpreter looks up the meaning of a name, so local and global user-defined names can override built-in names. Built-in types are described together here for easy reference.2.1

The tables in this chapter document the priorities of operators by listing them in order of ascending priority (within a table) and grouping operators that have the same priority in the same box. Binary operators of the same priority group from left to right. (Unary operators group from right to left, but there you have no real choice.) See chapter 5 of the Python Reference Manual for the complete picture on operator priorities.

Built-in Functions
The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order.

__import__( name[, globals[, locals[, fromlist[, level]]]])
This function is invoked by the import statement. It mainly exists so that you can replace it with another function that has a compatible interface, in order to change the semantics of the import statement. For examples of why and how you would do this, see the standard library modules ihooks and rexec. See also the built-in module imp, which defines some useful operations out of which you can build your own __import__() function.

For example, the statement "import spam" results in the following call: __import__('spam', globals(), locals(), [], -1); the statement "from spam.ham import eggs" results in "__import__('spam.ham', globals(), locals(), ['eggs'], -1)". Note that even though locals() and ['eggs'] are passed in as arguments, the __import__() function does not set the local variable named eggs; this is done by subsequent code that is generated for the import statement. (In fact, the standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.)

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using "import spam.ham.eggs", the top-level package spam must be placed in the importing namespace, but when using "from spam.ham import eggs", the spam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, use getattr() to extract the desired components. For example, you could define the following helper:

def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod

level specifies whether to use absolute or relative imports. The default is -1 which indicates both absolute and relative imports will be attempted. 0 means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__. Changed in version 2.5: The level parameter was added. Changed in version 2.5: Keyword support for parameters was added.

abs( x)
Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.

all( iterable)
Return True if all elements of the iterable are true. Equivalent to:

def all(iterable):
for element in iterable:
if not element:
return False
return True

New in version 2.5.

any( iterable)
Return True if any element of the iterable is true. Equivalent to:

def any(iterable):
for element in iterable:
if element:
return True
return False

New in version 2.5.

basestring( )
This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or unicode. isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)). New in version 2.3.

bool( [x])
Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.

New in version 2.2.1. Changed in version 2.3: If no argument is given, this function returns False.

callable( object)
Return true if the object argument appears callable, false if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__() method.

chr( i)
Return a string of one character whose ASCII code is the integer i. For example, chr(97) returns the string 'a'. This is the inverse of ord(). The argument must be in the range [0..255], inclusive; ValueError will be raised if i is outside that range.

classmethod( function)
Return a class method for function.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator - see the description of function definitions in chapter 7 of the Python Reference Manual for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

For more information on class methods, consult the documentation on the standard type hierarchy in chapter 3 of the Python Reference Manual (at the bottom). New in version 2.2. Changed in version 2.4: Function decorator syntax added.

cmp( x, y)
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

compile( string, filename, kind[, flags[, dont_inherit]])
Compile the string into a code object. Code objects can be executed by an exec statement or evaluated by a call to eval(). The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ('<string>' is commonly used). The kind argument specifies what kind of code must be compiled; it can be 'exec' if string consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something else than None will be printed).

When compiling multi-line statements, two caveats apply: line endings must be represented by a single newline character ('\n'), and the input must be terminated by at least one newline character. If line endings are represented by '\r\n', use the string replace() method to change them into '\n'.

The optional arguments flags and dont_inherit (which are new in Python 2.2) control which future statements (see PEP 236) affect the compilation of string. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile. If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it - the future statements in effect around the call to compile are ignored.

Future statements are specified by bits which can be bitwise or-ed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module.

complex( [real[, imag]])
Create a complex number with the value real + imag*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion function like int(), long() and float(). If both arguments are omitted, returns 0j.

delattr( object, name)
This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.

dict( [arg])
Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument arg is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument must each also be of one of those kinds, and each must in turn contain exactly two objects. The first is used as a key in the new dictionary, and the second as the key's value. If a given key is seen more than once, the last value associated with it is retained in the new dictionary.

If keyword arguments are given, the keywords themselves with their associated values are added as items to the dictionary. If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary. For example, these all return a dictionary equal to {"one": 2, "two": 3}:

* dict({'one': 2, 'two': 3})
* dict({'one': 2, 'two': 3}.items())
* dict({'one': 2, 'two': 3}.iteritems())
* dict(zip(('one', 'two'), (2, 3)))
* dict([['two', 3], ['one', 2]])
* dict(one=2, two=3)
* dict([(['one', 'two'][i-2], i) for i in (2, 3)])

New in version 2.2. Changed in version 2.3: Support for building a dictionary from keyword arguments added.

dir( [object])
Without arguments, return the list of names in the current local symbol table. With an argument, attempts to return a list of valid attributes for that object. This information is gleaned from the object's __dict__ attribute, if defined, and from the class or type object. The list is not necessarily complete. If the object is a module object, the list contains the names of the module's attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes. The resulting list is sorted alphabetically. For example:

>>> import struct
>>> dir()
['__builtins__', '__doc__', '__name__', 'struct']
>>> dir(struct)
['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack']

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases.

divmod( a, b)
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

Changed in version 2.3: Using divmod() with complex numbers is deprecated.

enumerate( iterable)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from zero) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3.

eval( expression[, globals[, locals]])
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object. Changed in version 2.4: formerly locals was required to be a dictionary.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local name space. If the globals dictionary is present and lacks '__builtins__', the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard __builtin__ module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1
>>> print eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. The code object must have been compiled passing 'eval' as the kind argument.

Hints: dynamic execution of statements is supported by the exec statement. Execution of statements from a file is supported by the execfile() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or execfile().

execfile( filename[, globals[, locals]])
This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration -- it reads the file unconditionally and does not create a new module.2.2

The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If provided, locals can be any mapping object. Changed in version 2.4: formerly locals was required to be a dictionary. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. The return value is None.

Warning: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function's locals.

file( filename[, mode[, bufsize]])
Constructor function for the file type, described further in section 3.9, ``File Objects''. The constructor's arguments are the same as those of the open() built-in function described below.

When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)").

New in version 2.2.

filter( function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator, If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

float( [x])
Convert a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. Otherwise, the argument may be a plain or long integer or a floating point number, and a floating point number with the same value (within Python's floating point precision) is returned. If no argument is given, returns 0.0.

Note: When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the C library and is known to vary.

frozenset( [iterable])
Return a frozenset object whose elements are taken from iterable. Frozensets are sets that have no update methods but can be hashed and used as members of other sets or as dictionary keys. The elements of a frozenset must be immutable themselves. To represent sets of sets, the inner sets should also be frozenset objects. If iterable is not specified, returns a new empty set, frozenset([]). New in version 2.4.

getattr( object, name[, default])
Return the value of the named attributed of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

globals( )
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

hasattr( object, name)
The arguments are an object and a string. The result is True if the string is the name of one of the object's attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)

hash( object)
Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

help( [object])
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated. New in version 2.2.

hex( x)
Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression. Changed in version 2.4: Formerly only returned an unsigned literal.

id( object)
Return the ``identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)

input( [prompt])
Equivalent to eval(raw_input(prompt)). Warning: This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.)

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.

int( [x[, radix]])
Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace. The radix parameter gives the base for the conversion (which is 10 by default) and may be any integer in the range [2, 36], or zero. If radix is zero, the proper radix is guessed based on the contents of string; the interpretation is the same as for integer literals. If radix is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain or long integer or a floating point number. Conversion of floating point numbers to integers truncates (towards zero). If the argument is outside the integer range a long object will be returned instead. If no arguments are given, returns 0.

isinstance( object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct or indirect) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Changed in version 2.2: Support for a tuple of type information was added.

issubclass( class, classinfo)
Return true if class is a subclass (direct or indirect) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised. Changed in version 2.3: Support for a tuple of type information was added.

iter( o[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned. New in version 2.2.

len( s)
Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

list( [iterable])
Return a list whose items are the same and in the same order as iterable's items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For instance, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, returns a new empty list, [].

locals( )
Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter.

long( [x[, radix]])
Convert a string or number to a long integer. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace. The radix argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns 0L.

map( function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

max( iterable[, args...][key])
With a single argument iterable, return the largest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the largest of the arguments.

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, "max(a,b,c,key=func)"). Changed in version 2.5: Added support for the optional key argument.

min( iterable[, args...][key])
With a single argument iterable, return the smallest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments.

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, "min(a,b,c,key=func)"). Changed in version 2.5: Added support for the optional key argument.

object( )
Return a new featureless object. object is a base for all new style classes. It has the methods that are common to all instances of new style classes. New in version 2.2.

Changed in version 2.3: This function does not accept any arguments. Formerly, it accepted arguments but ignored them.

oct( x)
Convert an integer number (of any size) to an octal string. The result is a valid Python expression. Changed in version 2.4: Formerly only returned an unsigned literal.

open( filename[, mode[, bufsize]])
Open a file, returning an object of the file type described in section 3.9, ``File Objects''. If the file cannot be opened, IOError is raised. When opening a file, it's preferable to use open() instead of invoking the file constructor directly.

The first two arguments are the same as for stdio's fopen(): filename is the file name to be opened, and mode is a string indicating how the file is to be opened.

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. When opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don't treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

The optional bufsize argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.2.3

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don't have this distinction, adding the 'b' has no effect.

In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

Python enforces that the mode, after stripping 'U', begins with 'r', 'w' or 'a'.

Changed in version 2.5: Restriction on first letter of mode string introduced.

ord( c)
Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character's code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a TypeError will be raised.

pow( x, y[, z])
Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int and long int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. (This last feature was added in Python 2.2. In Python 2.1 and before, if both arguments were of integer types and the second argument was negative, an exception was raised.) If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative. (This restriction was added in Python 2.2. In Python 2.1 and before, floating 3-argument pow() returned platform-dependent results depending on floating-point rounding accidents.)

property( [fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object).

fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x:

class C(object):
def __init__(self): self._x = None
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

class Parrot(object):
def __init__(self):
self._voltage = 100000

@property
def voltage(self):
"""Get the current voltage."""
return self._voltage

turns the voltage() method into a ``getter'' for a read-only attribute with the same name.

New in version 2.2. Changed in version 2.5: Use fget's docstring if no doc given.

range( [start,] stop[, step])
This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]

raw_input( [prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features.

reduce( function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

reload( module)
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).

When reload(module) is executed:

* Python modules' code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module's dictionary. The init function of extension modules is not called a second time.

* As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.

* The names in the module namespace are updated to point to any new or changed objects.

* Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

There are a number of other caveats:

If a module is syntactically correct but its initialization fails, the first import statement for it does not bind its name locally, but does store a (partially initialized) module object in sys.modules. To reload the module you must first import it again (this will bind the name to the partially initialized module object) before you can reload() it.

When a module is reloaded, its dictionary (containing the module's global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module's advantage if it maintains a global table or cache of objects -- with a try statement it can test for the table's presence and skip its initialization if desired:

try:
cache
except NameError:
cache = {}

It is legal though generally not very useful to reload built-in or dynamically loaded modules, except for sys, __main__ and __builtin__. In many cases, however, extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded.

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it -- one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead.

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances -- they continue to use the old class definition. The same is true for derived classes.

repr( object)
Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval().

reversed( seq)
Return a reverse iterator. seq must be an object which supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0). New in version 2.4.

round( x[, n])
Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

set( [iterable])
Return a set whose elements are taken from iterable. The elements must be immutable. To represent sets of sets, the inner sets should be frozenset objects. If iterable is not specified, returns a new empty set, set([]). New in version 2.4.

setattr( object, name, value)
This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

slice( [start,] stop[, step])
Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: "a[start:stop:step]" or "a[start:stop, i]".

sorted( iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable.

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section 3.6.4).

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: "cmp=lambda x,y: cmp(x.lower(), y.lower())"

key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower"

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

New in version 2.4.

staticmethod( function)
Return a static method for function.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
@staticmethod
def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator - see the description of function definitions in chapter 7 of the Python Reference Manual for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod() in this section.

For more information on static methods, consult the documentation on the standard type hierarchy in chapter 3 of the Python Reference Manual (at the bottom). New in version 2.2. Changed in version 2.4: Function decorator syntax added.

str( [object])
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.

sum( iterable[, start])
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable's items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate a sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) New in version 2.3.

super( type[, object-or-type])
Return the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new-style classes.

A typical use for calling a cooperative superclass method is:

class C(B):
def meth(self, arg):
super(C, self).meth(arg)

Note that super is implemented as part of the binding process for explicit dotted attribute lookups such as "super(C, self).__getitem__(name)". Accordingly, super is undefined for implicit lookups using statements or operators such as "super(C, self)[name]". New in version 2.2.

tuple( [iterable])
Return a tuple whose items are the same and in the same order as iterable's items. iterable may be a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For instance, tuple('abc') returns ('a', 'b', 'c') and tuple([1, 2, 3]) returns (1, 2, 3). If no argument is given, returns a new empty tuple, ().

type( object)
Return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.

With three arguments, type functions as a constructor as detailed below.

type( name, bases, dict)
Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute. For example, the following two statements create identical type objects:

>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1))

New in version 2.2.

unichr( i)
Return the Unicode string of one character whose Unicode code is the integer i. For example, unichr(97) returns the string u'a'. This is the inverse of ord() for Unicode strings. The valid range for the argument depends how Python was configured - it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF]. ValueError is raised otherwise. New in version 2.0.

unicode( [object[, encoding [, errors]]])
Return the Unicode string version of object using one of the following modes:

If encoding and/or errors are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised. Error handling is done according to errors; this specifies the treatment of characters which are invalid in the input encoding. If errors is 'strict' (the default), a ValueError is raised on errors, while a value of 'ignore' causes errors to be silently ignored, and a value of 'replace' causes the official Unicode replacement character, U+FFFD, to be used to replace input characters which cannot be decoded. See also the codecs module.

If no optional parameters are given, unicode() will mimic the behaviour of str() except that it returns Unicode strings instead of 8-bit strings. More precisely, if object is a Unicode string or subclass it will return that Unicode string without any additional decoding applied.

For objects which provide a __unicode__() method, it will call this method without arguments to create a Unicode string. For all other objects, the 8-bit string version or representation is requested and then converted to a Unicode string using the codec for the default encoding in 'strict' mode.

New in version 2.0. Changed in version 2.2: Support for __unicode__() added.

vars( [object])
Without arguments, return a dictionary corresponding to the current local symbol table. With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table. The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.2.4

xrange( [start,] stop[, step])
This function is very similar to range(), but returns an ``xrange object'' instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range's elements are never used (such as when the loop is usually terminated with break).

Note: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs ("short" Python integers), and also requires that the number of elements fit in a native C long.

zip( [iterable, ...])
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list. New in version 2.0.

Changed in version 2.4: Formerly, zip() required at least one argument and zip() raised a TypeError instead of returning an empty list.

Non-essential Buitl-in Functions
There are several built-in functions that are no longer essential to learn, know or use in modern Python programming. They have been kept here to maintain backwards compatibility with programs written for older versions of Python.

Python programmers, trainers, students and bookwriters should feel free to bypass these functions without concerns about missing something important.

apply( function, args[, keywords])
The function argument must be a callable object (a user-defined or built-in function or method, or a class object) and the args argument must be a sequence. The function is called with args as the argument list; the number of arguments is the length of the tuple. If the optional keywords argument is present, it must be a dictionary whose keys are strings. It specifies keyword arguments to be added to the end of the argument list. Calling apply() is different from just calling function(args), since in that case there is always exactly one argument. The use of apply() is exactly equivalent to function(*args, **keywords).

Deprecated since release 2.3. Use the extended call syntax with *args and **keywords instead.

buffer( object[, offset[, size]])
The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object will be created which references the object argument. The buffer object will be a slice from the beginning of object (or from the specified offset). The slice will extend to the end of object (or will have a length given by the size argument).

coerce( x, y)
Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations. If coercion is not possible, raise TypeError.

intern( string)
Enter string in the table of ``interned'' strings and return the interned string - which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup - if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys. Changed in version 2.3: Interned strings are not immortal (like they used to be in Python 2.2 and before); you must keep a reference to the return value of intern() around to benefit from it.

Built-in Exceptions
Exceptions should be class objects. The exceptions are defined in the module exceptions. This module never needs to be imported explicitly: the exceptions are provided in the built-in namespace as well as the exceptions module.

Note: In past versions of Python string exceptions were supported. In Python 1.5 and newer versions, all standard exceptions have been converted to class objects and users are encouraged to do the same. String exceptions will raise a DeprecationWarning in Python 2.5 and newer. In future versions, support for string exceptions will be removed.

Two distinct string objects with the same value are considered different exceptions. This is done to force programmers to use exception names rather than their string value when specifying exception handlers. The string value of all built-in exceptions is their name, but this is not a requirement for user-defined exceptions or exceptions defined by library modules.

For class exceptions, in a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

The built-in exceptions listed below can be generated by the interpreter or built-in functions. Except where mentioned, they have an ``associated value'' indicating the detailed cause of the error. This may be a string or a tuple containing several items of information (e.g., an error code and a string explaining the code). The associated value is the second argument to the raise statement. For string exceptions, the associated value itself will be stored in the variable named as the second argument of the except clause (if any). For class exceptions, that variable receives the exception instance. If the exception class is derived from the standard root class BaseException, the associated value is present as the exception instance's args attribute. If there is a single argument (as is preferred), it is bound to the message attribute.

User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition ``just like'' the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error.

The built-in exception classes can be sub-classed to define new exceptions; programmers are encouraged to at least derive new exceptions from the Exception class and not BaseException. More information on defining exceptions is available in the Python Tutorial under the heading ``User-defined Exceptions.''

The following exceptions are only used as base classes for other exceptions.

exception BaseException
The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that use Exception). If str() or unicode() is called on an instance of this class, the representation of the argument(s) to the instance are returned or the emptry string when there were no arguments. If only a single argument is passed in, it is stored in the message attribute. If more than one argument is passed in, message is set to the empty string. These semantics are meant to reflect the fact that message is to store a text message explaining why the exception had been raised. If more data needs to be attached to the exception, attach it through arbitrary attributes on the instance. All arguments are also stored in args as a tuple, but it will eventually be deprecated and thus its use is discouraged. New in version 2.5.

exception Exception
All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class. Changed in version 2.5: Changed to inherit from BaseException.

exception StandardError
The base class for all built-in exceptions except StopIteration, GeneratorExit, KeyboardInterrupt and SystemExit. StandardError itself is derived from Exception.

exception ArithmeticError
The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.

exception LookupError
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by sys.setdefaultencoding().

exception EnvironmentError
The base class for exceptions that can occur outside the Python system: IOError, OSError. When exceptions of this type are created with a 2-tuple, the first item is available on the instance's errno attribute (it is assumed to be an error number), and the second item is available on the strerror attribute (it is usually the associated error message). The tuple itself is also available on the args attribute. New in version 1.5.2.

When an EnvironmentError exception is instantiated with a 3-tuple, the first two items are available as above, while the third item is available on the filename attribute. However, for backwards compatibility, the args attribute contains only a 2-tuple of the first two constructor arguments.

The filename attribute is None when this exception is created with other than 3 arguments. The errno and strerror attributes are also None when the instance was created with other than 2 or 3 arguments. In this last case, args contains the verbatim constructor arguments as a tuple.

The following exceptions are the exceptions that are actually raised.

exception AssertionError
Raised when an assert statement fails.

exception AttributeError
Raised when an attribute reference or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)

exception EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data. (N.B.: the read() and readline() methods of file objects return an empty string when they hit EOF.)

exception FloatingPointError
Raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the --with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h file.

exception GeneratorExit
Raise when a generator's close() method is called. It directly inherits from Exception instead of StandardError since it is technically not an error. New in version 2.5.

exception IOError
Raised when an I/O operation (such as a print statement, the built-in open() function or a method of a file object) fails for an I/O-related reason, e.g., ``file not found'' or ``disk full''.

This class is derived from EnvironmentError. See the discussion above for more information on exception instance attributes.

exception ImportError
Raised when an import statement fails to find the module definition or when a from ... import fails to find a name that is to be imported.

exception IndexError
Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not a plain integer, TypeError is raised.)

exception KeyError
Raised when a mapping (dictionary) key is not found in the set of existing keys.

exception KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. Interrupts typed when a built-in function input() or raw_input() is waiting for input also raise this exception. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting. Changed in version 2.5: Changed to inherit from BaseException.

exception MemoryError
Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C's malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.

exception NameError
Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.

exception NotImplementedError
This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method. New in version 1.5.2.

exception OSError
This class is derived from EnvironmentError and is used primarily as the os module's os.error exception. See EnvironmentError above for a description of the possible associated values. New in version 1.5.2.

exception OverflowError
Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for long integers (which would rather raise MemoryError than give up). Because of the lack of standardization of floating point exception handling in C, most floating point operations also aren't checked. For plain integers, all operations that can overflow are checked except left shift, where typical applications prefer to drop bits than raise an exception.

exception ReferenceError
This exception is raised when a weak reference proxy, created by the weakref.proxy() function, is used to access an attribute of the referent after it has been garbage collected. For more information on weak references, see the weakref module. New in version 2.2: Previously known as the weakref.ReferenceError exception.

exception RuntimeError
Raised when an error is detected that doesn't fall in any of the other categories. The associated value is a string indicating what precisely went wrong. (This exception is mostly a relic from a previous version of the interpreter; it is not used very much any more.)

exception StopIteration
Raised by an iterator's next() method to signal that there are no further values. This is derived from Exception rather than StandardError, since this is not considered an error in its normal application. New in version 2.2.

exception SyntaxError
Raised when the parser encounters a syntax error. This may occur in an import statement, in an exec statement, in a call to the built-in function eval() or input(), or when reading the initial script or standard input (also interactively).

Instances of this class have attributes filename, lineno, offset and text for easier access to the details. str() of the exception instance returns only the message.

exception SystemError
Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms).

You should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (sys.version; it is also printed at the start of an interactive Python session), the exact error message (the exception's associated value) and if possible the source of the program that triggered the error.

exception SystemExit
This exception is raised by the sys.exit() function. When it is not handled, the Python interpreter exits; no stack traceback is printed. If the associated value is a plain integer, it specifies the system exit status (passed to C's exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object's value is printed and the exit status is one.

Instances have an attribute code which is set to the proposed exit status or error message (defaulting to None). Also, this exception derives directly from BaseException and not StandardError, since it is not technically an error.

A call to sys.exit() is translated into an exception so that clean-up handlers (finally clauses of try statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. The os._exit() function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call to fork()).

The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit. Changed in version 2.5: Changed to inherit from BaseException.

exception TypeError
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

exception UnboundLocalError
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError. New in version 2.0.

exception UnicodeError
Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError. New in version 2.0.

exception UnicodeEncodeError
Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError. New in version 2.3.

exception UnicodeDecodeError
Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError. New in version 2.3.

exception UnicodeTranslateError
Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError. New in version 2.3.

exception ValueError
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

exception WindowsError
Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value. The winerror and strerror values are created from the return values of the GetLastError() and FormatMessage() functions from the Windows Platform API. The errno value maps the winerror value to corresponding errno.h values. This is a subclass of OSError. New in version 2.0. Changed in version 2.5: Previous versions put the GetLastError() codes into errno.

exception ZeroDivisionError
Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.

The following exceptions are used as warning categories; see the warnings module for more information.

exception Warning
Base class for warning categories.

exception UserWarning
Base class for warnings generated by user code.

exception DeprecationWarning
Base class for warnings about deprecated features.

exception PendingDeprecationWarning
Base class for warnings about features which will be deprecated in the future.

exception SyntaxWarning
Base class for warnings about dubious syntax

exception RuntimeWarning
Base class for warnings about dubious runtime behavior.

exception FutureWarning
Base class for warnings about constructs that will change semantically in the future.

exception ImportWarning
Base class for warnings about probable mistakes in module imports. New in version 2.5.

exception UnicodeWarning
Base class for warnings related to Unicode. New in version 2.5.

The class hierarchy for built-in exceptions is:

BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- Exception
+-- GeneratorExit
+-- StopIteration
+-- StandardError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| | +-- UnicodeError
| | +-- UnicodeDecodeError
| | +-- UnicodeEncodeError
| | +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning

Built-in Types
2.4 Built-in Constants

A small number of constants live in the built-in namespace. They are:

False
The false value of the bool type. New in version 2.3.

True
The true value of the bool type. New in version 2.3.

None
The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.

NotImplemented
Special value which can be returned by the ``rich comparison'' special methods (__eq__(), __lt__(), and friends), to indicate that the comparison is not implemented with respect to the other type.

Ellipsis
Special value used in conjunction with extended slicing syntax.


3.1 Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

* None

* False

* zero of any numeric type, for example, 0, 0L, 0.0, 0j.

* any empty sequence, for example, '', (), [].

* any empty mapping, for example, {}.

* instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.3.1

All other values are considered true -- so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations "or" and "and" always return one of their operands.)

3.2 Boolean Operations -- and, or, not

These are the Boolean operations, ordered by ascending priority:

Operation Result Notes
x or y if x is false, then y, else x (1)
x and y if x is false, then x, else y (1)
not x if x is false, then True, else False (2)

Notes:

(1)
These only evaluate their second argument if needed for their outcome.

(2)
"not" has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

3.3 Comparisons

Comparison operations are supported by all objects. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

This table summarizes the comparison operations:

Operation Meaning Notes
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal (1)
<> not equal (1)
is object identity
is not negated object identity

Notes:

(1)
<> and != are alternate spellings for the same operator. != is the preferred spelling; <> is obsolescent.

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

Instances of a class normally compare as non-equal unless the class defines the __cmp__() method. Refer to the Python Reference Manual for information on the use of this method to effect object comparisons.

Implementation note: Objects of different types except numbers are ordered by their type names; objects of the same types that don't support proper comparison are ordered by their address.

Two more operations with the same syntactic priority, "in" and "not in", are supported only by sequence types (below).

3.4 Numeric Types -- int, float, long, complex

There are four distinct numeric types: plain integers, long integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of plain integers. Plain integers (also just called integers) are implemented using long in C, which gives them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value for the current platform, the minimum value is -sys.maxint - 1). Long integers have unlimited precision. Floating point numbers are implemented using double in C. All bets on their precision are off unless you happen to know the machine you are working with.

Complex numbers have a real and imaginary part, which are each implemented using double in C. To extract these parts from a complex number z, use z.real and z.imag.

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an "L" or "l" suffix yield long integers ("L" is preferred because "1l" looks too much like eleven!). Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending "j" or "J" to a numeric literal yields a complex number with a zero real part. A complex numeric literal is the sum of a real and an imaginary part.

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the ``narrower'' type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule.3.2 The constructors int(), long(), float(), and complex() can be used to produce numbers of a specific type.

All numeric types (except complex) support the following operations, sorted by ascending priority (operations in the same box have the same priority; all numeric operations have a higher priority than comparison operations):

Operation Result Notes
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y (1)
x // y (floored) quotient of x and y (5)
x % y remainder of x / y (4)
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer (2)
long(x) x converted to long integer (2)
float(x) x converted to floating point
complex(re,im) a complex number with real part re, imaginary part im. im defaults to zero.
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y) (3)(4)
pow(x, y) x to the power y
x ** y x to the power y

Notes:

(1)
For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.

(2)
Conversion from floating point to (long or plain) integer may round or truncate as in C; see functions floor() and ceil() in the math module for well-defined conversions.

(3)
See section 2.1, ``Built-in Functions,'' for a full description.

(4)
Complex floor division operator, modulo operator, and divmod().

Deprecated since release 2.3. Instead convert to float using abs() if appropriate.

(5)
Also referred to as integer division. The resultant value is a whole integer, though the result's type is not necessarily int.

3.4.1 Bit-string Operations on Integer Types

Plain and long integer types support additional operations that make sense only for bit-strings. Negative numbers are treated as their 2's complement value (for long integers, this assumes a sufficiently large number of bits that no overflow occurs during the operation).

The priorities of the binary bit-wise operations are all lower than the numeric operations and higher than the comparisons; the unary operation "~" has the same priority as the other unary numeric operations ("+" and "-").

This table lists the bit-string operations sorted in ascending priority (operations in the same box have the same priority):

Operation Result Notes
x | y bitwise or of x and y
x ^ y bitwise exclusive or of x and y
x & y bitwise and of x and y
x << n x shifted left by n bits (1), (2)
x >> n x shifted right by n bits (1), (3)
~x the bits of x inverted

Notes:

(1)
Negative shift counts are illegal and cause a ValueError to be raised.
(2)
A left shift by n bits is equivalent to multiplication by pow(2, n) without overflow check.
(3)
A right shift by n bits is equivalent to division by pow(2, n) without overflow check.

3.5 Iterator Types

New in version 2.2.

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.

One method needs to be defined for container objects to provide iteration support:

__iter__( )
Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

__iter__( )
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

next( )
Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.

The intention of the protocol is that once an iterator's next() method raises StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken. (This constraint was added in Python 2.3; in Python 2.2, various iterators are broken according to this rule.)

Python's generators provide a convenient way to implement the iterator protocol. If a container object's __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() methods.

3.6 Sequence Types -- str, unicode, list, tuple, buffer, xrange

There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects.

String literals are written in single or double quotes: 'xyzzy', "frobozz". See chapter 2 of the Python Reference Manual for more about string literals. Unicode strings are much like strings, but are specified in the syntax using a preceding "u" character: u'abc', u"def". Lists are constructed with square brackets, separating items with commas: [a, b, c]. Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as a, b, c or (). A single item tuple must have a trailing comma, such as (d,).

Buffer objects are not directly supported by Python syntax, but can be created by calling the builtin function buffer(). They don't support concatenation or repetition.

Xrange objects are similar to buffers in that there is no specific syntax to create them, but they are created using the xrange() function. They don't support slicing, concatenation or repetition, and using in, not in, min() or max() on them is inefficient.

Most sequence types support the following operations. The "in" and "not in" operations have the same priorities as the comparison operations. The "+" and "*" operations have the same priority as the corresponding numeric operations.3.3

This table lists the sequence operations sorted in ascending priority (operations in the same box have the same priority). In the table, s and t are sequences of the same type; n, i and j are integers:

Operation Result Notes
x in s True if an item of s is equal to x, else False (1)
x not in s False if an item of s is equal to x, else True (1)
s + t the concatenation of s and t (6)
s * n , n * s n shallow copies of s concatenated (2)
s[i] i'th item of s, origin 0 (3)
s[i:j] slice of s from i to j (3), (4)
s[i:j:k] slice of s from i to j with step k (3), (5)
len(s) length of s
min(s) smallest item of s
max(s) largest item of s

Notes:

(1)
When s is a string or Unicode string object the in and not in operations act like a substring test. In Python versions before 2.3, x had to be a string of length 1. In Python 2.3 and beyond, x may be a string of any length.

(2)
Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

(3)
If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

(4)
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

(5)
The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that $0 \leq n < \frac{j-i}{k}$. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become ``end'' values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

(6)
If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations. Changed in version 2.4: Formerly, string concatenation never occurred in-place.

3.6.1 String Methods

These are the string methods which both 8-bit strings and Unicode objects support:

capitalize( )
Return a copy of the string with only its first character capitalized.

For 8-bit strings, this method is locale-dependent.

center( width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar (default is a space). Changed in version 2.4: Support for the fillchar argument.

count( sub[, start[, end]])
Return the number of occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

decode( [encoding[, errors]])
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error, see section 4.8.1. New in version 2.2. Changed in version 2.3: Support for other error handling schemes added.

encode( [encoding[,errors]])
Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error, see section 4.8.1. For a list of possible encodings, see section


ကြၽန္ေတာ္ ငါးပုိင္းေလာက္ ခြဲေရးထားပါတယ္ ပူးတြဲျပရင္ စာလုံးအေရအတြက္ မ်ားသြားလုိ႔ပါ

Last edited by ေမာင္ဧက; 12-09-2008 at 11:51 PM..
ေမာင္ဧက is offline   Reply With Quote
ေအာက္ပါအသင္း၀င္မွ ေမာင္ဧက အား ေက်းဇူးတင္စကား ေျပာၾကားသြားပါသည္။
Old 31-12-2010, 04:12 PM
  post #8
thureinsoe
MF Contributor
 
thureinsoe's Avatar
 
အသင္း၀င္ေန႔စြဲ: Mar 2010
တည္ေနရာ: ရန္ကုန္
ေရးသားခ်က္မ်ား: 580
ႏိုင္ငံအလံ: Users Flag!
ေက်းဇူးတင္စကား: 2,093
ပို႔စ္ 525 ခုအတြက္ 3,955 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
thureinsoe will become famous soon enough
Icon12 Python ebookေလးပါ

Python အေၾကာင္းကိုေတာ႔ ၾကားဖူးၾကမွာပါ.
Python ဟာ ေလ႔လာရလြယ္ကူၿပီး ေရးရာတြင္
Productivity ေကာင္းတယ္ဆိုၾကပါတယ္
Python ဟာ Hight Level Programming Language
ျဖစ္ပါတယ္
ပိုသိခ်င္ေတာ့
Code:
http://python.org/
http://en.wikipedia.org/wiki/Python_...ng_language%29
ေအာက္ကလင့္ကေတာ့ Python ebookေလးပါ

သူတည္းတစ္ေယာက္ေကာင္းဖို႔ေရာက္မူ သူတစ္ေယာက္မွာပ်က္လင္႔ကာသာဓမၼတာတည္း
နႏၵသူရိယအမတ္ၾကီး


phpcrazy.mm@gmail.com
thureinsoe is offline   Reply With Quote
ေအာက္ပါအသင္း၀င္ 2 ဦးတို႔မွ thureinsoe အား ေက်းဇူးတင္စကား ေျပာၾကားသြားပါသည္။
Reply

တန္ဆာပလာမ်ား
ေဖာ္ျပမႈပံုစံ

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

ဖိုရမ္ေတြ ေက်ာ္ေရာက္ခ်င္ရင္ !


ဖိုရမ္၏ ပင္မအခ်ိန္သည္ ဂရင္းနစ္စံေတာ္ခ်ိန္ +6.5 ျဖစ္သည္။ေဒသစံေတာ္ခ်ိန္ 10:28 PM
Inactive Reminders By Icora Web Design