This article mainly introduces new features compared with python2.6 and python3.0. For more information, see the python3.0 documentation.
Common stumbling blocks
This section briefly lists the changes that are prone to human errors.
- The print statement is replaced by the print () function. You can use the keyword parameter to replace the previous special print syntax. For example:
- Old: Print "the answer is", 2*2
- New: Print ("the answer is", 2*2)
- Old: Print
X,
# Use a comma to end a line break.
- New: Print (x, end ="
")
# Use spaces instead of line breaks
- Old:
Print
# Output a new line
- New:
Print ()
# Output a new line
- Old: Print> SYS. stderr, "fatal
Error"
- New: Print ("Fatal error", file = SYS. stderr)
- Old: Print (X,
Y)
# Output repr (x, y ))
- New: Print (X,
Y ))
# Unlike print (x, y )!
You can customize the delimiter between output items:
Print ("there are <", 2 ** 32, ">
Possibilities !", SEP = "")
The output result is:
There are <4294967296>
Possibilities!
Note:
- The print () function does not support the "Soft Space" feature of the old print statement. For example, in python2.x, print "A/N ",
"B" outputs "A/Nb/N", while in python3.0, print ("A/N", "B") Outputs "A/n B/N"
- Learn to get used to print!
- When 2to3 source code conversion tool is used, all print statements are automatically converted to the print () function call. This does not need to be argued for large projects.
- Python3.0 uses strings (strings) and bytes to replace Unicode strings and 8-bit strings, which means that almost all codes using Unicode encoding and binary data must be modified. This change is good. In the 2. x world, countless bugs are caused by coding problems.
- Map () and filter () return iterator (iterators)
- Dict Methods keys (), items (), values () return to the view (also an iterator) rather than list)
- The built-in sorted () and list. Sort () Methods no longer accept CMP parameters that represent comparison functions, instead of key parameters.
- 1/2 returns a floating point number. You can use 1/2 to obtain an integer.
- The repr () function no longer contains the trailing L for long integers, so removing the last character without any judgment will lead to removing a useful number.
String and bytes
- There is only one character string: Str. Its behavior and implementation are very similar to the Unicode string of 2. x.
- The basestring superclass have been removed. The 2to3 tool replaces each existing basestring with Str.
- Pep3133: new bytes type, used to represent binary data and encoded text. STR and bytes cannot be mixed. If needed, the display must be converted. The conversion method is str. encode () (STR-> bytes) and bytes. decode () (bytes-> Str ).
- All backslash characters in the original string (raw strings) are interpreted literally, and Unicode escape characters are not specially processed.
- Pep3112: bytes literal volume, such as B "ABC", to create a bytes instance.
- Pep3120: Default source file encoding for UTF-8
- Pep3131: Non-ASCII identifiers can be used (however, except for the contributor name in the annotation, the standard library still only contains ASCII)
- Pep3116: new IO implementation, API is almost 100% backward compatible, and binary files use bytes instead of strings
- Remove the stringio and cstringio modules and replace them with IO. stringio or IO. bytesio.
Pep3101: A New Method for string formatting
- Str. Format method (the % operator is replaced in the original article. In fact, the format method differs greatly from %, and each has its own strengths ).
Pep3106: fixed the keys (), items (), values () Methods of dict.
- Dict. iterkeys (), dict. itervalues (), and dict. iteritems () are deleted ()
- Dict. Keys (), dict. Values (), and dict. Items () return references to dict-related data.
Pep3107: function annotations)
- Standardized methods for annotation function parameters and return values
Exception stuff
- Pep352: The exception class must inherit from baseexception, which is the base class of the exception structure.
- Removed standarderror
- Dropping sequence behavior (slicing !) And message attribute
Exception instances.
- Pep3109: throwing an exception: Now you must use raise exception (ARGs) instead of the original raise exception,
ARGs
- Pep3110: capture exceptions. Now we must use failed t exception as identifier instead of the original failed t
Exception, identifier
- Pep3134: exception chain ).
- Improved some exception information when Windows cannot load mode, with localized processing.
New Class and metaclass stuff
- Classic class removed
- Pep3115: New metaclass syntax
- Pep3119: abstract base class.
- Pep3129: Class packaging.
- Pep3141: base class of digital Abstraction
Other language changes
Here we will list the changes to the core and built-in functions of most Python languages.
- Removed backticks (replaced by repr)
- Removed <> (non-equal sign, use! = Replace)
- As and with become keywords
- True, false, and none are converted into keywords.
- Pep237: Long does not exist. Only int exists. It is the same as long. It no longer supports literal numbers ending with L. Remove SYS. maxint because Int Is already infinitely large.
- Pep238: int division, returns float
- Changes the behavior of sequence operators, such as x <Y. If the X and Y types do not match, a typeerror is thrown instead of returning the immediate bool value.
- _ Getslice __is removed. Syntax A [I: J] is interpreted as a. _ getitem _ (slice (I, j ))
- Pep3102: keyword-only
Arguments. In the function parameter list, the named parameters that appear after * ARGs can only be called in the form of "keyword Parameters ".
- Pep3104: nonlocal declaration. You can use nonlocal to declare an external variable (not a global variable)
- Pep3111: raw_input ()
The name is changed to input (), that is, the new input () function is from the standard input device (sys. stdin) reads a row and returns the result (excluding the row Terminator). If the input terminates prematurely, this function throws an eoferror. If you want to use the old input (), you can use (input ()).
- Xrange () is renamed to range (), and range () is not a list, but an iterator.
- Pep3113: tuple parameter unpacking is removed )". This writing method is no longer available:
Def Foo (A, (B, c )):...
Write as follows:
Def Foo (A, B _c ):
B, c = B _c
- Pep3114: Rename next () to _ next _ (). The new built-in function next () can call the _ next _ () method of an object.
- Pep3127: New octal literal, binary literal, and bin () function. You should write 0o666 instead of 0666, And the OCT () function has also made a response change. Similarly, 0b1010 is equivalent to 10. Bin (10) returns "0b1010 ″. 0666.
- Pep3132: Support for iterator package splitting. Now you can write:
A, B, * rest = some_seqence
Even like this:
* Rest, A = stuff
In general, the rest object is a list, and the object on the right of the equal sign is iteratable.
- Pep3135: New Super (). You can not use any parameters to call Super (). The correct parameters and actual conditions are correctly selected. If a parameter is used, its behavior remains the same as before.
- Zip (), map (), filter () returns the iterator.
- Removed string. Letters and its friends (string. lowcase and string. uppercase). Now we are playing string. ascii_letters.
- Removed apply (), callable (), exefile (), file (), reduce (), reload ()
- Dict. has_key () is removed (). Test with the in Operator
- The exec statement is missing. It is the exec () function.
- Special _ Oct _ () and _ hex _ () methods are removed. The OCT () and hex () methods use _ index __()
- Removed the support for _ members _ and _ Methods _.
- Rename nb_nonzero to nb_bool, __nonzero _ () to _ bool __()
Optimizations
- Generally, Python 3.0 is about 2.5 slower than Python 33%. However, there is still room for improvement.
Module changes (new, improved, and obsolete)
- The cpickle module is removed and can be replaced by the pickle module. In the end, we will have a transparent and efficient module.
- Removed the imageop module.
- Removed audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, MD5,
Mimewriter, mimify, popen2, rexec, sets, Sha, stringold, strop,
Sunaudiodev, timing, and xmllib modules
- Removed bsddb module (released separately, available at http://www.jcea.es/programacion/pybsddb.htm)
- Removed the new module.
- OS. tmpnam () and OS. tmpfile () functions are moved to the tmpfile module.
- The tokenize module currently uses bytes to work. The main entry point is not generate_tokens, but tokenize. tokenize ()
Build and c api changes
Python's build process and c api changes include:
- Pep3118: New Buffer API
- Pep3121: initialization of the extension module &
Finalization
- Pep3123: Make pyobject_head conform to standard C
Other changes and fixes
A series of improvements and bug fixes are scattered in the source code. Changes log indicates that from 2.6 to 3.0, there are XXX changes and YYY bug fixes.