Getting started with Python LanguageList comprehensionsFilterListFunctionsDecoratorsMath ModuleLoopsRandom moduleComparisonsImporting modulesSorting, Minimum and MaximumOperator moduleVariable Scope and BindingBasic Input and OutputFiles & Folders I/OJSON ModuleString MethodsMetaclassesIndexing and SlicingGeneratorsSimple Mathematical OperatorsReduceMap FunctionExponentiationSearchingDictionaryClassesCountingManipulating XMLDate and TimeSetCollections moduleParallel computationMultithreadingWriting extensionsUnit TestingRegular Expressions (Regex)Bitwise OperatorsIncompatibilities moving from Python 2 to Python 3Virtual environmentsCopying dataTupleContext Managers (“with” Statement)Hidden FeaturesEnumString FormattingConditionalsComplex mathUnicode and bytesThe __name__ special variableChecking Path Existence and PermissionsPython NetworkingAsyncio ModuleThe Print Functionos.pathCreating Python packagesParsing Command Line argumentsHTML ParsingSubprocess Librarysetup.pyList slicing (selecting parts of lists)SocketsItertools ModuleRecursionBoolean OperatorsThe dis moduleType Hintspip: PyPI Package ManagerThe locale ModuleExceptionsWeb scraping with PythonDeque ModuleDistributionProperty ObjectsOverloadingDebuggingReading and Writing CSVDynamic code execution with `exec` and `eval`PyInstaller - Distributing Python CodeIterables and IteratorsData Visualization with PythonThe Interpreter (Command Line Console)*args and **kwargsFunctools ModuleGarbage CollectionIndentationSecurity and CryptographyPickle data serialisationurllibBinary DataPython and ExcelIdiomsMethod OverridingDifference between Module and PackageData SerializationPython concurrencyIntroduction to RabbitMQ using AMQPStormPostgreSQLDescriptorCommon PitfallsMultiprocessingtempfile NamedTemporaryFileWorking with ZIP archivesStackProfilingUser-Defined MethodsWorking around the Global Interpreter Lock (GIL)DeploymentLoggingProcesses and ThreadsThe os ModuleComments and DocumentationDatabase AccessPython HTTP ServerAlternatives to switch statement from other languagesList destructuring (aka packing and unpacking)Accessing Python source code and bytecodeMixinsAttribute AccessArcPyPython Anti-PatternsPlugin and Extension ClassesWebsocketsImmutable datatypes(int, float, str, tuple and frozensets)String representations of class instances: __str__ and __repr__ methodsArraysOperator PrecedencePolymorphismNon-official Python implementationsList ComprehensionsWeb Server Gateway Interface (WSGI)2to3 toolAbstract syntax treeAbstract Base Classes (abc)UnicodeSecure Shell Connection in PythonPython Serial Communication (pyserial)Neo4j and Cypher using Py2NeoBasic Curses with PythonPerformance optimizationTemplates in pythonPillowThe pass statementLinked List Nodepy.testDate FormattingHeapqtkinterCLI subcommands with precise help outputDefining functions with list argumentsSqlite3 ModulePython PersistenceTurtle GraphicsConnecting Python to SQL ServerDesign PatternsMultidimensional arraysAudioPygletQueue ModuleijsonWebbrowser ModuleThe base64 ModuleFlaskgroupby()Sockets And Message Encryption/Decryption Between Client and ServerpygameInput, Subset and Output External Data Files using Pandashashlibgetting start with GZipDjangoctypesCreating a Windows service using PythonPython Server Sent EventsMutable vs Immutable (and Hashable) in PythonPython speed of programconfigparserLinked listsCommonwealth ExceptionsOptical Character RecognitionPython Data TypesPartial functionspyautogui modulegraph-toolUnzipping FilesFunctional Programming in PythonPython Virtual Environment - virtualenvsysvirtual environment with virtualenvwrapperCreate virtual environment with virtualenvwrapper in windowsPython Requests PostPlotting with MatplotlibPython Lex-YaccChemPy - python packagepyaudioshelveUsage of "pip" module: PyPI Package ManagerIoT Programming with Python and Raspberry PICode blocks, execution frames, and namespaceskivy - Cross-platform Python Framework for NUI DevelopmentCall Python from C#Similarities in syntax, Differences in meaning: Python vs. JavaScriptWriting to CSV from String or ListRaise Custom Errors / ExceptionsUsing loops within functionsPandas Transform: Preform operations on groups and concatenate the results

2to3 tool

Other topics

Remarks:

The 2to3 tool is an python program which is used to convert the code written in Python 2.x to Python 3.x code. The tool reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code.

The 2to3 tool is available in the standard library as lib2to3 which contains a rich set of fixers that will handle almost all code. Since lib2to3 is a generic library, it is possible to write your own fixers for 2to3.

Basic Usage

Consider the following Python2.x code. Save the file as example.py

Python 2.x2.0
def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

In the above file, there are several incompatible lines. The raw_input() method has been replaced with input() in Python 3.x and print is no longer a statement, but a function. This code can be converted to Python 3.x code using the 2to3 tool.

Unix

$ 2to3 example.py

Windows

> path/to/2to3.py example.py

Running the above code will output the differences against the original source file as shown below.

RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored example.py
--- example.py    (original)
+++ example.py    (refactored)
@@ -1,5 +1,5 @@
 def greet(name):
-    print "Hello, {0}!".format(name)
-print "What's your name?"
-name = raw_input()
+    print("Hello, {0}!".format(name))
+print("What's your name?")
+name = input()
 greet(name)
RefactoringTool: Files that need to be modified:
RefactoringTool: example.py

The modifications can be written back to the source file using the -w flag. A backup of the original file called example.py.bak is created, unless the -n flag is given.

Unix

$ 2to3 -w example.py

Windows

> path/to/2to3.py -w example.py

Now the example.py file has been converted from Python 2.x to Python 3.x code.

Once finished, example.py will contain the following valid Python3.x code:

Python 3.x3.0
def greet(name):
    print("Hello, {0}!".format(name))
print("What's your name?")
name = input()
greet(name)

Syntax:

  • $ 2to3 [-options] path/to/file.py

Parameters:

ParameterDescription
filename / directory_name2to3 accepts a list of files or directories which is to be transformed as its argument. The directories are recursively traversed for Python sources.
OptionOption Description
-f FIX, --fix=FIXSpecify transformations to be applied; default: all. List available transformations with --list-fixes
-j PROCESSES, --processes=PROCESSESRun 2to3 concurrently
-x NOFIX, --nofix=NOFIXExclude a transformation
-l, --list-fixesList available transformations
-p, --print-functionChange the grammar so that print() is considered a function
-v, --verboseMore verbose output
--no-diffsDo not output diffs of the refactoring
-wWrite back modified files
-n, --nobackupsDo not create backups of modified files
-o OUTPUT_DIR, --output-dir=OUTPUT_DIRPlace output files in this directory instead of overwriting input files. Requires the -n flag, as backup files are unnecessary when the input files are not modified.
-W, --write-unchanged-filesWrite output files even is no changes were required. Useful with -o so that a complete source tree is translated and copied. Implies -w.
--add-suffix=ADD_SUFFIXSpecify a string to be appended to all output filenames. Requires -n if non-empty. Ex.: --add-suffix='3' will generate .py3 files.

Contributors

Topic Id: 5320

Example Ids: 18927

This site is not affiliated with any of the contributors.