Easy, clean, reliable Python 2/3 compatibility

Overview

Overview: Easy, clean, reliable Python 2/3 compatibility

https://travis-ci.org/PythonCharmers/python-future.svg?branch=master https://readthedocs.org/projects/python-future/badge/?version=latest

python-future is the missing compatibility layer between Python 2 and Python 3. It allows you to use a single, clean Python 3.x-compatible codebase to support both Python 2 and Python 3 with minimal overhead.

It provides future and past packages with backports and forward ports of features from Python 3 and 2. It also comes with futurize and pasteurize, customized 2to3-based scripts that helps you to convert either Py2 or Py3 code easily to support both Python 2 and 3 in a single clean Py3-style codebase, module by module.

Notable projects that use python-future for Python 2/3 compatibility are Mezzanine and ObsPy.

Features

  • future.builtins package (also available as builtins on Py2) provides backports and remappings for 20 builtins with different semantics on Py3 versus Py2
  • support for directly importing 30 standard library modules under their Python 3 names on Py2
  • support for importing the other 14 refactored standard library modules under their Py3 names relatively cleanly via future.standard_library and future.moves
  • past.builtins package provides forward-ports of 19 Python 2 types and builtin functions. These can aid with per-module code migrations.
  • past.translation package supports transparent translation of Python 2 modules to Python 3 upon import. [This feature is currently in alpha.]
  • 1000+ unit tests, including many from the Py3.3 source tree.
  • futurize and pasteurize scripts based on 2to3 and parts of 3to2 and python-modernize, for automatic conversion from either Py2 or Py3 to a clean single-source codebase compatible with Python 2.6+ and Python 3.3+.
  • a curated set of utility functions and decorators in future.utils and past.utils selected from Py2/3 compatibility interfaces from projects like six, IPython, Jinja2, Django, and Pandas.
  • support for the surrogateescape error handler when encoding and decoding the backported str and bytes objects. [This feature is currently in alpha.]
  • support for pre-commit hooks

Code examples

Replacements for Py2's built-in functions and types are designed to be imported at the top of each Python module together with Python's built-in __future__ statements. For example, this code behaves identically on Python 2.6/2.7 after these imports as it does on Python 3.3+:

from __future__ import absolute_import, division, print_function
from builtins import (bytes, str, open, super, range,
                      zip, round, input, int, pow, object)

# Backported Py3 bytes object
b = bytes(b'ABCD')
assert list(b) == [65, 66, 67, 68]
assert repr(b) == "b'ABCD'"
# These raise TypeErrors:
# b + u'EFGH'
# bytes(b',').join([u'Fred', u'Bill'])

# Backported Py3 str object
s = str(u'ABCD')
assert s != bytes(b'ABCD')
assert isinstance(s.encode('utf-8'), bytes)
assert isinstance(b.decode('utf-8'), str)
assert repr(s) == "'ABCD'"      # consistent repr with Py3 (no u prefix)
# These raise TypeErrors:
# bytes(b'B') in s
# s.find(bytes(b'A'))

# Extra arguments for the open() function
f = open('japanese.txt', encoding='utf-8', errors='replace')

# New zero-argument super() function:
class VerboseList(list):
    def append(self, item):
        print('Adding an item')
        super().append(item)

# New iterable range object with slicing support
for i in range(10**15)[:10]:
    pass

# Other iterators: map, zip, filter
my_iter = zip(range(3), ['a', 'b', 'c'])
assert my_iter != list(my_iter)

# The round() function behaves as it does in Python 3, using
# "Banker's Rounding" to the nearest even last digit:
assert round(0.1250, 2) == 0.12

# input() replaces Py2's raw_input() (with no eval()):
name = input('What is your name? ')
print('Hello ' + name)

# pow() supports fractional exponents of negative numbers like in Py3:
z = pow(-1, 0.5)

# Compatible output from isinstance() across Py2/3:
assert isinstance(2**64, int)        # long integers
assert isinstance(u'blah', str)
assert isinstance('blah', str)       # only if unicode_literals is in effect

# Py3-style iterators written as new-style classes (subclasses of
# future.types.newobject) are automatically backward compatible with Py2:
class Upper(object):
    def __init__(self, iterable):
        self._iter = iter(iterable)
    def __next__(self):                 # note the Py3 interface
        return next(self._iter).upper()
    def __iter__(self):
        return self
assert list(Upper('hello')) == list('HELLO')

There is also support for renamed standard library modules. The recommended interface works like this:

# Many Py3 module names are supported directly on both Py2.x and 3.x:
from http.client import HttpConnection
import html.parser
import queue
import xmlrpc.client

# Refactored modules with clashing names on Py2 and Py3 are supported
# as follows:
from future import standard_library
standard_library.install_aliases()

# Then, for example:
from itertools import filterfalse, zip_longest
from urllib.request import urlopen
from collections import ChainMap
from collections import UserDict, UserList, UserString
from subprocess import getoutput, getstatusoutput
from collections import Counter, OrderedDict   # backported to Py2.6

Automatic conversion to Py2/3-compatible code

python-future comes with two scripts called futurize and pasteurize to aid in making Python 2 code or Python 3 code compatible with both platforms (Py2/3). It is based on 2to3 and uses fixers from lib2to3, lib3to2, and python-modernize, as well as custom fixers.

futurize passes Python 2 code through all the appropriate fixers to turn it into valid Python 3 code, and then adds __future__ and future package imports so that it also runs under Python 2.

For conversions from Python 3 code to Py2/3, use the pasteurize script instead. This converts Py3-only constructs (e.g. new metaclass syntax) to Py2/3 compatible constructs and adds __future__ and future imports to the top of each module.

In both cases, the result should be relatively clean Py3-style code that runs mostly unchanged on both Python 2 and Python 3.

Futurize: 2 to both

For example, running futurize -w mymodule.py turns this Python 2 code:

import Queue
from urllib2 import urlopen

def greet(name):
    print 'Hello',
    print name

print "What's your name?",
name = raw_input()
greet(name)

into this code which runs on both Py2 and Py3:

from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import input
import queue
from urllib.request import urlopen

def greet(name):
    print('Hello', end=' ')
    print(name)

print("What's your name?", end=' ')
name = input()
greet(name)

See :ref:`forwards-conversion` and :ref:`backwards-conversion` for more details.

Automatic translation

The past package can automatically translate some simple Python 2 modules to Python 3 upon import. The goal is to support the "long tail" of real-world Python 2 modules (e.g. on PyPI) that have not been ported yet. For example, here is how to use a Python 2-only package called plotrique on Python 3. First install it:

$ pip3 install plotrique==0.2.5-7 --no-compile   # to ignore SyntaxErrors

(or use pip if this points to your Py3 environment.)

Then pass a whitelist of module name prefixes to the autotranslate() function. Example:

$ python3

>>> from past.translation import autotranslate
>>> autotranslate(['plotrique'])
>>> import plotrique

This transparently translates and runs the plotrique module and any submodules in the plotrique package that plotrique imports.

This is intended to help you migrate to Python 3 without the need for all your code's dependencies to support Python 3 yet. It should be used as a last resort; ideally Python 2-only dependencies should be ported properly to a Python 2/3 compatible codebase using a tool like futurize and the changes should be pushed to the upstream project.

Note: the auto-translation feature is still in alpha; it needs more testing and development, and will likely never be perfect.

For more info, see :ref:`translation`.

Pre-commit hooks

Pre-commit is a framework for managing and maintaining multi-language pre-commit hooks.

In case you need to port your project from Python 2 to Python 3, you might consider using such hook during the transition period.

First:

$ pip install pre-commit

and then in your project's directory:

$ pre-commit install

Next, you need to add this entry to your .pre-commit-config.yaml

-   repo: https://github.com/PythonCharmers/python-future
    rev: master
    hooks:
        - id: futurize
          args: [--both-stages]

The args part is optional, by default only stage1 is applied.

Licensing

Author:

Ed Schofield, Jordan M. Adler, et al

Copyright:

2013-2019 Python Charmers Pty Ltd, Australia.

Sponsors:

Python Charmers Pty Ltd, Australia, and Python Charmers Pte Ltd, Singapore. http://pythoncharmers.com

Pinterest https://opensource.pinterest.com/

Licence:

MIT. See LICENSE.txt or here.

Other credits:

See here.

Next steps

If you are new to Python-Future, check out the Quickstart Guide.

For an update on changes in the latest version, see the What's New page.

Comments
  • harcoded tmp folder prevent windows compatibilty of past module

    harcoded tmp folder prevent windows compatibilty of past module

    For issue https://github.com/PythonCharmers/python-future/issues/295 Here we are using temp env variable to figure out right directory to write files like original_code.py in past's translate. I am working on a project that rely on past module and currently before calling the past module's function I am creating Temp directory as a workaround. Once this PR is merged I don't have to use that workaround. It would be good to make this module independent of any OS. Thanks

    opened by kapilkd13 26
  • virtualenv + python-future = broken virtualenv

    virtualenv + python-future = broken virtualenv

    Simplest reproduction:

    $ virtualenv venv
    $ ./venv/bin/pip install future virtualenv
    Collecting future
      Using cached future-0.14.3.tar.gz
    Collecting virtualenv
      Using cached virtualenv-12.1.1-py2.py3-none-any.whl
    Installing collected packages: future, virtualenv
      Running setup.py install for future
    Successfully installed future-0.14.3 virtualenv-12.1.1
    $ ./venv/bin/virtualenv -ppython3.4 venv34
    Running virtualenv with interpreter /usr/bin/python3.4
    Traceback (most recent call last):
      File "/home/anthony/venv/local/lib/python2.7/site-packages/virtualenv.py", line 8, in <module>
        import base64
      File "/usr/lib/python3.4/base64.py", line 9, in <module>
        import re
      File "/usr/lib/python3.4/re.py", line 336, in <module>
        import copyreg
      File "/home/anthony/venv/lib/python2.7/site-packages/copyreg/__init__.py", line 7, in <module>
        raise ImportError('This package should not be accessible on Python 3. '
    ImportError: This package should not be accessible on Python 3. Either you are trying to run from the python-future src folder or your installation of python-future is corrupted.
    
    opened by asottile 18
  • Publish sdist and bdist wheel

    Publish sdist and bdist wheel

    The benefits of wheels are well documented. See: https://pythonwheels.com/ This package is pure Python and publishing it as both source and as a wheel is simple.

    opened by groodt 15
  • Proposal to not use unicode_literals

    Proposal to not use unicode_literals

    I want to propose not using unicode_literals for this undertaking. Only a very low number of people are using Python 3.2 or older and being explicit about unicode strings makes Python code less error prone.

    Accidentally upgrading docstrings and other things to unicode has very bad consequences which can go unnoticed for a really long time. I have seen people putting unicode strings into WSGI dictionaries, breaking pydoc because of unicode docstrings, Django breaking filesystem access due to accidentally using unicode paths etc.

    I like the idea of python future a ton, and just started looking into it, but I am really not a fan of the idea of proposing people to use unicode literals.

    futurize script docs 
    opened by mitsuhiko 15
  • builtins import broken in version 0.17.0

    builtins import broken in version 0.17.0

    Importing builtins in version 0.17.0 causes error.

    >>> import builtins
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named builtins
    >>> 
    
    opened by e-rk 14
  • The new magic

    The new magic "configparser" import breaks the "configparser" backport

    There is a backport of the configparser changes in Python 3.x called simply "configparser". With your newly introduced polyglot imports, your package might override the backport, e.g. it won't be possible to use both together.

    Please consider adding the configparser backport to the list of python-future's requirements, which will solve this issue.

    opened by ambv 13
  • Wrong conversion of division to old_div

    Wrong conversion of division to old_div

    Example code

    The following code contains an old style division.

    (x / 2 * 3.0)
    

    The expected result

    The result running the above code with arbitrary values assigned to x should be the following, where the parentheses explicitly show the order of the operations (x / 2) * 3.0. Or written in another order the result should be evaluated as x * (3.0 / 2).

    The issue

    Once we run futurize on the code above, an old_div gets inserted by the fix_division_safe fixture. However as one can see in the diff below, the function gets called with a wrong order of arguments.

    $ futurize --stage2 src/example.py
    RefactoringTool: Refactored src/example.py
    --- src/example.py      (original)
    +++ src/example.py      (refactored)
    @@ -1 +1,3 @@
    -(x / 2 * 3.0)
    +from __future__ import division
    +from past.utils import old_div
    +(old_div(x, 2 * 3.0))
    RefactoringTool: Files that need to be modified:
    RefactoringTool: src/example.py
    

    Expected conversion

    As already stated in the section 'expected result' the correct conversion should have been: (old_div(x, 2) * 3.0)

    bug 0.18 
    opened by wagnerpeer 12
  • Debian packaging (solved)

    Debian packaging (solved)

    Are there plans for Debian .deb packages? @obspy is distributed as Debian packages and the next major release will have a dependency on python-future.. which is still unresolved for Debian packaging..

    enhancement 
    opened by megies 12
  • ImportError when using CommonMark-py with Google App Engine

    ImportError when using CommonMark-py with Google App Engine

    When I try to use CommonMark-py -which uses python-future- with App Engine I get this error, if I put import CommonMark at the top:

    ERROR    2016-08-26 14:04:59,126 wsgi.py:263] 
    Traceback (most recent call last):
      File "/home/super/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
        handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
      File "/home/super/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
        handler, path, err = LoadObject(self._handler)
      File "/home/super/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
        obj = __import__(path[0])
      File "/home/super/WebProjects/myapp/blog.py", line 3, in <module>
        from models import Post
      File "/home/super/WebProjects/myapp/models.py", line 1, in <module>
        import CommonMark
      File "/home/super/WebProjects/myapp/libs/CommonMark/__init__.py", line 4, in <module>
        from CommonMark.main import commonmark
      File "/home/super/WebProjects/myapp/libs/CommonMark/main.py", line 15, in <module>
        from CommonMark.dump import dumpAST, dumpJSON
      File "/home/super/WebProjects/myapp/libs/CommonMark/dump.py", line 3, in <module>
        from builtins import str
      File "/home/super/WebProjects/myapp/libs/builtins/__init__.py", line 8, in <module>
        from future.builtins import *
      File "/home/super/WebProjects/myapp/libs/future/builtins/__init__.py", line 10, in <module>
        from future.builtins.iterators import (filter, map, zip)
      File "/home/super/WebProjects/myapp/libs/future/builtins/iterators.py", line 43, in <module>
        from future.types import newrange as range
      File "/home/super/WebProjects/myapp/libs/future/types/__init__.py", line 243, in <module>
        from .newrange import newrange
      File "/home/super/WebProjects/myapp/libs/future/types/newrange.py", line 25, in <module>
        from future.backports.misc import count   # with step parameter on Py2.6
      File "/home/super/WebProjects/myapp/libs/future/backports/__init__.py", line 17, in <module>
        from .misc import (ceil,
      File "/home/super/WebProjects/myapp/libs/future/backports/misc.py", line 900, in <module>
        from subprocess import check_output
    ImportError: cannot import name check_output
    INFO     2016-08-26 14:04:59,140 module.py:788] default: "GET /blog/5822463824887808 HTTP/1.1" 500 -
    INFO     2016-08-26 14:04:59,196 module.py:788] default: "GET /favicon.ico HTTP/1.1" 304 -
    

    But, when I import CommonMark inside a method I get:

    ERROR    2016-08-26 13:38:08,116 webapp2.py:1552] cannot import name check_output
    Traceback (most recent call last):
      File "/home/super/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
        rv = self.handle_exception(request, response, e)
      File "/home/super/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
        rv = self.router.dispatch(request, response)
      File "/home/super/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
        return route.handler_adapter(request, response)
      File "/home/super/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
        return handler.dispatch()
      File "/home/super/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
        return self.handle_exception(e, self.app.debug)
      File "/home/super/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
        return method(*args, **kwargs)
      File "/home/super/WebProjects/myapp/blog.py", line 29, in get
        self.render('permalink.html', post=post, url=self.url)
      File "/home/super/WebProjects/myapp/handlers.py", line 33, in render
        self.write(self.render_str(template, **kw))
      File "/home/super/WebProjects/myapp/handlers.py", line 30, in render_str
        return render_str(template, **kw)
      File "/home/super/WebProjects/myapp/handlers.py", line 20, in render_str
        return t.render(kw)
      File "/home/super/google_appengine/lib/jinja2-2.6/jinja2/environment.py", line 894, in render
        return self.environment.handle_exception(exc_info, True)
      File "/home/super/WebProjects/myapp/templates/permalink.html", line 1, in top-level template code
        {% extends "base.html" %}
    ImportError: cannot import name check_output
    INFO     2016-08-26 13:38:08,186 module.py:788] default: "GET /blog/5822463824887808 HTTP/1.1" 500 228
    INFO     2016-08-26 13:38:08,281 module.py:788] default: "GET /favicon.ico HTTP/1.1" 304 -
    

    I am used to add other libraries to my App Engine projects as described in App Engine's installing a library document but this library causes these errors even though it is working with webapp2 outside App Engine!

    I reported this issue to CommonMark but Mr. @nikolas suggested reporting it here.

    Note: I am using App Engine Standard Environment and Python 2.7.12. Also, It seems like App Engine is using version 2.7.2.

    opened by badersur 10
  • Python 2.6: TypeError: create_connection() takes at most 2 arguments (3 given)

    Python 2.6: TypeError: create_connection() takes at most 2 arguments (3 given)

    We're seeing this traceback on Python 2.6:

    Traceback (most recent call last):
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/obspy/core/tests/test_stream.py", line 1687, in test_read
        tr = read('http://examples.obspy.org/test.sac', dtype=np.int32)[0]
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/obspy/core/util/decorator.py", line 307, in new_func
        return func(*args, **kwargs)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/obspy/core/stream.py", line 225, in read
        fh.write(urllib.request.urlopen(pathname_or_url).read())
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/urllib/request.py", line 171, in urlopen
        return opener.open(url, data, timeout)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/urllib/request.py", line 494, in open
        response = self._open(req, data)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/urllib/request.py", line 512, in _open
        '_open', req)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/urllib/request.py", line 466, in _call_chain
        result = func(*args)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/urllib/request.py", line 1311, in http_open
        return self.do_open(http_client.HTTPConnection, req)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/urllib/request.py", line 1284, in do_open
        h.request(req.get_method(), req.selector, req.data, headers)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/http/client.py", line 1092, in request
        self._send_request(method, url, body, headers)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/http/client.py", line 1130, in _send_request
        self.endheaders(body)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/http/client.py", line 1088, in endheaders
        self._send_output(message_body)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/http/client.py", line 933, in _send_output
        self.send(msg)
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/http/client.py", line 869, in send
        self.connect()
      File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/future/backports/http/client.py", line 847, in connect
        self.timeout, self.source_address)
    TypeError: create_connection() takes at most 2 arguments (3 given)
    
    opened by QuLogic 10
  • basestring fixer is extremely disruptive

    basestring fixer is extremely disruptive

    futurize --stage2 replaces all uses of basestring with str (and also makes str always be the text type), which breaks isinstance checks on native strings on Python 2.

    If there were a string_types available, maybe futurize could use that instead :)

    opened by eevee 9
  • PYTHONPATH breaks pip installation

    PYTHONPATH breaks pip installation

    It is impossible to install the package via any dependency-manager (pipenv, poetry, ...) if the PYTHONPATH is adjusted. Alacritty 2022-12-28

    Device info: Chip: M1 OS: MacOS Ventura 13.1

    opened by parfeniukink 0
  • Backport fix for bpo-38804

    Backport fix for bpo-38804

    Recently, a CVE was published for this project related to a CVE previously patched in Python. I am not sure if this project is still maintained any more but it is still listed as a dependency by some other popular projects, so it would be good to patch.

    The regex http.cookiejar.LOOSE_HTTP_DATE_RE was vulnerable to regular expression denial of service (REDoS). The regex contained multiple overlapping \s* capture groups. A long sequence of spaces can trigger bad performance.

    See https://github.com/python/cpython/pull/17157 and https://pyup.io/posts/pyup-discovers-redos-vulnerabilities-in-top-python-packages/

    opened by wshanks 2
  • Add fixture for ValueError.message to futurize

    Add fixture for ValueError.message to futurize

    Bug report

    Please extend the futurize tool to display a warning when ValueError.message is used, or replace the message attribute e.g. with str(<exception>), since ValueError.message no longer exists in Python 3.

    Reproducer

    $ cat example.py2
    #!/usr/bin/env python2.7
    try:
        raise ValueError('Foo')
    except ValueError as e:
        print "Caught: %s" % e.message
     
    $ futurize example.py2 
    RefactoringTool: Skipping optional fixer: idioms
    RefactoringTool: Skipping optional fixer: ws_comma
    RefactoringTool: Refactored example.py2
    --- example.py2	(original)
    +++ example.py2	(refactored)
    @@ -1,5 +1,6 @@
     #!/usr/bin/env python2.7
    +from __future__ import print_function
     try:
         raise ValueError('Foo')
     except ValueError as e:
    -    print "Caught: %s" % e.message
    +    print("Caught: %s" % e.message)
    RefactoringTool: Files that need to be modified:
    RefactoringTool: example.py2
    

    Example of an expected result

    --- example.py2	(original)
    +++ example.py2	(refactored)
    @@ -2,4 +2,4 @@
     try:
         raise ValueError('Foo')
     except ValueError as e:
    -    print "Caught: %s" % e.message
    +    print("Caught: %s" % str(e))
    

    My environment

    • up-to-date ArchLinux on x86_64
    • Python 3.10.8 (main, Oct 13 2022, 21:13:48) [GCC 12.2.0]
    • futurize 0.18.2
    opened by CarstenGrohmann 0
  • test_single_exception_stacktrace failed with python-3.11

    test_single_exception_stacktrace failed with python-3.11

    Hi all.

    test_single_exception_stacktrace is failing with Python-3.11.0~b5:

    + PYTHONPATH=/builddir/build/BUILD/future-0.18.2/python3/build/lib
    + py.test-3.11 -k 'not test_pow and not test_urllib2' -q
    ...............................................................s........ [  6%]
    ...s....................sss..............s.............................. [ 13%]
    ..s..................x........s......................................... [ 20%]
    ..................s...x...x..x..x.......s.xsss.x....x...x.....x.....x.xx [ 26%]
    ............................................ss.......................... [ 33%]
    ........................................................................ [ 40%]
    ..s..........................................x.........sssss............ [ 47%]
    .............................................................s.s........ [ 53%]
    ...........x...x...xx........................ss..........s....ss........ [ 60%]
    .....s.....ss....................s............................s..x...... [ 67%]
    ........................................................................ [ 73%]
    ...........s..................................s.....s..s................ [ 80%]
    ....................s.s..............s.sssssssssss...................... [ 87%]
    ..............................F....x..xxxxxx...x.xxxxxx....xx..xx..x.xx. [ 94%]
    xx...x....x...x.......................s....................x....         [100%]
    =================================== FAILURES ===================================
    __________________ TestCause.test_single_exception_stacktrace __________________
    self = <test_future.test_utils.TestCause testMethod=test_single_exception_stacktrace>
            def test_single_exception_stacktrace(self):
                expected = '''Traceback (most recent call last):
          File "/opt/python-future/tests/test_future/test_utils.py", line 328, in test_single_exception_stacktrace
            raise CustomException('ERROR')
        '''
                if sys.version_info >= (3, 11):
                    expected += '    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
                if PY2:
                    expected += 'CustomException: ERROR\n'
                else:
                    expected += 'test_future.test_utils.CustomException: ERROR\n'
        
                try:
    >               raise CustomException('ERROR')
    E               test_future.test_utils.CustomException: ERROR
    tests/test_future/test_utils.py:354: CustomException
    During handling of the above exception, another exception occurred:
    self = <test_future.test_utils.TestCause testMethod=test_single_exception_stacktrace>
            def test_single_exception_stacktrace(self):
                expected = '''Traceback (most recent call last):
          File "/opt/python-future/tests/test_future/test_utils.py", line 328, in test_single_exception_stacktrace
            raise CustomException('ERROR')
        '''
                if sys.version_info >= (3, 11):
                    expected += '    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
                if PY2:
                    expected += 'CustomException: ERROR\n'
                else:
                    expected += 'test_future.test_utils.CustomException: ERROR\n'
        
                try:
                    raise CustomException('ERROR')
                except:
                    ret = re.sub(r'"[^"]*tests/test_future', '"/opt/python-future/tests/test_future', traceback.format_exc())
                    ret = re.sub(r', line \d+,', ', line 328,', ret)
    >               self.assertEqual(expected, ret)
    E               AssertionError: 'Trac[173 chars]\')\n    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\ntest_[38 chars]OR\n' != 'Trac[173 chars]\')\ntest_future.test_utils.CustomException: ERROR\n'
    E                 Traceback (most recent call last):
    E                   File "/opt/python-future/tests/test_future/test_utils.py", line 328, in test_single_exception_stacktrace
    E                     raise CustomException('ERROR')
    E               -     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    E                 test_future.test_utils.CustomException: ERROR
    tests/test_future/test_utils.py:358: AssertionError
    =============================== warnings summary ===============================
    build/lib/future/standard_library/__init__.py:65
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/standard_library/__init__.py:65: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
        import imp
    tests/test_future/test_builtins.py:267
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_builtins.py:267: DeprecationWarning: invalid escape sequence '\u'
        (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
    tests/test_future/test_builtins.py:289
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_builtins.py:289: DeprecationWarning: invalid escape sequence '\u'
        (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
    build/lib/future/backports/test/support.py:1977
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/test/support.py:1977: DeprecationWarning: invalid escape sequence '\d'
        m = re.match("2.6.(\d{1,2})", kernel_version)
    build/lib/future/backports/email/message.py:13
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/email/message.py:13: DeprecationWarning: 'uu' is deprecated and slated for removal in Python 3.13
        import uu
    build/lib/future/backports/email/utils.py:68
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/email/utils.py:68: DeprecationWarning: invalid escape sequence '\A'
        '([^\ud800-\udbff]|\A)[\udc00-\udfff]([^\udc00-\udfff]|\Z)').search
    build/lib/future/backports/urllib/parse.py:957
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/urllib/parse.py:957: DeprecationWarning: invalid escape sequence '\?'
        _queryprog = re.compile('^(.*)\?([^?]*)$')
    build/lib/libfuturize/fixer_util.py:11
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/libfuturize/fixer_util.py:11: DeprecationWarning: lib2to3 package is deprecated and may not be able to parse Python 3.10+
        from lib2to3.fixer_util import (FromImport, Newline, is_import,
    tests/test_future/test_htmlparser.py:685
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_htmlparser.py:685: DeprecationWarning: invalid escape sequence '\='
        "<a $><b $=%><c \=/>",
    build/lib/future/backports/html/parser.py:31
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/html/parser.py:31: DeprecationWarning: invalid escape sequence '\s'
        tagfind = re.compile('([a-zA-Z][-.a-zA-Z0-9:_]*)(?:\s|/(?!>))*')
    build/lib/future/backports/html/parser.py:79
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/html/parser.py:79: DeprecationWarning: invalid escape sequence '\s'
        endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
    tests/test_future/test_http_cookiejar.py:1034
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_http_cookiejar.py:1034: DeprecationWarning: invalid escape sequence '\$'
        self.assertRegex(h, "\$Port([^=]|$)",
    tests/test_future/test_http_cookiejar.py:1373
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_http_cookiejar.py:1373: DeprecationWarning: invalid escape sequence '\s'
        '\s*\$Path="\/acme"')
    tests/test_future/test_http_cookiejar.py:1375
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_http_cookiejar.py:1375: DeprecationWarning: invalid escape sequence '\s'
        '\s*\$Path="\/acme"')
    build/lib/future/backports/http/client.py:1
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/http/client.py:1: DeprecationWarning: invalid escape sequence '\_'
        """HTTP/1.1 client library
    build/lib/future/backports/email/feedparser.py:37
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/email/feedparser.py:37: DeprecationWarning: invalid escape sequence '\Z'
        NLCRE_eol = re.compile('(\r\n|\r|\n)\Z')
    build/lib/future/backports/http/cookiejar.py:212
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/http/cookiejar.py:212: DeprecationWarning: invalid escape sequence '\d'
        "(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$", re.ASCII)
    build/lib/future/backports/http/cookiejar.py:289
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/http/cookiejar.py:289: DeprecationWarning: invalid escape sequence '\d'
        """^
    build/lib/future/backports/http/cookiejar.py:423
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/http/cookiejar.py:423: DeprecationWarning: invalid escape sequence '\s'
        non_junk, nr_junk_chars = re.subn("^[=\s;]*", "", text)
    tests/test_future/test_urllib.py:536
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_urllib.py:536: DeprecationWarning: invalid escape sequence '\^'
        """Tests for urllib.quote() and urllib.quote_plus()
    tests/test_future/test_urllib.py:611
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_urllib.py:611: DeprecationWarning: invalid escape sequence '\^'
        should_quote.append('<>#%"{}|\^[]`')
    tests/test_future/test_urllib_toplevel.py:551
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_urllib_toplevel.py:551: DeprecationWarning: invalid escape sequence '\^'
        """Tests for urllib.quote() and urllib.quote_plus()
    tests/test_future/test_urllib_toplevel.py:626
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_urllib_toplevel.py:626: DeprecationWarning: invalid escape sequence '\^'
        should_quote.append('<>#%"{}|\^[]`')
    build/lib/past/types/oldstr.py:23
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/past/types/oldstr.py:23: DeprecationWarning: invalid escape sequence '\d'
        """
    tests/test_future/test_htmlparser.py: 4 warnings
    tests/test_future/test_http_cookiejar.py: 5 warnings
    tests/test_future/test_urllibnet.py: 3 warnings
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/test/support.py:1656: DeprecationWarning: unittest.makeSuite() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.loadTestsFromTestCase() instead.
        suite.addTest(unittest.makeSuite(cls))
    tests/test_future/test_httplib.py::SourceAddressTest::testHTTPSConnectionSourceAddress
    tests/test_future/test_httplib.py::HTTPSTest::test_attributes
    tests/test_future/test_httplib.py::HTTPSTest::test_host_port
    tests/test_future/test_httplib.py::HTTPSTest::test_host_port
    tests/test_future/test_httplib.py::HTTPSTest::test_host_port
    tests/test_future/test_httplib.py::HTTPSTest::test_host_port
    tests/test_future/test_httplib.py::HTTPSTest::test_host_port
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/future/backports/http/client.py:1218: DeprecationWarning: ssl.PROTOCOL_TLS is deprecated
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    tests/test_future/test_int.py::IntTestCases::test_intconversion
    tests/test_future/test_int.py::IntTestCases::test_intconversion
    tests/test_future/test_int.py::IntTestCases::test_intconversion
    tests/test_future/test_int.py::IntTestCases::test_intconversion
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_int.py:401: DeprecationWarning: The delegation of int() to __trunc__ is deprecated.
        int(TruncReturnsNonIntegral())
    tests/test_future/test_int.py::IntTestCases::test_intconversion
    tests/test_future/test_int.py::IntTestCases::test_intconversion
    tests/test_future/test_int.py::IntTestCases::test_intconversion
    tests/test_future/test_int.py::IntTestCases::test_intconversion
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_int.py:421: DeprecationWarning: The delegation of int() to __trunc__ is deprecated.
        int(TruncReturnsBadInt())
    tests/test_future/test_standard_library.py::TestStandardLibraryReorganization::test_reload
      /usr/lib64/python3.11/importlib/__init__.py:169: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
        _bootstrap._exec(spec, module)
    tests/test_future/test_urllibnet.py::urlopenNetworkTests::test_getcode
    tests/test_future/test_urllibnet.py::test_main
      /builddir/build/BUILD/future-0.18.2/python3/tests/test_future/test_urllibnet.py:103: DeprecationWarning: FancyURLopener style of invoking requests is deprecated. Use newer urlopen functions/methods
        open_url = urllib_request.FancyURLopener().open(URL)
    tests/test_past/test_oldstr.py::TestOldStr::test_unescape
      /builddir/build/BUILD/future-0.18.2/python3/build/lib/past/types/oldstr.py:37: DeprecationWarning: invalid escape sequence '\c'
        return s.encode().decode('unicode_escape')
    -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
    =========================== short test summary info ============================
    FAILED tests/test_future/test_utils.py::TestCause::test_single_exception_stacktrace
    1 failed, 973 passed, 52 skipped, 57 deselected, 46 xfailed, 55 warnings in 26.95s
    
    opened by sagitter 0
  • Passing code to futurize as a string

    Passing code to futurize as a string

    futurize works on files. But can I run it on code strings? E.g. is there a function I can import which takes source code (string) as input and returns futurized code (as a string)?

    If not, where would I start to adapt the futurize script to do this?

    opened by shobrook 0
Releases(v0.18.2)
  • v0.18.2(Jun 13, 2020)

    This is a minor bug-fix release containing a number of fixes:

    • Fix min/max functions with generators, and 'None' default (PR #514)
    • Use BaseException in raise_() (PR #515)
    • Fix builtins.round() for Decimals (Issue #501)
    • Fix raise_from() to prevent failures with immutable classes (PR #518)
    • Make FixInput idempotent (Issue #427)
    • Fix type in newround (PR #521)
    • Support mimetype guessing in urllib2 for Py3.8+ (Issue #508)

    Python 3.8 is not yet officially supported.

    Source code(tar.gz)
    Source code(zip)
  • v0.18.1(Jun 13, 2020)

    This is a minor bug-fix release containing a fix for raise_() when passed an exception that's not an Exception (e.g. BaseException subclasses)

    Source code(tar.gz)
    Source code(zip)
  • v0.18.0(Jun 13, 2020)

    This is a major bug-fix and feature release, including:

    • Fix collections.abc import for py38+
    • Remove import for isnewbytes() function, reducing CPU cost significantly
    • Fix bug with importing past.translation when importing past which breaks zipped python installations
    • Fix an issue with copyreg import under Py3 that results in unexposed stdlib functionality
    • Export and document types in future.utils
    • Update behavior of newstr.eq() to match str.eq() as per reference docs
    • Fix raising and the raising fixer to handle cases where the syntax is ambigious
    • Allow "default" parameter in min() and max() (Issue #334)
    • Implement hash() in newstr (Issue #454)
    • Future proof some version checks to handle the fact that Py4 won't be a major breaking release
    • Fix urllib.request imports for Python 3.8 compatibility (Issue #447)
    • Fix future import ordering (Issue #445)
    • Fixed bug in fix_division_safe fixture (Issue #434)
    • Do not globally destroy re.ASCII in PY3
    • Fix a bug in email.Message.set_boundary() (Issue #429)
    • Implement format_map() in str
    • Implement readinto() for socket.fp

    As well as a number of corrections to a variety of documentation, and updates to test infrastructure.

    Source code(tar.gz)
    Source code(zip)
  • v0.17.1(Jun 13, 2020)

  • v0.17.0(Oct 25, 2018)

    This is a major bug-fix release, including:

    • Fix from collections import ChainMap after install_aliases() (issue #226)
    • Fix multiple import from __future__bug in futurize (issue #113)
    • Add support for proper %s formatting of newbytes
    • Properly implement iterator protocol for newrange object
    • Fix past.translation on read-only file systems
    • Fix Tkinter import bug introduced in Python 2.7.4 (issue #262)
    • Correct TypeError to ValueError in a specific edge case for newrange
    • Support inequality tests betwen newstrs and newbytes
    • Add type check to __get__ in newsuper
    • Fix fix_division_safe to support better conversion of complex expressions, and skip obvious float division.

    As well as a number of corrections to a variety of documentation, and updates to test infrastructure.

    Source code(tar.gz)
    Source code(zip)
Owner
Python Charmers
Python Charmers
FCurve-Cleaner: Tries to clean your dense mocap graphs like an animator would

Tries to clean your dense mocap graphs like an animator would! So it will produce a usable artist friendly result while maintaining the original graph.

wiSHFul97 5 Aug 17, 2022
A Python utility belt containing simple tools, a stdlib like feel, and extra batteries. Hashing, Caching, Timing, Progress, and more made easy!

Ubelt is a small library of robust, tested, documented, and simple functions that extend the Python standard library. It has a flat API that all behav

Jon Crall 638 Dec 13, 2022
Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls

guess-the-numbers Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls Number guessing game

Amir Hussein Sharifnezhad 5 Oct 9, 2021
Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls

password-generator Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls Password generator

Amir Hussein Sharifnezhad 3 Oct 9, 2021
Sabe is a python framework written for easy web server setup.

Sabe is a python framework written for easy web server setup. Sabe, kolay web sunucusu kurulumu için yazılmış bir python çerçevesidir. Öğrenmesi kola

null 2 Jan 1, 2022
Easy way to build a SaaS application using Python and Dash

EasySaaS This project will be attempt to make a great starting point for your next big business as easy and efficent as possible. This project will cr

xianhu 3 Nov 17, 2022
Simple and easy to use python API for the COVID registration booking system of the math department @ unipd (torre archimede)

Simple and easy to use python API for the COVID registration booking system of the math department @ unipd (torre archimede). This API creates an interface with the official browser, with more useful functionalities.

Guglielmo Camporese 4 Dec 24, 2021
A modern python module including many useful features that make discord bot programming extremely easy.

discord-super-utils Documentation Secondary Documentation A modern python module including many useful features that make discord bot programming extr

null 106 Dec 19, 2022
This repository provides a set of easy to understand and tested Python samples for using Acronis Cyber Platform API.

Base Acronis Cyber Platform API operations with Python !!! info Copyright © 2019-2021 Acronis International GmbH. This is distributed under MIT licens

Acronis International GmbH 3 Aug 11, 2022
An easy python calculator for those who want's to know how if statements, loops, and imports works give it a try!

A usefull calculator for any student or anyone who want's to know how to build a simple 2 mode python based calculator.

Antonio Sánchez 1 Jan 6, 2022
A simple and easy to use Python's PIP configuration manager, similar to the Arch Linux's Java manager.

PIPCONF - The PIP configuration manager If you need to manage multiple configurations containing indexes and trusted hosts for PIP, this project was m

João Paulo Carvalho 11 Nov 30, 2022
A collection of common regular expressions bundled with an easy to use interface.

CommonRegex Find all times, dates, links, phone numbers, emails, ip addresses, prices, hex colors, and credit card numbers in a string. We did the har

Madison May 1.5k Dec 31, 2022
Connect Playground - easy way to fill in your account with production-like objects

Just set of scripts to initialise accpunt with production-like data: A - Basic Distributor Account Initialization INPUT Distributor Account Token ACTI

CloudBlue 5 Jun 25, 2021
Tie together `drf-spectacular` and `djangorestframework-dataclasses` for easy-to-use apis and openapi schemas.

Speccify Tie together drf-spectacular and djangorestframework-dataclasses for easy-to-use apis and openapi schemas. Usage @dataclass class MyQ

Lyst 4 Sep 26, 2022
tgEasy | Easy for a Brighter Shine | Monkey Patcher Addon for Pyrogram

tgEasy | Easy for a Brighter Shine | Monkey Patcher Addon for Pyrogram

Jayant Hegde Kageri 35 Nov 12, 2022
Generate Openbox Menus from a easy to write configuration file.

openbox-menu-generator Generate Openbox Menus from a easy to write configuration file. Example Configuration: ('#' indicate comments but not implement

null 3 Jul 14, 2022
This module extends twarc to allow you to print out tweets as text for easy testing on the command line

twarc-text This module extends twarc to allow you to print out tweets as text for easy testing on the command line. Maybe it's useful for spot checkin

Documenting the Now 2 Oct 12, 2021
🤖🤖 Jarvis is an virtual assistant which can some tasks easy for you like surfing on web opening an app and much more... 🤖🤖

Jarvis ?? ?? Jarvis is an virtual assistant which can some tasks easy for you like surfing on web opening an app and much more... ?? ?? Developer : su

null 1 Nov 8, 2021