The resource loading... loading...

Modifications of Python 2.x.x with Python 3.x.x & Methods of converting Python 2.x.x to Python 3.x.x

Author: Inventors quantify - small dreams, Created: 2016-10-09 12:36:49, Updated: 2017-10-11 10:18:05

Python 2 and Python 3 syntax differences, changes

Almost all Python 2 programs require some modification to run properly in Python 3 environments. To simplify this conversion process, Python 3 comes with a utility script called 2to3, which takes your Python 2 program source file as input and then automatically converts it to Python 3 form. Case study: Porting chardet to Python 3 describes how to run the script, and then shows some of the situations it cannot repair automatically.

  • print statements

In Python 2, print is a statement. Whatever you want to output, you can just put it after the print keyword. In Python 3, print is a function. Like any other function, print requires that you pass what you want to output to it as an argument.

Notes Python 2 Python 3
print print()
print 1 print(1)
print 1,2 print(1,2)
print 1,2, print(1,2,end=’ ')
print >>sys.stderr,1,2,3 print(1,2,3, file=sys.stderr)

1, to output a blank line, print without parameters is called (((((((( 2, to output a separate value, you need to use this value as a print () parameter. 3, two values separated by a space are used for the output and can be called print ((() with two parameters. There are a few tricks to this example. In Python 2, if you use a comma (,) as the end of a print statement, it will output the result with a space separator, and then output a trailing space without a carriage return. In Python 3, the same effect can be achieved by passing the end = as a keyword parameter to print. 5. In Python 2, you can redirect the output to a pipeline using the >pipe_name syntax, such as sys.stderr. In Python 3, you can do the same by passing the pipeline as a keyword parameter file value to print. The default value of the parameter file is std.stdout, so resetting its value will make print () output to another pipeline.

  • Unicode strings

Python 2 has two types of strings:Unicode stringsandNon-Unicode stringsThere is only one type in Python 3:Unicode strings

Notes Python 2 Python 3
u‘PapayaWhip’ ‘PapayaWhip’
ur’PapayaWhip\foo’ r‘PapayaWhip\foo’

The Unicode strings in Python 2 are ordinary strings in Python 3 because in Python 3 the strings are always in Unicode form. The Unicode raw string ("Python does not automatically translate inverse slope" using this string) is also replaced with a normal string, since in Python 3 all raw strings are encoded in Unicode.

  • Unicode for the global function

There are two global functions in Python 2 that can force an object to be converted into a string: unicode ((() converts an object to a Unicode string, and str ((() converts an object to a non-Unicode string. Python 3 has only one string type, a Unicode string, so the str ((() function can do all the functions.The unicode ((() function is no longer available in Python 3.)

Notes Python 2 Python 3
unicode(anything) str(anything)
  • long full length

Python 2 has int and long types prepared for non-floating point numbers. The maximum value of the type int cannot exceed sys.maxint, and this maximum value is platform-related. The long integer type can be defined by adding an L at the end of the number, which is obviously larger than the numerical range represented by the type int. In Python 3, there is only one integer type int, which in most cases is very similar to the long integer type in Python 2.

Read more: PEP 237: unifying the long and the full.

Notes Python 2 Python 3
x = 1000000000000L x = 1000000000000
x = 0xFFFFFFFFFFFFL x = 0xFFFFFFFFFFFF
long(x) int(x)
type(x) is long type(x) is int
isinstance(x,long) isinstance(x,int)

In Python 2, the decimal-length integer is replaced by the decimal-length normal integer in Python 3. In Python 2, the 16-digit long integer is replaced by the 16-digit normal integer in Python 3. In Python 3, since the long integral no longer exists, it's possible to create a long integral in Python 3.The natural long ((() function is also missing. To force the conversion of a variable to an integer, the int ((( function can be used.I'm not sure. Checks whether a variable is integer, obtains its data type, and compares it to an int type ((not long)). You can also use the isinstance () function to check the data type; once again, use int, not long, to check the integer type.

  • <> comparison operator

Python 2 supports <> as a synonym for!=. Python 3 only supports!=, no longer supports <>.

Notes Python 2 Python 3
if x <> y: if x != y:
if x <> y<> z: if x != y!= z:

1, simply compare. 2, comparison between three relatively complex values.

  • The dictionary class method has_key ((()

In Python 2, the has_key method of a dictionary object is used to test whether the dictionary contains a specific key. Python 3 no longer supports this method.inThe operator.

Notes Python 2 Python 3
a_dictionary.has_key(‘PapayaWhip’) ‘PapayaWhip’ in a_dictionary
a_dictionary.has_key(x) or a_dictionary.has_key(y) x in a_dictionary or y in a_dictionary
a_dictionary.has_key(x or y) (x or y) in a_dictionary
a_dictionary.has_key(x + y) (x + y) in a_dictionary
x + a_dictionary.has_key(y) x + (y in a_dictionary)

1, the simplest form. 2, the priority of the operator or is less than that of the operator in, so there is no need to add parentheses here. On the other hand, for the same reason, the priority of or is lower than in, and parentheses need to be added here. Note: the code here is completely different from the previous line. Python first interprets x or y, and then returns x (if x is true in the context of the boolean) or y. Python then checks whether this result is a key in a_dictionary. 4, the priority of the operator in is lower than the operator +, so this form in the code does not technically need brackets, but 2to3 is added. 5 ∞ This form must have parentheses because in has a lower priority than +∞.

  • Method of returning a dictionary class to a list

In Python 2, the return values of many dictionary methods are lists. Among the most commonly used methods are keys, items, and values. In Python 3, the return values of all of the above methods are changed to a dynamic view. In some contextual environments, this change has no effect.

Notes Python 2 Python 3
a_dictionary.keys() list(a_dictionary.keys())
a_dictionary.items() list(a_dictionary.items())
a_dictionary.iterkeys() iter(a_dictionary.keys())
[i for iin a_dictionary.iterkeys()] [i for iin a_dictionary.keys()]
min(a_dictionary.keys()) no change

1, using the list () function to convert the return value of keys () to a static list, 2to3 may return errors for security reasons. Such code is valid, but it is somewhat less efficient for using views. You should check the code after the conversion to see if it necessarily needs a list, and maybe the view can do the same job. This is another way of looking at the conversion of the 2to3 method to the list. 3, In Python 3 iterkeys are no longer supported. If necessary, use iter to convert the return value of keys to an iterator. The 4, 2to3 method can identify which iterkeys are used in the list parsing and then convert it to the keys in Python 3 method. This is possible because the view is iterative. The return value of the 5, 2to3 method, which also recognizes the keys ((() method, is immediately passed to another function that will traverse the entire sequence, so there is no need to convert the return value of the keys (() to a list first. Instead, the min (()) function is happy to traverse the view. This process works equally well for min ((), max ((), sum ((), tuple ((), setlist ((), sorted ((), any (()) and all (()).

  • Modules that have been renamed or reorganized

From Python 2 to Python 3, some of the modules in the standard library have been renamed. Some of the interrelated modules have also been combined or reorganized to make the association more logical.

  • http is In Python 3, several related HTTP modules are combined into a single package, http.
Notes Python 2 Python 3
import httplib import http.client
import Cookie import http.cookies
import cookielib import http.cookiejar
import BaseHTTPServer <br> import SimpleHTTPServer <br> import CGIHttpServer import http.server

The http.client module implements an underlying library that can be used to request HTTP resources and parse HTTP responses. The http.cookies module provides a Python-like interface to retrieve cookies sent through the HTTP header Set-Cookie The most common browsers store cookies on disk in the form of files, which can be manipulated by the http.cookiejar module. The http.server module implements a basic HTTP server

  • urllib Python 2 has some modules for parsing, encoding, and retrieving URLs, but these modules overlap like mouse clicks. In Python 3, these modules are reorganized into a separate package, urllib.
Notes Python 2 Python 3
import urllib import urllib.request <br> urllib.parse,urllib.error
import urllib2 import urllib.request <br> urllib.error
import urlparse import urllib.parse
import robotparser import urllib.robotparser
from urllib import FancyURLopener <br> from urllib import urlencode from urllib.request import FancyURLopener <br> from urllib.parse import urlencode
from urllib2 import Request <br> from urllib2 import HTTPError from urllib.request import Request <br> from urllib.error import HTTPError

Previously, the urllib module in Python 2 had a variety of functions, including urlopen for data acquisition, and was also useful for splitting URLs into its constituent functions of splittype (), splithost (), and splituser (). In the new urllib package, these functions are organized more logically. 2to3 will modify the calls of these functions to accommodate the new naming scheme. In Python 3, the previous urllib2 module was incorporated into the urllib package. In urllib2, your favorite things will be integrated into the urllib module of Python 3, such as the build_opener () method, the Request object, the HTTPBasicAuthHandler and friends. The urllib.parse module in Python 3 contains all the parse functions of the original Python 2 urlparse module. The urllib.robotparse module parses the robots.txt file. The FancyURLopener class that handles HTTP redirects and other status codes is still valid in the urllib.request module in Python 3. The request object is still valid in urllib.request, but constants like HTTPError have been moved to urllib.error. Did I mention that 2to3 will also rewrite your function calls? For example, if you import urllib modules into your Python 2 code and call the urllib.urlopen function to get data, 2to3 will modify both the import statement and the function call.

Notes Python 2 Python 3
import urllib print urllib.urlopen('http://diveintopython3.org/’).read() import urllib.request, urllib.parse, urllib.error <br> print(urllib.request.urlopen('http://diveintopython3.org/’).read())
  • dbm All DBM clones are now in a separate package, dbm. If you need a specific variant of one, such as GNUDBM, you can import the appropriate module into the dbm package.
Notes Python 2 Python 3
import dbm import dbm.ndbm
import gdbm import dbm.gnu
import dbhash import dbm.bsd
import dumbdbm import dbm.dumb
import anydbm <br> import whichdb import dbm
  • xmlrpc XML-RPC is a lightweight method for executing remote RPC calls over the HTTP protocol. Some implementations of the XML-RPC client and XML-RPC server are now combined into a separate package, xmlrpc.
Notes Python 2 Python 3
import xmlrpclib import xmlrpc.client
import DocXMLRPCServer <br> import SimpleXMLRPCServer import xmlrpc.server
  • Other modules

Notes Python 2 Python 3
try:<br>  import cStringIO as StringIO <br>except ImportError: <br>  import StringIO import io
try:<br>  import cPickle as pickle <br>except ImportError: <br>  import pickle import pickle
import _builtin_ import builtins
import copy_reg import copyreg
import Queue import queue
import SocketServer import socketserver
import ConfigParser import configparser
import repr import reprlib
import commands import subprocess

1, in Python 2, you normally do this by first trying to import cStringIO as a substitute for StringIO, and if it fails, then import StringIO again. Do not do this in Python 3; the io module will help you handle this. It will find the fastest available implementation and then use it automatically. In Python 2, importing the fastest pickle implementation is also a useful method similar to the one above. In Python 3, the pickle module will automatically handle it for you, so don't do it again. The builtins module contains global functions, classes, and constants that are used throughout the Python language. Redefining a function in the builtins module means redefining this global function everywhere. This sounds powerful, but it's also scary. 4, copyreg module adds support for pickle module for user custom types defined in C language. The queue module 5 implements a multi-producer, multi-consumer queue. The socketserver module provides a common base class for implementing various socket servers. 7, the configparser module is used to parse the INI-style profile. The reprlib module reimplements the built-in function repr (), and adds controls for the length of the string representation before it is cut. The subprocess module allows you to create subprocesses, connect to their pipelines, and retrieve their return values.

  • Relative import within the package

A package is a single entity made up of a group of related modules. In Python 2, you can use import foo or from foo import Bar to make mutual references to modules within the same package.2解释器会先在当前目录里搜索foo.pyIn Python 3, the process is slightly different. Python 3 does not first search the current path, it searches directly in the Python path. If you want to import one module in a package into another module in a package, you need to explicitly provide the relative paths of the two modules.

Let's say you have the following package, and you have multiple files in the same directory:

chardet/ | ±-init.py | +--constants.py | +--mbcharsetprober.py | +--universaldetector.py

Now let's assume that universal detector.py needs to import the entire constants.py.,另外还需要导入mbcharsetprober.py的一个类。你会怎样做?

Notes Python 2 Python 3
import constants from .import constants
from mbcharsetprober import MultiByteCharSetProber from .mbcharsetprober import MultiByteCharsetProber

1, when you need to import the entire module from elsewhere in the package, use the new from.import syntax.universaldetector.py) and you want to import the file (((constants.pyIn this example, the two files are in the same directory, so a single hyphen is used. You can also import from the parent directory ((from... import anothermodule) or from the child directory. 2, to import a specific class or function directly from other modules into your module namespace, add the relative path in front of the module you want to import, and remove the last slash. In this example, mbcharsetprober.py and universaldetector.py are in the same directory, so the relative path name is a comma. You can also import from the parent directory ((from... import anothermodule) or from the child directory.

  • Iterator method next ((()

In Python 2, the iterator has a next ((() method to return the next item in the sequence. In Python 3 this works the same, but now there is a new global function next (()) which uses an iterator as an argument.

Notes Python 2 Python 3
anIterator.next() next(anIterator)
a_function_that_returns_an_iterator().next() next(a_function_that_returns_an_iterator())
class A:<br>  def next(self):<br>  pass class A:<br>  def _next_(self):<br>  pass|
class A:<br>  def next(self, x, y):<br>  pass no change
next = 42<br>for an_iterator in a_sequence_of_iterators:<br>  an_iterator.next() next = 42<br>for an_iterator in a_sequence_of_iterators:<br>  an_iterator._next_()

1, the simplest example, you no longer call an iterator's next() method, you now pass the iterator itself as an argument to the global function next() ‒ 2, if you have a return value that is a function of the iterator, call this function and pass the result as a parameter to the next ((() function. 3rd, if you assume your own class and then use it as an iterator, in Python 3 you can do that by defining special methods.next_(This is what I'm going to do. 4, if the class you define just has a next (((), it uses one or more arguments, 2to3 will not move it when executed. This class cannot be used as an iterator because its next ((() method has arguments. 5, this one is a bit complicated. If you happen to have a local variable called next, in Python 3 its priority will be higher than the global function next (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((next_() to get the next element in the sequence. Or, you can rewrite the code so that the name of the local variable is not next, but 2to3 won't do that for you.

  • Global function filter (()

In Python 2, the filter() method returns a list, which is obtained by detecting each item in the sequence by a function that returns a value of True or False. In Python 3, the filter() function returns an iterator, no longer a list.

Notes Python 2 Python 3
filter(a_function, a_sequence) list(filter(a_function, a_sequence))
list(filter(a_function, a_sequence)) no change
filter(None, a_sequence) [i for iin a_sequence if i]
for i in filter(None, a_sequence): no change
[i for iin filter(a_function, a_sequence)] no change

In the simplest case, 2to3 will use a list () function to wrap the filter () and the list () function will traverse its parameters and return a list. However, if the filter call has been wrapped by the list, 2to3 will not process it, since it is irrelevant whether the filter return is an iterator. 3, to handle a special syntax such as filter (None,...) 2to3 converts this call from syntactically equivalent to list parsing. 4, since the for loop runs through the entire sequence, no further modifications are necessary. 5, as above, no modification is required, because the list parses across the entire sequence, and even if the filter returns an iterator, it will still work as normal as the previous filter returns the list.

  • The global function map ((()

As with the filter))) change, the map))) function now returns an iterator.

Notes Python 2 Python 3
map(a_function,‘PapayaWhip’) list(map(a_function,‘PapayaWhip’))
map(None,‘PapayaWhip’) list(‘PapayaWhip’)
map(lambda x: x+1,range(42)) [x+1for x in range(42)]
for i in map(a_function, a_sequence): no change
[i for iin map(a_function,a_sequence)] no change

1, similar to filtering (), in the simplest case, 2to3 uses a list function to wrap the map () call. 2、 for special map ((None,...) syntax, similar to filter ((None,...) 2to3 converts it to an equivalent call using list ((( 3, if the first parameter of map ((() is a lambda function, 2to3 converts it to a list parse in equivalence. 4, no change is required for for loops that run through the entire sequence. 5, again, no modification is needed here, because the list parses across the entire sequence, and it works fine even if the return value of map ((() is an iterator instead of a list.

  • The global function reduce (((

In Python 3, the reduce () function has been removed from the global namespace and is now placed in the fucntools module.

Notes Python 2 Python 3
reduce(a, b, c) from functools import reduce reduce(a, b, c)
  • The global function applies

Python 2 has a global function called apply (), which uses a function f and a list [a, b, c] as arguments, returning a value of f (a, b, c). You can also do the same thing by directly calling the function and passing an asterisk (**) to it before the list. In Python 3 the function apply (**) no longer exists; asterisk notation must be used.

Notes Python 2 Python 3
apply(a_function, a_list_of_args) a_function(*a_list_of_args)
apply(a_function, a_list_of_args, a_dictionary_of_named_args) a_function(*a_list_of_args,**a_dictionary_of_named_args)
apply(a_function, a_list_of_args+ z) a_function(*a_list_of_args+ z)
apply(aModule.a_function, a_list_of_args) aModule.a_function(*a_list_of_args)

1, in its simplest form, can be called by adding an asterisk before the list of arguments (like [a, b, c]). This is equivalent to the apply function in Python 2. 2, In Python 2, the apply function can actually have 3 parameters: a function, a list of parameters, and a dictionary of named arguments. In Python 3, you can add an asterisk before the list of parameters.), adding two asterisks ((**) before the dictionary naming parameter to achieve the same effect. 3, the operator + is used here as a function of the linked list and has higher priority than the operator, so there is no need to add extra brackets around a_list_of_args + z. 4, 2 to 3 scripts are smart enough to convert complex apply () calls, including calls to import functions in modules.

  • The global function intern (((

In Python 2, you can limit the function intern to a string to achieve performance optimization. In Python 3, the function intern is moved to the sys module.

Notes Python 2 Python 3
intern(aString) sys.intern(aString)
  • The exec statement

Just as the print statement becomes a function in Python 3, the exec statement is like this. The.exec () function uses a string containing arbitrary Python code as an argument, and then executes it like an execution statement or expression..exec () is similar toeval () but is more powerful and more sophisticated.

Notes Python 2 Python 3
exec codeString exec(codeString)
exec codeString in a_global_namespace exec(codeString, a_global_namespace)
exec codeString in a_global_namespace, a_local_namespace exec(codeString, a_global_namespace,a_local_namespace)

1, in its simplest form, because exec ((() is now a function, not a statement, 2to3 encloses this string-like code with parentheses. 2, the exec statement in Python 2 can specify a namespace, and the code will execute in this private space made up of global objects. Python 3 also has this feature; you only need to pass this namespace as the second parameter to the exec function. More amazingly, the exec statement in Python 2 can also specify a local namespace (e.g. a variable declared in a function). In Python 3, the exec function also has this function.

  • The execfile statement

Like the previous exec statement, the execfile statement in Python 2 can also be executed using strings just like the Python code; unlike the exec using strings and the execfile using files. In Python 3, the execfile statement has been removed. If you really want to execute Python code in a file (but you don't want to import it), you can do it by opening the file, reading its contents, and then calling the compile) global function (Python interpreter compels the code, and then calls the new exec function).

Notes Python 2 Python 3
execfile(‘a_filename’) exec(compile(open(‘a_filename’).read(),‘a_filename’,‘exec’))
  • repr (with quotation marks)

In Python 2, in order to get a string representation of an arbitrary object, there is a way to wrap the object in counter-citations (e.g.xThe special syntax of ∈ R. In Python 3, this capability still exists, but you can no longer use anti-quotes to get this string represented. You need to use the global function repr ().

Notes Python 2 Python 3
`x` repr(x)
`‘PapayaWhip’ + `2`` repr(‘PapayaWhip’+ repr(2))

1, remember, x can be anything, a class, a function, a module, a basic data type, etc. The repr function can use any type of parameter. 2, in Python 2, counter-quotes can be nested, resulting in this puzzling (but effective) expression. 2to3 is smart enough to convert this nested call to the repr function.

  • Try...except phrase

The syntax for capturing anomalies may have changed slightly from Python 2 to Python 3.

Notes Python 2 Python 3
try:<br>  import mymodule<br>except ImportError, e<br>  pass try:<br>  import mymodule<br>except ImportError as e:<br>  pass
try:<br>  import mymodule<br>except (RuntimeError, ImportError), e<br>  pass try:<br>  import mymodule<br>except (RuntimeError, ImportError) as e:<br>  pass
try:<br>  import mymodule<br>except ImportError:<br>  pass no change
try:<br>  import mymodule<br>except:<br>  pass no change

1, as opposed to Python 2 where commas are added after exception types, Python 3 uses a new keyword, as. The keyword as can also be used to capture several types of anomalies at once. If you catch an exception but don't want to access the exception object itself, the syntax of Python 2 and Python 3 is the same. Similarly, if you use a fallback method to capture all exceptions, the syntax of Python 2 and Python 3 is the same. 5, you should definitely not use this method (see fallback above) when importing modules (or most other situations); otherwise, the program may capture an exception such as Keyboard Interrupt (if the user presses Ctrl-C to interrupt the program), which makes debugging more difficult.

  • Raise phrase

In Python 3, there are subtle changes in the syntax to throw out custom abnormalities.

Notes Python 2 Python 3
raise MyException unchanged
raise MyException,‘error message’ raise MyException(‘error message’)
raise MyException,‘error message’, a_traceback raise MyException(‘errormessage’).with_traceback(a_traceback)
raise ‘error message’ unsupported

1, throwing out an exception that doesn't have a user-defined error message, in its simplest form, the syntax doesn't change. 2, the change is obvious when you want to throw an exception with a user-custom error message. Python 2 separates the exception type from the error message with a comma; Python 3 passes the error message to the exception type as a parameter. 3. Python 2 supports a more complex syntax to throw an exception with user custom trace. In Python 3 you can do the same, but the syntax is completely different. In Python 2, you can throw an exception without an exception class, with only one exception message. In Python 3, this form is no longer supported. 2to3 will warn you that it cannot automatically fix this syntax.

  • Throw method of the generator

In Python 2, the generator has a throw (throw) method. Calling a_generator.throw (throw) throws an exception when the generator is paused, and then returns the next value obtained by the generator function. In Python 3, this function is still available, but with a slightly different syntax.

Notes Python 2 Python 3
a_generator.throw(MyException) no change
a_generator.throw(MyException,‘error message’) a_generator.throw(MyException(‘error message’))
a_generator.throw(‘error message’) unsupported

1, in its simplest form, the generator throws out an exception that does not carry a user-customized error message. In this case, there is no change in syntax from Python 2 to Python 3. 2 If the generator throws out an exception with a user custom error message, you need to pass the error string to the exception class to instantiate it. 3. Python 2 also supports throwing out exceptions with only exception messages. Python 3 does not support this syntax, and 2to3 displays a warning message telling you that you need to manually fix this code.

  • Global function xrange (())

In Python 2, there are two ways to get numbers in a certain range: range (), which returns a list, and range (), which returns an iterator. In Python 3, range (), which returns an iterator, xrange (), which no longer exists.

Notes Python 2 Python 3
xrange(10) range(10)
a_list = range(10) a_list = list(range(10))
[i for iin xrange(10)] [i for iin range(10)]
for i in range(10): no change
sum(range(10)) no change

1, in the simplest case, 2to3 will simply convert xrange (()) to range (()). 2, if your Python 2 code uses range ((), 2to3 doesn't know if you need a list, or if an iterator works too. As a precaution, 2to3 may report an error, and then use list (() to force the return value of range (() to be converted to the list type. 3, if there is an xrange () function in the list parse, there is no need to convert its return value to a list, as list parse is equally valid for iterators. 4, similarly, the for loop also works on the iterator, so nothing changes here either. 5, the function sum ((() can work on an iterator, so 2to3 is also not modified here. Just like the dictionary method that returns a value as a view ((view) instead of a list, this also applies to min ((), max ((), sum ((), list ((), tuple ((), set ((), sorted ((), any ((), all (()).

  • Global functions raw_input (()) and input (())

Python 2 has two global functions that are used in the command line to request user input. The first is called input, which waits for the user to enter a Python expression and then returns the result. The second is called raw_input, which returns what the user enters. This is very confusing for beginners, and is widely seen as a hack of the Python language.

Notes Python 2 Python 3
raw_input() input()
raw_input(‘prompt’) input(‘prompt’)
input() eval(input())

In the simplest form, raw_input ((() is replaced by input ((()). In Python 2, the raw_input () function can specify a prompt as a parameter. In Python 3, this function is reserved. If you really want to ask the user to enter a Python expression, the result can be calculated by calling the input function and passing the return value to eval.

  • Function property func_*

In Python 2, the code in the function can access the special properties of the function itself. In Python 3, these special properties are renamed for consistency.

Notes Python 2 Python 3
a_function.func_name a_function._name_
a_function.func_doc a_function._doc_
a_function.func_defaults a_function._defaults_
a_function.func_dict a_function._dict_
a_function.func_closure a_function._closure_
a_function.func_globals a_function._globals_
a_function.func_code a_function._code_

1,__name__ attribute ((original func_name) contains the name of the function. 2,__doc__ attribute ((originalfuncdoc) contains the document string ((docstring) that you defined in the function source code 3,__defaults__ attribute ((originalfunc_defaults) is an element set that stores the default value of the parameter. 4,__dict__ attribute (original function_dict) is a namespace that supports arbitrary function properties. The __closure__ property (originally func_closure) is a subset of a cell object that contains the binding of a function to a free variable. The ___globals__ attribute (originally function_globals) is a reference to a module-wide namespace in which the function itself is defined. 7,__code__ attribute (original function_code) is a code object that represents a compiled function body.

  • I/O method xreadlines

In Python 2, the file object has an xreadlines () method, which returns an iterator, one line at a time, to read the file. This is especially useful in the for loop. In fact, later versions of Python 2 added this feature to the file object itself.

In Python 3, the xreadlines () method is no longer available. 2to3 can solve simple situations, but some edge cases require manual intervention.

Notes Python 2 Python 3
for line in a_file.xreadlines(): for line in a_file:
for line in a_file.xreadlines(5): no change (broken)

1, if you previously called xreadlines without arguments ((), 2to3 will convert it to the file object itself. In Python 3, this converted code can do the same job as before: read a line of the file once, and then execute a for loop loop. 2, if you have previously used an argument (xreadlines) to call xreadlines (), 2to3 cannot complete the conversion from Python 2 to Python 3 for you, your code will fail in this way: AttributeError: _io.TextIOWrapper object has no attribute xreadlines. You can manually convert xreadlines to readlines to make the code work in Python 3.

  • Lambda functions that use elements instead of multiple parameters

In Python 2, you can define an anonymous lambda function, which allows the function to actually accept multiple parameters by specifying the number of elements of the array as arguments. In fact, the Python 2 interpreter unpacks this array into named arguments, which you can then reference in the lambda function. In Python 3, you can still pass a array as an argument to the lambda function, but the Python interpreter does not parse it into named arguments.

Notes Python 2 Python 3
lambda (x,): x+ f(x) lambda x1: x1[0]+f(x1[0])
lambda (x, y): x+f(y) lambda x_y: x_y[0]+f(x_y[1])
lambda (x,(y,z)): x+ y+ z lambda x_y_z: x_y_z[0]+x_y_z[1][0]+ x_y_z[1][1]
lambda x, y, z: x+y + z unchanged

1, if you have defined a lambda function, it uses the element set containing an element as its argument, in Python 3 it is converted to a lambda function containing a reference to x1[0]; x1 is a 2to3 script that is automatically generated based on the naming parameters in the original element set. 2, the lambda function is converted to x_y using the two-element subset ((x, y) as the argument, which has two position parameters, x_y[0] and x_y[1]). 3, 2to3 scripts can even handle lambda functions that use nested naming parameters as parameters. The resulting code is a bit hard to read, but it works the same in Python 3 as the original code in Python 2. 4, you can define a lambda function that uses multiple parameters. If no parentheses are enclosed around the parameter, Python 2 treats it as a lambda function that contains multiple parameters; in this lambda function body, you refer to these parameters by name, as you do in other types of functions. This syntax is still valid in Python 3.

  • Properties of special methods

In Python 2, class methods can access the class object that defines them, as well as the method object itself. Im_self is the instance object of the class; im_func is the function object, and im_class is the class itself. In Python 3, these properties are renamed to follow the naming convention for other properties.

Notes Python 2 Python 3
aClassInstance.aClassMethod.im_func aClassInstance.aClassMethod._func_
aClassInstance.aClassMethod.im_self aClassInstance.aClassMethod._self_
aClassInstance.aClassMethod.im_class aClassInstance.aClassMethod._self_._class_
  • __nonzero__ special method

In Python 2, you can create your own classes and make them usable in a boolean context. For example, you can instantiate this class and use this instance object in an if statement.nonzero_() method, which returns a value of True or False, is called when the instance object is in the context of a boolean. In Python 3, you can still perform the same function, but the name of this particular method is changed.bool_()。

Notes Python 2 Python 3
class A:<br>  def _nonzero_(self):<br>  pass class A:<br>  def _bool_(self):<br>  pass
class A:<br>  def _nonzero_(self, x, y):<br>  pass no change

1, when using a class object in the context of Boolean, Python 3 calls_bool_(), not _nonzero_(This is my blog) But if you have a definition that uses two parameters.nonzero_The 2to3 script assumes that the method you defined has other uses and therefore does not modify the code.

  • Eight-digit type

Between Python 2 and Python 3, there is a slight change in the syntax of defining octal numbers.

Notes Python 2 Python 3
x = 0755 x = 0o755
  • sys.maxint

The sys.maxint constant is no longer accurate as long and integer are integrated; however, this value is still useful for platform-specific detection capabilities, so it is retained by Python 3 and renamed sys.maxsize.

Notes Python 2 Python 3
from sys importmaxint from sys importmaxsize
a_function(sys.maxint) a_function(sys.maxsize)

1, maxint becomes maxsize. 2, all sys.maxint is changed to sys.maxsize.

  • Global function callable

In Python 2, you can use the global function callable to check if an object is callable. In Python 3, this global function is cancelled. Special methods can be used to check if an object is callable.call_The existence of ().

Notes Python 2 Python 3
callable(anything) hasattr(anything,’_call_’)
  • The global function ((zip)

In Python 2, the global function zip ((() can use any number of sequences as arguments, and it returns a list made up of elements. The first element contains the first element of each sequence; the second element contains the second element of each sequence; and so on. In Python 3, zip ((() returns an iterator, not a list.

Notes Python 2 Python 3
zip(a, b, c) list(zip(a, b, c))
d.join(zip(a, b, c)) no change

In the simplest form, you can restore the function to the previous function of the zip function by calling the return value of the list ((() function to wrap zip (((), the list ((() function will traverse the iterator that returned this zip ((() function, and then return the list representation of the result. In contextual environments where all elements of the sequence are already traversed (e.g. here the call to the join method) the zip () returning iterator can function normally. The 2to3 script detects these situations and does not make changes to your code.

  • StandardError is missing

In Python 2, StandardError is the base class for all other built-in anomalies except StopIteration, GeneratorExit, KeyboardInterrupt, and SystemExit. In Python 3, StandardError has been removed; Exception is used instead.

Notes Python 2 Python 3
x =StandardError() x =Exception()
x =StandardError(a, b, c) x =Exception(a, b, c)
  • Constants in the types module

The types module has a variety of constants that help you determine the type of an object. In Python 2, it contains constants that represent all basic data types, such as dict and int. In Python 3, these constants have been removed.

Notes Python 2 Python 3
types.UnicodeType str
types.StringType bytes
types.DictType dict
types.IntType int
types.LongType int
types.ListType list
types.NoneType type(None)
types.BooleanType bool
types.BufferType memoryview
types.ClassType type
types.ComplexType complex
types.EllipsisType type(Ellipsis)
types.FloatType float
types.ObjectType object
types.NotImplementedType type(NotImplemented)
types.SliceType slice
types.TupleType tuple
types.TypeType type
types.XRangeType range

Types.StringType is mapped to bytes, not str, because the string string string in Python 2 is actually a sequence of bytes encoded with some kind of character.

  • Global function in instance (())

The isinstance function checks whether an object is an instance of a particular class or type. In Python 2, you can pass an instance to an instance that is made up of types, and if the object is any type in the instance, the function returns True. In Python 3, you can still do this, but it is not recommended to pass a type twice as an argument.

Notes Python 2 Python 3
isinstance(x,(int,float,int)) isinstance(x,(int,float))
  • basestring data type

Python 2 has two types of strings: Unicode-encoded strings and non-Unicode-encoded strings. However, there is another type, basestring. It is an abstract data type that is a superclass of str and unicode types. It cannot be directly invoked or instantiated, but you can use it as an instance parameter to detect whether an object is a Unicode string or a non-Unicode string.

Notes Python 2 Python 3
isinstance(x, basestring) isinstance(x, str)
  • The itertools module

Python 2.3 introduces the itertools module, which defines variants (variants) of the global functions zip (), map (), and filter (), which are returned as iterators rather than lists. In Python 3, these variants in these itertools are eliminated because the return type of these global functions is inherently iterator.

Notes Python 2 Python 3
itertools.izip(a, b) zip(a, b)
itertools.imap(a, b) map(a, b)
itertools.ifilter(a, b) filter(a, b)
from itertools import imap, izip, foo from itertools import foo

1, using the global zip ((() function instead of itertools.izip ((()). 2、 use map ((() instead of itertools.imap ((() ー 3,itertools.ifilter ((() became filter ((() ▽ The itertools module still exists in Python 3, but it no longer contains functions that have been moved to the global namespace. The 2to3 script is intelligent enough to remove import statements that are no longer useful, while maintaining the integrity of other import statements.

  • sys.exc_type, sys.exc_value, sys.exc_traceback

There are three variables that you can access in the sys module when dealing with exceptions: sys.exc_type, sys.exc_value, sys.exc_traceback. These actually existed in the Python 1 era. Starting with Python 1.5, it is no longer recommended to use these three variables due to the new release of sys.exc_info, which is a subset containing all three elements above.

Notes Python 2 Python 3
sys.exc_type sys.exc_info()[0]
sys.exc_value sys.exc_info()[1]
sys.exc_traceback sys.exc_info()[2]
  • Parsing the list of elements

In Python 2, if you need to write a list parse that traverses an array, you don't need to add parentheses around the array value. In Python 3, these parentheses are required.

Notes Python 2 Python 3
[i for iin 1,2] [i for iin(1,2)]
  • os.getcwdu (()) function

Python 2 has a function called os.getcwd (), which returns the current working directory as a string (not encoded in Unicode). Since modern file systems can handle directory names that can be encoded by any number of characters, Python 2.3 introduces the os.getcwdu (), which returns the current working directory as a string encoded in Unicode. In Python 3, since there is only one string (of the Unicode type), you only need os.getcwd ().

Notes Python 2 Python 3
os.getcwdu() os.getcwd()
  • Metaclass

In Python 2, you can create metaclasses by defining metaclass parameters in the class declaration, or by defining a special class-level __metaclass__ attribute. In Python 3, the __metaclass__ attribute has been removed.

Notes Python 2 Python 3
class C(metaclass=PapayaMeta):<br>  pass unchanged
class Whip:<br>  _metaclass_ = PapayaMeta class Whip(metaclass=PapayaMeta):<br>  pass
class C(Whipper, Beater):<br>  _metaclass_ = PapayaMeta class C(Whipper,Beater,metaclass=PapayaMeta):<br>  pass

1, when declaring a class, declare the metaclass argument, which is valid in both Python 2 and Python 3, they are the same. 2, in the class definition, declares that the __metaclass__ attribute is valid in Python 2, but no longer valid in Python 3. 3, 2to3 can construct a valid class declaration even if the class inherits from multiple parent classes.

  • About the code style

The fixes listed below are not really fixes; that is, they are just stylistic things about the code, not about the essence of the code. However, Python developers have a vested interest in making the style of the code as consistent as possible. To this end, there is an official manual dedicated to describing the Python style of code.

  • set (() literal value ((literal))

In Python 2, the only way to define a literal set is to call a set. In Python 3, this is still valid, but using a new notation (literal notation): capital brackets is a clearer way. This method works in addition to empty sets, because dictionaries also use capital brackets, so {} represents an empty dictionary, not an empty set.

The 2to3 script does not repair set (() literal values by default. To enable this feature, specify the -f set_literal parameter when calling 2to3 from the command line.

Notes Before After
set([1,2,3]) {1,2,3}
set((1,2,3)) {1,2,3}
set([i for iin a_sequence]) {i for iin a_sequence}
  • The global function buffer ((((explicit)

Python objects implemented in C can export a buffer interface that allows other Python code to read and write to a memory directly. This sounds powerful, but it's equally terrible. In Python 3, buffer was renamed memoryview. The actual modifications are more complex, but you can almost ignore these differences.

The 2to3 script does not repair the buffer ((() function by default. To enable this function, specify the -f buffer parameter when calling 2to3 from the command line.

Notes Before After
x =buffer(y) x =memoryview(y)
  • The space around the comma is obvious.

Although Python has strict requirements for spaces for indenting and outdenting, Python is free to use spaces in other ways. In lists, arrays, collections, and dictionaries, spaces can appear before or after commas, which is not a bad thing. However, the Python Code Style Manual states that there can be no spaces before commas and a space after commas.

By default, the 2to3 script does not repair spaces around commas. To enable this feature, specify the -f wscomma argument when calling 2to3 from the command line.

Notes Before After
a ,b a, b
{a :b} {a: b}
  • Common idioms (obvious)

Many conventions have been established in the Python community. Some are such as while 1: loop, which dates back to Python 1. (Python didn't have a true bull type until Python 2.3, so developers used 1 and 0 alternatives before.) Contemporary Python programmers should exercise their brains to use modern versions of these conventions.

The 2to3 script does not fix these conventions by default. To enable this feature, specify the -f idioms parameter when calling 2to3 from the command line.

Notes Before After
while 1:<br>  do_stuff() while True:<br>  do_stuff()
type(x) == T isinstance(x, T)
type(x) is T isinstance(x, T)
a_list = list(a_sequence) a_list = sorted(a_sequence)
a_list.sort() do_stuff(a_list)
do_stuff(a_list)

Translated fromThe CSDN blog

How to convert Python2 code to Python3 code

This article is about how to convert Python 2.x code to Python 3.x code. How to convert Python 2.x code to Python 3.x code

  • 1.自己手动转换

This doesn't need to be said much if it only involves a few functions, such as print etc.

If you want to change your code, you can do it yourself.

  • 2.利用Python内置(Python脚本)工具,帮你自动转换

The Python 2.x version, like Python 2.7.2 that I installed, comes with some useful tools after it is downloaded and installed on windows.

其中一个叫做2to3.pyThis is the code that you can use to convert Python 2.x to Python 3.x.

It is located at: Root directory of Python installations\Python27\Tools\Scripts\2to3.py

如何利用2to3.py, implementing the conversion of Python 2.x code to Python 3.x code bars For example, I have a Python 2.x Python script in my hand:

D:\tmp\tmp_dev_root\python\python2_to_python3\34563264_data_from_site.py

Now, I want to convert it to Python 3.x code.

You can open the cmd in windows, locate it under the script you want to convert, and run it.

D:\tmp\WordPress\DevRoot\Python27\Tools\Scripts\2to3.py -w 34563264_data_from_site.py

If the conversion is successful, the corresponding execution results are:

D:\tmp\tmp_dev_root\python\python2_to_python3>D:\tmp\WordPress\DevRoot\Python27\Tools\Scripts\2to3.py -w 34563264_data_from_site.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored 34563264_data_from_site.py
--- 34563264_data_from_site.py  (original)
+++ 34563264_data_from_site.py  (refactored)
@@ -18,7 +18,7 @@
 import time;
 import codecs;
 import logging;
-import urllib;
+import urllib.request, urllib.parse, urllib.error;
 from datetime import datetime,timedelta;
 from optparse import OptionParser;
 from string import Template,replace;
@@ -90,7 +90,7 @@
         foundPhone = eachItemSoup.find(attrs={"class":"phone"});
         logging.debug("foundPhone=%s", foundPhone);
         if(foundPhone):
-            foundPhoneUni = unicode(foundPhone);
+            foundPhoneUni = str(foundPhone);
             logging.debug("foundPhoneUni=%s", foundPhoneUni);
             # case 1:
             #<p class="phone"><strong>phone:</strong>&nbsp;800.206.7886<br />
@@ -122,7 +122,7 @@
         foundWeb = eachItemSoup.find(attrs={"class":"web"});
         logging.debug("foundWeb=%s", foundWeb);
         if(foundWeb):
-            foundWebUni = unicode(foundWeb);
+            foundWebUni = str(foundWeb);
             logging.debug("foundWebUni=%s", foundWebUni);
 
             # <p class="web"><strong>e-mail:</strong>&nbsp;<a href="#">sales@cinesysinc.com</a><br />
@@ -151,7 +151,7 @@
         foundAddr = eachItemSoup.find(attrs={"class":"addr"});
         logging.debug("foundAddr=%s", foundAddr);
         if(foundAddr):
-            foundAddrUni = unicode(foundAddr);
+            foundAddrUni = str(foundAddr);
 
             # <p class="addr">
                 # <strong>address:</strong>&nbsp;740 SW 21st Ave, Suite #310<br />
RefactoringTool: Files that were modified:
RefactoringTool: 34563264_data_from_site.py

At this point, you can see the original 345636264_data_from_site.py, which has become Python 3.x.


More

FangBeiIs there a Python 2 for botvs?

Inventors quantify - small dreamsThe BotVS retrieval server uses Python version 2.7, which supports both Python 2 and Python 3 for the BotVS platform.