Docsity

from - future - import - python, Notas de estudo de Engenharia Elétrica

Pré-visualização parcial do texto

Baixe from - future - import - python e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

From future import Python

Picking a Python

Version: A Manifesto

David Mertz

David Mertz

Picking a Python Version:

A Manifesto

From future import Python

Table of Contents

  • Python Versions.
  • The (Small) Break
  • Moving Forward
  • Unix-Like Systems
  • Python 3 Uptake
  • Is It Enough?
  • Porting.
  • 2to3
  • six.py
  • Python-Future
  • Library Support
  • Advantages of Python 3.x.
  • Unicode Handling
  • The Greatly Improved Email and Mailbox Modules
  • The concurrent.futures Module
  • Coroutine Support and yield from
  • The asyncio Module
  • Views and Iterators Everywhere
  • Function Annotations
  • Other Things
  • Other Implementations.
  • PyPy
  • PyPy-STM
  • Jython
  • IronPython
  • Cython
  • Numba
  • Python Distributions.
  • Continuum Analytics’ Anaconda
  • Enthought’s Canopy
  • ActiveState’s ActivePython

Figure 1-1. Guido van Rossum’s PyCon 2014 keynote address (photo credit: David Lesieur 2014, CC-BY-SA)

Python developers have numerous versions and implementations to choose from. Many of us still use Python 2.x and CPython—and that is still often a good choice—but there are many situations in which making a different choice makes sense.

Python 3.x, and in particular the Python 3.5 version coming out soon, offer numerous advantages over the Python 2.x series. New development should typically be done using Python 3.x, and although the 2020 end-of-life for Python 2.x isn’t all that close, it is good for companies and projects to start think of porting plans for existing code.

The (Small) Break

With the introduction of the so-called “Python 3000” version, which was released after long deliberation as Python 3.0 and subsequent Python 3.x versions, the designers deliberately allowed small lan‐ guage incompatibilities to be introduced in the new language series. A full discussion of this is contained in a Python Enhancement Pro‐ posal: PEP 3000 - Python 3000. Even during the Python 2.x to 3.x series transition, the philosophy of Python insisted on making

2 | Python Versions

1 Fred Brooks, The Mythical Man-Month. Addison-Wesley, 1975.

changes as incremental as possible. Unlike in the histories of some other programming language evolutions, Python 3.x was never meant as a blue-sky project, and avoids the pitfalls of a “second- system effect.”^1 Python 3.x aims to improve a familiar Python 2.x language rather than to create a new or fundamentally different lan‐ guage.

While there is a significant subset of Python code that is able to be version-neutral “out of the box,” most existing codebases require a small degree of rewriting and/or use of compatibility tools and libra‐ ries to move from Python 2.x to Python 3.x. Real-world code using the most natural idioms in Python 2.x usually does various things that are not quite compatible with Python 3.x, and the code that is version-neutral must be written in a careful way to achieve that. That is to say, if you wrote some module or script 10 years ago, it is quite unlikely is will “just run” in Python 3.x with no changes.

Moving Forward

The bottom line is that Python 3.x is a better language than Python 2.x, albeit in a large collection of relatively small ways. But as with any transition—especially one that introduces genuine backward incompatibilities—it takes time to move users to the latest version. To a lesser extent, this is true even within a series: there were (are) certainly some few long-running and stable programs that ran (probably still run) on Python 2.1—or even on Python 1.5.2—where simply keeping the platform consistent was easier than testing a transition. “If it ain’t broke, don’t fix it!”

However, going forward, new projects should be written for Python 3.x, and actively maintained old projects should transition between versions or plan on doing so at the earliest opportunity. Still, even after the 2020 end-of-life, executables already running will not sud‐ denly stop doing so (albeit, changes in underlying operatings sys‐ tems or in supporting hardware might require new versions, but much the same upgrade issue exists for OSes as for programming languages, and letting old systems “just run” is the same option in both cases).

One issue to consider when moving to the latest version of Python is simply what version of the language comes preinstalled with your

Moving Forward | 3

  • Eventually, python will refer to the same target as python3.
  • Python 2.x-only scripts should either be updated to be source compatible with Python 3.x or use python2 in the shebang line.

While some currently shipping systems like Apple OS X only ship with Python 2.x, others like Arch Linux™ ship with python aliased to python3 already. In (almost) all cases, explicitly specifying python or python3 in the shebang line will resolve any ambiguity.

Python 3 on Fedora and Red Hat

Major Linux distributions generally follow the recommendation of PEP 394, and furthermore, are moving at a consistent pace towards general internal use of Python 3.x. For example, Fedora’s wiki docu‐ ments this effort:

The main goal is switching to Python 3 as a default, in which state:

  • DNF is the default package manager instead of Yum, which only works with Python 2
  • Python 3 is the only Python implementation in the minimal buildroot
  • Python 3 is the only Python implementation on the LiveCD
  • Anaconda and all of its dependencies run on Python 3
  • cloud-init and all of its dependencies run on Python 3

Python 3 on Ubuntu

Ubuntu is following a similar path vis-à-vis Python versioning as is Fedora (and Red Hat). Ubuntu’s wiki describes their goals:

For both Ubuntu and Debian, we have ongoing project goals to make Python 3 the default, preferred Python version in the distros. This means:

  • Python 3 will be the only Python version installed by default. Python 3 will be the only Python version in any installation media (i.e. image ISOs)
  • Only Python 3 will be allowed on the Ubuntu touch images.
  • All upstream libraries that support Python 3 will have their Python 3 version available in the archive.

Unix-Like Systems | 5

  • All applications that run under Python 3 will use Python 3 by default.
  • All system scripts in the archive will use Python 3.

Ubuntu 14.04 LTS has recently been released. We made great pro‐ gress toward these goals, but we must acknowledge that it is a daunting, multi-cycle process. A top goal for 14.04 was to remove Python 2 from the touch images, and sadly we almost but didn’t quite make it. There were still a few autopilot tests for which the Python 3 ports did not land in time, thus keeping Python 2 autopi‐ lot support on the base touch image. This work is being completed for Utopic and we expect to remove Python 2 from the touch images early in the 14.10 cycle (actually, any day now).

Python 3 Uptake

It is difficult to know with any confidence just how widely used Python 3.x is compared to Python 2.x. Indeed, it is not easy to know how widely used Python is in general, either in absolute terms or compared to other programming languages. For that matter, there are many meanings one could give to “how widely used” to begin with: how many local applications? How many servers? Serving how many clients? How much CPU time used in the process? How important are the various applications? How many lines of code in the version? And so on.

Certainly Python in general is near the top of popular programming languages if one looks at indices like the TIOBE Programming Community Index, the Transparent Language Popularity Index, the PYPL PopularitY of Programming Language, IEEE Spectrum’s 2014 Ranking, or The RedMonk Programming Language Rankings.

Being active in the Python community, and also being a director of the Python Software Foundation, this writer has some access to some rough indicators of Python version usage that while not confi‐ dential, also haven’t been widely published (mostly because of their lack of statistical rigor). But a few points are suggestive.

Downloads from python.org

On the python.org website itself, downloads of 3.x versions started outnumbering downloads of 2.x versions beginning in early 2013. As discussed above, many operating system distributions come with Python versions installed, so those probably do not need to be

6 | Python Versions

tion is overly Panglossian, and the new modules in Python 3.x have only a small effect on the demand and use of third-party libraries and tools. (Figure 1-3 shows PyPI’s navigation screen.)

Figure 1-3. The navigation screen of the Python Package Index

A 2013/2014 Survey

A survey was completed at the beginning of 2014 to gauge relative usage, based on responses from postings on comp.lang.python, python-dev, and hacker news. While still unscientific, the 2.x- vs-3.x-survey might be of interest to readers:

Question Yes No

Have you ever written code in Python 2.x? 97.29% 2.48%

Have you ever written code in Python 3.x? 59.75% 39.83%

Do you currently write more code in Python 2.x than 3.x? 77.08% 21.63%

Do you think Python 3.x was a mistake? 22.36% 75.22%

Do you have dependencies keeping you on Python 2.x? 60.19% 37.75%

Have you ever ported code from Python 2.x to Python 3.x? 32.44% 66.37%

Have you ever written/ported code using 2to3? 16.03% 82.53%

Have you ever written/ported code using 3to2? 1.90% 96.60%

[…] code to run on Python 2.x and Python 3.x unmodified? 30.75% 68.08%

8 | Python Versions

Is It Enough?

There seems to be an ongoing perception in at least parts of the Python community that projects are “stuck” on Python 2.x, whether either widely used libraries or in-house codebases. This perception is mostly false when it comes to widely used third-party libraries: the large majority of the most important FLOSS support libraries have Python 3.x-compatible versions today. Because some of those library versions have been created relatively recently, perceptions of the “ecosystem” not having moved to Python 3.x may simply reflect infrequent review by developers of the overall snapshot of porting statuses (it is a not inconsiderable project to conduct such a review as it applies to one’s own large codebase).

Adoption of Python 3.x was also slowed somewhat by missteps in Python 3.0 that were not fixed until Python 3.1. So there was not a really good and stable Python 3.x version until mid-2009, in truth. For applications that work intensively with text processing, the benchmark version is probably even Python 3.3, because of the improvements in PEP 393 - Flexible String Representation. That release happened in September 2012. The variable-width storage of unicode strings made for a big win in memory allocation and usage:

The memory usage of Python 3.3 is two to three times smaller than Python 3.2, and a little bit better than Python 2.7, on a Django benchmark (see the PEP for details).

More than the details of what improvements arrived on what dates in the history of Python 3.x, what probably feeds many developers’ sense of being “stuck” is not any concrete large conceptual or infra‐ structure problem in porting, but simply the fact that it takes more work to change versions—on a short-term basis—than it does to leave things as they are within a large codebase.

Even adding some minor functionality, bug fix, kludge, or work‐ around to a large, in-house, Python 2.x codebase is less work today than is porting (and more importantly, testing and validating that port) to Python 3.x. The next problem would often have been solved by the port, or at least much easier to address after it is made. But today’s work is done now, and the next problem not addressed until later. In corporations, profits and expenses are accounted for quar‐ terly; and even open source projects are also often constrained by

Is It Enough? | 9

Porting

Several tools are available to somewhat automate porting of code from Python 2.x to Python 3.x. Using any of these will generally require some manual developer attention during the process, but in many cases a fairly small degree of such attention.

There are two approaches to consider when porting code:

  • Is this a one time transition? For in-house code, it is almost cer‐ tainly a better idea to make a clean break and commit to the Python 3.x series (after sufficient testing, code review, etc.). Even FLOSS libraries may want to make the jump as well, per‐ haps maintaining parallel versions for a certain period of time (e.g., a Foolib and Foolib3 might both get updated for a while).
  • Do you want to instead create a version-neutral codebase that will run on both Python 2.x and Python 3.x? It is possible to use compatibility shims to write such code while still fairly elegantly falling back or falling forward with differences in features. How‐ ever, using these shims will probably require writing some code in a manner less than the most idiomatic style for a Python ser‐ ies, at least at times.

Basically, if you want to make a clean break, use the tool 2to3 which comes bundled with recent Python versions, in both series. If you want to create version-neutral code, use the support libraries six or Python-Futures. There was, for a while, a short-lived project called 3to2 to backport code already written for Python 3.x; however, it has not been well maintained, and using it is not recommended.

11

2to

The documentation for 2to3 - Automated Python 2 to 3 code transla‐ tion describes it as follows:

2to3 is a Python program that reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code. The standard library contains a rich set of fixers that will handle almost all code. [The] 2to3 supporting library lib2to3 is, however, a flexible and generic library, so it is possible to write your own fix‐ ers for 2to3. lib2to3 could also be adapted to custom applications in which Python code needs to be edited automatically.

As a little experiment for this paper, I decided to take a look at my long out-of-maintenance library Gnosis_Utils. I do not particularly recommend using any part of this library, since most of the useful things it did have been superceded by newer libraries. For the most part, the library was always a teaching tool, and a way of publishing examples and concepts that I discussed in my long-running column for IBM developerWorks, Charming Python (albeit, I was pleased to hear from many correspondents who used parts of it in real produc‐ tion systems, and to know it was included with some Linux and BSD distributions). In particular, this library stopped being maintained in 2006, and was probably last run by me using Python 2.5.

However, because of its age, it might make a good experiment in porting. In its simplest mode, running 2to3 simply proposes a diff to use in updating files. There are switches to perform the actions automatically, and some others to limit which transformations are performed. Let us look at what the tool might do in default mode:

% 2to3 Gnosis_Utils-1.2.2/gnosis/trigramlib.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 Gnosis_Utils-1.2.2/gnosis/trigram- lib.py --- Gnosis_Utils-1.2.2/gnosis/trigramlib.py (original) +++ Gnosis_Utils-1.2.2/gnosis/trigramlib.py (refactored) @@ -1,6 +1,6 @@ "Support functions for trigram analysis" -from future import generators -import string, cPickle

+import string, pickle

12 | Porting

  • for trigram,(spam,good) in trigrams.items():
  • for trigram,(spam,good) in list(trigrams.items()): ratio = float(spam)/(spam+good) if spam+good >= 10: if ratio < 0.05 or ratio > 0.95: interesting[trigram] = ratio
  • cPickle.dump(interesting, open('interesting- trigrams','wb'), 1)
  • pickle.dump(interesting, open('interesting- trigrams','wb'), 1) return interesting

RefactoringTool: Files that need to be modified: RefactoringTool: Gnosis_Utils-1.2.2/gnosis/trigramlib.py

Everything suggested here will produce valid Python 3.x code, and applying the diff is completely sufficient to do so. But a few of the suggestions are neither idiomatic nor necessary. For example:

  • ident = ''.join(map(chr, range(256)))
  • ident = ''.join(map(chr, list(range(256))))

Since the built-in function range() has become lazy (like xrange() was in Python 2.x), 2to3 conservatively shows us how to create a concrete list. In almost all contexts, lazy is not only acceptable, but even superior in performance (it doesn’t matter for range(256), but it might for range(1000000000)).

On the other hand, some of the suggestions 2to3 makes are actually to change constructs that are compatible with Python 3.x but simply not idiomatic, nor as elegant. For example:

  • spam,good = map(lambda s: int(s,16), line[3:].split(':'))
  • spam,good = [int(s,16) for s in line[3:].split(':')]

The existing line will still work correctly in Python 3.x, but using a list comprehension is more idiomatic and more readable than using map(lambda s: ..., ...).

Past merely working after taking or ignoring such a list of proposed changes by an informed developer, the next step in a high-quality port is a more systematic code review. Not just “What is the syntac‐ tic way to do this?”, but also “Are there standard library modules or new constructs that do this faster? Or more generally? Or more cor‐ rectly? Or using less code and/or more readable code?” The answer to these questions is often yes—but then, that answer is often yes within a version series, or simply when new eyes look at old code.

14 | Porting

Getting code simply to the level of working correctly is usually as simple as running 2to3 and applying its recommendations. Further improvements can be done incrementally, and as time and require‐ ments permit.

six.py

The documentation for Six: Python 2 and 3 Compatibility Library describes it as follows:

Six provides simple utilities for wrapping over differences between Python 2 and Python 3. It is intended to support codebases that work on both Python 2 and 3 without modification. [S]ix consists of only one Python file, so it is painless to copy into a project.

There are a variety of constructs that differ between Python 2.x and 3.x, but it is often possible to wrap the basic functionality in a func‐ tion, class, or method that abstracts away the difference (perhaps by explicitly detecting interpreter version and branching). The effect is that in version-neutral code using six.py, one frequently utilizes calls of the six.do_something(...) sort as the way of doing the close-enough-to-equivalent thing under whichever Python version the program runs in.

For example, almost certainly the most obvious difference between Python 2.x and Python 3.x—especially for beginners—is that the print statement has been replaced by the print() function. What six gives users is a function six.print_() to use everywhere. In Python 3.x, it is simply an alias for the built-in print() while in Python 2.x it reimplements the behavior of that function (with the various keyword arguments). So, for example, where 2to3 would suggest this change:

  • print >>fh, '%s%x:%x' % (trigram, spam, good)
  • print('%s%x:%x' % (trigram, spam, good), file=fh)

The version-neutral change would use:

six.print_('%s%x:%x' % (trigram, spam, good), file=fh)

Python 2.7.x has itself already backported many things—where it is possible to do so without breaking compatibility. So in some cases six is useful instead for supporting even earlier versions of Python 2.x. For example, this is probably what you’d actually do if you only cared about supporting Python 2.7.x and Python 3.x:

six.py | 15