├── .github
├── CONTRIBUTING.md
├── SECURITY.md
└── workflows
│ └── ci.yml
├── .gitignore
├── .pre-commit-hooks.yaml
├── 2.6.Dockerfile
├── Dockerfile
├── LICENSE.txt
├── MANIFEST.in
├── README.rst
├── TESTING.txt
├── check_rst.sh
├── docs
├── 3rd-party-py3k-compat-code
│ ├── astropy_py3compat.py
│ ├── django_utils_encoding.py
│ ├── gevent_py3k.py
│ ├── ipython_py3compat.py
│ ├── jinja2_compat.py
│ ├── numpy_py3k.py
│ ├── pandas_py3k.py
│ ├── pycrypto_py3compat.py
│ └── statsmodels_py3k.py
├── Makefile
├── _static
│ ├── python-future-icon-32.ico
│ ├── python-future-icon-white-32.ico
│ ├── python-future-logo-textless-transparent.png
│ ├── python-future-logo.png
│ └── python-future-logo.tiff
├── _templates
│ ├── layout.html
│ ├── navbar.html
│ ├── sidebarintro.html
│ ├── sidebarlogo.html
│ └── sidebartoc.html
├── _themes
│ ├── LICENSE
│ ├── README
│ └── future
│ │ ├── layout.html
│ │ ├── relations.html
│ │ ├── static
│ │ └── future.css_t
│ │ └── theme.conf
├── automatic_conversion.rst
├── bind_method.rst
├── bytes_object.rst
├── changelog.rst
├── compatible_idioms.rst
├── conf.py
├── contents.rst.inc
├── conversion_limitations.rst
├── credits.rst
├── custom_iterators.rst
├── custom_str_methods.rst
├── dev_notes.rst
├── development.rst
├── dict_object.rst
├── faq.rst
├── func_annotations.rst
├── future-builtins.rst
├── futureext.py
├── futurize.rst
├── futurize_cheatsheet.rst
├── futurize_overview.rst
├── hindsight.rst
├── imports.rst
├── index.rst
├── int_object.rst
├── isinstance.rst
├── limitations.rst
├── metaclasses.rst
├── notebooks
│ ├── Writing Python 2-3 compatible code.ipynb
│ ├── bytes object.ipynb
│ └── object special methods (next, bool, ...).ipynb
├── older_interfaces.rst
├── open_function.rst
├── other
│ ├── auto2to3.py
│ ├── find_pattern.py
│ ├── fix_notebook_html_colour.py
│ ├── lessons.txt
│ ├── todo.txt
│ ├── upload_future_docs.sh
│ └── useful_links.txt
├── overview.rst
├── pasteurize.rst
├── quickstart.rst
├── reference.rst
├── requirements.txt
├── roadmap.rst
├── standard_library_imports.rst
├── stdlib_incompatibilities.rst
├── str_object.rst
├── translation.rst
├── unicode_literals.rst
├── upgrading.rst
├── utilities.rst
├── what_else.rst
├── whatsnew.rst
└── why_python3.rst
├── futurize.py
├── pasteurize.py
├── pytest.ini
├── setup.cfg
├── setup.py
├── src
├── __init__.py
├── _dummy_thread
│ └── __init__.py
├── _markupbase
│ └── __init__.py
├── _thread
│ └── __init__.py
├── builtins
│ └── __init__.py
├── copyreg
│ └── __init__.py
├── future
│ ├── __init__.py
│ ├── backports
│ │ ├── __init__.py
│ │ ├── _markupbase.py
│ │ ├── datetime.py
│ │ ├── email
│ │ │ ├── __init__.py
│ │ │ ├── _encoded_words.py
│ │ │ ├── _header_value_parser.py
│ │ │ ├── _parseaddr.py
│ │ │ ├── _policybase.py
│ │ │ ├── base64mime.py
│ │ │ ├── charset.py
│ │ │ ├── encoders.py
│ │ │ ├── errors.py
│ │ │ ├── feedparser.py
│ │ │ ├── generator.py
│ │ │ ├── header.py
│ │ │ ├── headerregistry.py
│ │ │ ├── iterators.py
│ │ │ ├── message.py
│ │ │ ├── mime
│ │ │ │ ├── __init__.py
│ │ │ │ ├── application.py
│ │ │ │ ├── audio.py
│ │ │ │ ├── base.py
│ │ │ │ ├── image.py
│ │ │ │ ├── message.py
│ │ │ │ ├── multipart.py
│ │ │ │ ├── nonmultipart.py
│ │ │ │ └── text.py
│ │ │ ├── parser.py
│ │ │ ├── policy.py
│ │ │ ├── quoprimime.py
│ │ │ └── utils.py
│ │ ├── html
│ │ │ ├── __init__.py
│ │ │ ├── entities.py
│ │ │ └── parser.py
│ │ ├── http
│ │ │ ├── __init__.py
│ │ │ ├── client.py
│ │ │ ├── cookiejar.py
│ │ │ ├── cookies.py
│ │ │ └── server.py
│ │ ├── misc.py
│ │ ├── socket.py
│ │ ├── socketserver.py
│ │ ├── test
│ │ │ ├── __init__.py
│ │ │ ├── badcert.pem
│ │ │ ├── badkey.pem
│ │ │ ├── dh512.pem
│ │ │ ├── https_svn_python_org_root.pem
│ │ │ ├── keycert.passwd.pem
│ │ │ ├── keycert.pem
│ │ │ ├── keycert2.pem
│ │ │ ├── nokia.pem
│ │ │ ├── nullbytecert.pem
│ │ │ ├── nullcert.pem
│ │ │ ├── pystone.py
│ │ │ ├── sha256.pem
│ │ │ ├── ssl_cert.pem
│ │ │ ├── ssl_key.passwd.pem
│ │ │ ├── ssl_key.pem
│ │ │ ├── ssl_servers.py
│ │ │ └── support.py
│ │ ├── total_ordering.py
│ │ ├── urllib
│ │ │ ├── __init__.py
│ │ │ ├── error.py
│ │ │ ├── parse.py
│ │ │ ├── request.py
│ │ │ ├── response.py
│ │ │ └── robotparser.py
│ │ └── xmlrpc
│ │ │ ├── __init__.py
│ │ │ ├── client.py
│ │ │ └── server.py
│ ├── builtins
│ │ ├── __init__.py
│ │ ├── disabled.py
│ │ ├── iterators.py
│ │ ├── misc.py
│ │ ├── new_min_max.py
│ │ ├── newnext.py
│ │ ├── newround.py
│ │ └── newsuper.py
│ ├── moves
│ │ ├── __init__.py
│ │ ├── _dummy_thread.py
│ │ ├── _markupbase.py
│ │ ├── _thread.py
│ │ ├── builtins.py
│ │ ├── collections.py
│ │ ├── configparser.py
│ │ ├── copyreg.py
│ │ ├── dbm
│ │ │ ├── __init__.py
│ │ │ ├── dumb.py
│ │ │ ├── gnu.py
│ │ │ └── ndbm.py
│ │ ├── html
│ │ │ ├── __init__.py
│ │ │ ├── entities.py
│ │ │ └── parser.py
│ │ ├── http
│ │ │ ├── __init__.py
│ │ │ ├── client.py
│ │ │ ├── cookiejar.py
│ │ │ ├── cookies.py
│ │ │ └── server.py
│ │ ├── itertools.py
│ │ ├── multiprocessing.py
│ │ ├── pickle.py
│ │ ├── queue.py
│ │ ├── reprlib.py
│ │ ├── socketserver.py
│ │ ├── subprocess.py
│ │ ├── sys.py
│ │ ├── test
│ │ │ ├── __init__.py
│ │ │ └── support.py
│ │ ├── tkinter
│ │ │ ├── __init__.py
│ │ │ ├── colorchooser.py
│ │ │ ├── commondialog.py
│ │ │ ├── constants.py
│ │ │ ├── dialog.py
│ │ │ ├── dnd.py
│ │ │ ├── filedialog.py
│ │ │ ├── font.py
│ │ │ ├── messagebox.py
│ │ │ ├── scrolledtext.py
│ │ │ ├── simpledialog.py
│ │ │ ├── tix.py
│ │ │ └── ttk.py
│ │ ├── urllib
│ │ │ ├── __init__.py
│ │ │ ├── error.py
│ │ │ ├── parse.py
│ │ │ ├── request.py
│ │ │ ├── response.py
│ │ │ └── robotparser.py
│ │ ├── winreg.py
│ │ └── xmlrpc
│ │ │ ├── __init__.py
│ │ │ ├── client.py
│ │ │ └── server.py
│ ├── standard_library
│ │ └── __init__.py
│ ├── tests
│ │ ├── __init__.py
│ │ └── base.py
│ ├── types
│ │ ├── __init__.py
│ │ ├── newbytes.py
│ │ ├── newdict.py
│ │ ├── newint.py
│ │ ├── newlist.py
│ │ ├── newmemoryview.py
│ │ ├── newobject.py
│ │ ├── newopen.py
│ │ ├── newrange.py
│ │ └── newstr.py
│ └── utils
│ │ ├── __init__.py
│ │ └── surrogateescape.py
├── html
│ ├── __init__.py
│ ├── entities.py
│ └── parser.py
├── http
│ ├── __init__.py
│ ├── client.py
│ ├── cookiejar.py
│ ├── cookies.py
│ └── server.py
├── libfuturize
│ ├── __init__.py
│ ├── fixer_util.py
│ ├── fixes
│ │ ├── __init__.py
│ │ ├── fix_UserDict.py
│ │ ├── fix_absolute_import.py
│ │ ├── fix_add__future__imports_except_unicode_literals.py
│ │ ├── fix_basestring.py
│ │ ├── fix_bytes.py
│ │ ├── fix_cmp.py
│ │ ├── fix_division.py
│ │ ├── fix_division_safe.py
│ │ ├── fix_execfile.py
│ │ ├── fix_future_builtins.py
│ │ ├── fix_future_standard_library.py
│ │ ├── fix_future_standard_library_urllib.py
│ │ ├── fix_input.py
│ │ ├── fix_metaclass.py
│ │ ├── fix_next_call.py
│ │ ├── fix_object.py
│ │ ├── fix_oldstr_wrap.py
│ │ ├── fix_order___future__imports.py
│ │ ├── fix_print.py
│ │ ├── fix_print_with_import.py
│ │ ├── fix_raise.py
│ │ ├── fix_remove_old__future__imports.py
│ │ ├── fix_unicode_keep_u.py
│ │ ├── fix_unicode_literals_import.py
│ │ └── fix_xrange_with_import.py
│ └── main.py
├── libpasteurize
│ ├── __init__.py
│ ├── fixes
│ │ ├── __init__.py
│ │ ├── feature_base.py
│ │ ├── fix_add_all__future__imports.py
│ │ ├── fix_add_all_future_builtins.py
│ │ ├── fix_add_future_standard_library_import.py
│ │ ├── fix_annotations.py
│ │ ├── fix_division.py
│ │ ├── fix_features.py
│ │ ├── fix_fullargspec.py
│ │ ├── fix_future_builtins.py
│ │ ├── fix_getcwd.py
│ │ ├── fix_imports.py
│ │ ├── fix_imports2.py
│ │ ├── fix_kwargs.py
│ │ ├── fix_memoryview.py
│ │ ├── fix_metaclass.py
│ │ ├── fix_newstyle.py
│ │ ├── fix_next.py
│ │ ├── fix_printfunction.py
│ │ ├── fix_raise.py
│ │ ├── fix_raise_.py
│ │ ├── fix_throw.py
│ │ └── fix_unpacking.py
│ └── main.py
├── past
│ ├── __init__.py
│ ├── builtins
│ │ ├── __init__.py
│ │ ├── misc.py
│ │ └── noniterators.py
│ ├── translation
│ │ └── __init__.py
│ ├── types
│ │ ├── __init__.py
│ │ ├── basestring.py
│ │ ├── olddict.py
│ │ └── oldstr.py
│ └── utils
│ │ └── __init__.py
├── queue
│ └── __init__.py
├── reprlib
│ └── __init__.py
├── socketserver
│ └── __init__.py
├── tkinter
│ ├── __init__.py
│ ├── colorchooser.py
│ ├── commondialog.py
│ ├── constants.py
│ ├── dialog.py
│ ├── dnd.py
│ ├── filedialog.py
│ ├── font.py
│ ├── messagebox.py
│ ├── scrolledtext.py
│ ├── simpledialog.py
│ ├── tix.py
│ └── ttk.py
├── winreg
│ └── __init__.py
└── xmlrpc
│ ├── __init__.py
│ ├── client.py
│ └── server.py
├── test.sh
└── tests
├── test_future
├── __init__.py
├── test_backports.py
├── test_buffer.py
├── test_builtins.py
├── test_builtins_explicit_import.py
├── test_bytes.py
├── test_chainmap.py
├── test_common_iterators.py
├── test_count.py
├── test_decorators.py
├── test_dict.py
├── test_email_generation.py
├── test_email_multipart.py
├── test_explicit_imports.py
├── test_futurize.py
├── test_html.py
├── test_htmlparser.py
├── test_http_cookiejar.py
├── test_httplib.py
├── test_import_star.py
├── test_imports_httplib.py
├── test_imports_urllib.py
├── test_int.py
├── test_int_old_division.py
├── test_isinstance.py
├── test_libfuturize_fixers.py
├── test_list.py
├── test_magicsuper.py
├── test_object.py
├── test_pasteurize.py
├── test_py2_str_literals_to_bytes.py
├── test_range.py
├── test_requests.py
├── test_standard_library.py
├── test_str.py
├── test_super.py
├── test_surrogateescape.py
├── test_urllib.py
├── test_urllib2.py
├── test_urllib_response.py
├── test_urllib_toplevel.py
├── test_urllibnet.py
├── test_urlparse.py
└── test_utils.py
└── test_past
├── __init__.py
├── test_basestring.py
├── test_builtins.py
├── test_misc.py
├── test_noniterators.py
├── test_olddict.py
├── test_oldstr.py
├── test_translation.py
└── test_values.py
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | ## Build documentation locally
4 |
5 | Using tox:
6 | ```shell
7 | $ tox -e docs
8 | ```
9 |
--------------------------------------------------------------------------------
/.github/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Security updates are applied only to the latest release.
6 |
7 | ## Reporting a Vulnerability
8 |
9 | If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released.
10 |
11 | Please disclose it at [security advisory](https://github.com/PythonCharmers/python-future/security/advisories/new).
12 |
13 | This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure.
14 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | pull_request:
5 | push:
6 |
7 | concurrency:
8 | group: ${{ github.head_ref || github.run_id }}
9 | cancel-in-progress: true
10 |
11 | jobs:
12 | test:
13 | strategy:
14 | fail-fast: false
15 | matrix:
16 | versions:
17 | # - python: "2.6"
18 | - python: "2.7"
19 | - python: "3.3"
20 | - python: "3.4"
21 | - python: "3.5"
22 | - python: "3.6"
23 | - python: "3.7"
24 | - python: "3.8"
25 | - python: "3.9"
26 |
27 | runs-on: ubuntu-latest
28 | steps:
29 | - uses: actions/checkout@v4
30 | - if: ${{ matrix.versions.python != '2.6' }}
31 | run: |
32 | docker build \
33 | . \
34 | --build-arg PYTHON_VERSION=${{ matrix.versions.python }} \
35 | -t jmadler/python-future-builder:${{ matrix.versions.python }}
36 | - if: ${{ matrix.versions.python == '2.6' }}
37 | run: |
38 | docker build \
39 | . \
40 | -f 2.6.Dockerfile \
41 | -t jmadler/python-future-builder:${{ matrix.versions.python }}
42 | - run: |
43 | docker run \
44 | -e PYTHON_VERSION=${{ matrix.versions.python }} \
45 | jmadler/python-future-builder:${{ matrix.versions.python }} \
46 | /root/python-future/test.sh
47 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 | .ipynb_checkpoints
3 |
4 | # VIM swap files
5 | *.sw[po]
6 |
7 | # C extensions
8 | *.so
9 |
10 | # Packages
11 | *.egg
12 | *.egg-info
13 | dist
14 | build
15 | eggs
16 | parts
17 | bin
18 | var
19 | sdist
20 | develop-eggs
21 | .installed.cfg
22 | lib
23 | lib64
24 | MANIFEST
25 | MANIFEST.in
26 |
27 | # Backup files
28 | *.bak
29 | *.backup
30 |
31 | # Installer logs
32 | pip-log.txt
33 |
34 | # Unit test / coverage reports
35 | .coverage
36 | .tox
37 | nosetests.xml
38 |
39 | # Translations
40 | *.mo
41 |
42 | # Mr Developer
43 | .mr.developer.cfg
44 | .project
45 | .pydevproject
46 |
47 | # PyCharm / IntelliJ
48 | .idea
49 |
50 | # Generated test file
51 | mytempfile.py
52 |
--------------------------------------------------------------------------------
/.pre-commit-hooks.yaml:
--------------------------------------------------------------------------------
1 | - id: futurize
2 | name: futurize
3 | description: Futurize your Py2 code to ensure it is runnable on Py3.
4 | language: python
5 | types: [python]
6 | entry: futurize -w -n --no-diffs
7 | args: [--stage1]
8 |
9 | - id: pasteurize
10 | name: pasteurize
11 | description: Pasteurize your Py3 code to ensure it is runnable on Py2.
12 | language: python
13 | language_version: python3
14 | types: [python]
15 | entry: pasteurize -w -n --no-diffs
16 |
--------------------------------------------------------------------------------
/2.6.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM mrupgrade/deadsnakes:2.6
2 |
3 | RUN mkdir -p ~/.pip/ && echo '[global] \n\
4 | trusted-host = pypi.python.org\n\
5 | pypi.org\n\
6 | files.pythonhosted.org\n\
7 | ' >> ~/.pip/pip.conf
8 |
9 | RUN apt-get update && \
10 | apt-get install -y curl
11 |
12 | RUN mkdir -p /root/pip && \
13 | cd /root/pip && \
14 | curl -O https://files.pythonhosted.org/packages/8a/e9/8468cd68b582b06ef554be0b96b59f59779627131aad48f8a5bce4b13450/wheel-0.29.0-py2.py3-none-any.whl && \
15 | curl -O https://files.pythonhosted.org/packages/31/77/3781f65cafe55480b56914def99022a5d2965a4bb269655c89ef2f1de3cd/importlib-1.0.4.zip && \
16 | curl -O https://files.pythonhosted.org/packages/ef/41/d8a61f1b2ba308e96b36106e95024977e30129355fd12087f23e4b9852a1/pytest-3.2.5-py2.py3-none-any.whl && \
17 | curl -O https://files.pythonhosted.org/packages/f2/94/3af39d34be01a24a6e65433d19e107099374224905f1e0cc6bbe1fd22a2f/argparse-1.4.0-py2.py3-none-any.whl && \
18 | curl -O https://files.pythonhosted.org/packages/72/20/7f0f433060a962200b7272b8c12ba90ef5b903e218174301d0abfd523813/unittest2-1.1.0-py2.py3-none-any.whl && \
19 | curl -O https://files.pythonhosted.org/packages/53/67/9620edf7803ab867b175e4fd23c7b8bd8eba11cb761514dcd2e726ef07da/py-1.4.34-py2.py3-none-any.whl && \
20 | curl -O https://files.pythonhosted.org/packages/53/25/ef88e8e45db141faa9598fbf7ad0062df8f50f881a36ed6a0073e1572126/ordereddict-1.1.tar.gz && \
21 | curl -O https://files.pythonhosted.org/packages/17/0a/6ac05a3723017a967193456a2efa0aa9ac4b51456891af1e2353bb9de21e/traceback2-1.4.0-py2.py3-none-any.whl && \
22 | curl -O https://files.pythonhosted.org/packages/65/26/32b8464df2a97e6dd1b656ed26b2c194606c16fe163c695a992b36c11cdf/six-1.13.0-py2.py3-none-any.whl && \
23 | curl -O https://files.pythonhosted.org/packages/c7/a3/c5da2a44c85bfbb6eebcfc1dde24933f8704441b98fdde6528f4831757a6/linecache2-1.0.0-py2.py3-none-any.whl
24 |
25 | WORKDIR /root/python-future
26 | ADD . /root/python-future
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG PYTHON_VERSION
2 | FROM python:${PYTHON_VERSION}-slim
3 |
4 | ENV LC_ALL=C.UTF-8
5 |
6 | WORKDIR /root/python-future
7 | ADD . /root/python-future
8 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) 2013-2024 Python Charmers, Australia
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include *.sh
2 | include *.txt
3 | include *.rst
4 | include *.py
5 | include .travis.yml
6 | include pytest.ini
7 | recursive-include docs LICENSE
8 | recursive-include docs README
9 | recursive-include docs *.conf
10 | recursive-include docs *.css_t
11 | recursive-include docs *.html
12 | recursive-include docs *.ico
13 | recursive-include docs *.inc
14 | recursive-include docs *.ipynb
15 | recursive-include docs *.png
16 | recursive-include docs *.py
17 | recursive-include docs *.rst
18 | recursive-include docs *.sh
19 | recursive-include docs *.tiff
20 | recursive-include docs *.txt
21 | recursive-include docs Makefile
22 | recursive-include src *.py
23 | recursive-include src *.pem
24 | recursive-include tests *.au
25 | recursive-include tests *.gif
26 | recursive-include tests *.py
27 | recursive-include tests *.txt
28 |
--------------------------------------------------------------------------------
/TESTING.txt:
--------------------------------------------------------------------------------
1 | A docker image, python-future-builder, is used to do testing and building. The test suite can be run with:
2 |
3 | $ bash build.sh
4 |
5 | which tests the module under a number of different python versions, where available, or with:
6 |
7 | $ py.test
8 |
9 | To execute a single test:
10 |
11 | $ pytest -k test_chained_exceptions_stacktrace
12 |
--------------------------------------------------------------------------------
/check_rst.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | rst2html README.rst > README.html && xdg-open README.html
3 |
--------------------------------------------------------------------------------
/docs/3rd-party-py3k-compat-code/gevent_py3k.py:
--------------------------------------------------------------------------------
1 | """
2 | From gevent/hub.py
3 | """
4 | PY3 = sys.version_info[0] >= 3
5 |
6 | if PY3:
7 | string_types = str,
8 | integer_types = int,
9 | else:
10 | string_types = basestring,
11 | integer_types = (int, long)
12 |
13 |
14 | if sys.version_info[0] <= 2:
15 | import thread
16 | else:
17 | import _thread as thread
18 |
--------------------------------------------------------------------------------
/docs/3rd-party-py3k-compat-code/numpy_py3k.py:
--------------------------------------------------------------------------------
1 | """
2 | Python 3 compatibility tools.
3 |
4 | """
5 |
6 | __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
7 | 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
8 | 'asstr', 'open_latin1']
9 |
10 | import sys
11 |
12 | if sys.version_info[0] >= 3:
13 | import io
14 | bytes = bytes
15 | unicode = str
16 |
17 | def asunicode(s):
18 | if isinstance(s, bytes):
19 | return s.decode('latin1')
20 | return str(s)
21 |
22 | def asbytes(s):
23 | if isinstance(s, bytes):
24 | return s
25 | return str(s).encode('latin1')
26 |
27 | def asstr(s):
28 | if isinstance(s, bytes):
29 | return s.decode('latin1')
30 | return str(s)
31 |
32 | def isfileobj(f):
33 | return isinstance(f, (io.FileIO, io.BufferedReader))
34 |
35 | def open_latin1(filename, mode='r'):
36 | return open(filename, mode=mode, encoding='iso-8859-1')
37 |
38 | strchar = 'U'
39 |
40 | else:
41 | bytes = str
42 | unicode = unicode
43 | asbytes = str
44 | asstr = str
45 | strchar = 'S'
46 |
47 | def isfileobj(f):
48 | return isinstance(f, file)
49 |
50 | def asunicode(s):
51 | if isinstance(s, unicode):
52 | return s
53 | return str(s).decode('ascii')
54 |
55 | def open_latin1(filename, mode='r'):
56 | return open(filename, mode=mode)
57 |
58 | def getexception():
59 | return sys.exc_info()[1]
60 |
61 | def asbytes_nested(x):
62 | if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
63 | return [asbytes_nested(y) for y in x]
64 | else:
65 | return asbytes(x)
66 |
67 | def asunicode_nested(x):
68 | if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
69 | return [asunicode_nested(y) for y in x]
70 | else:
71 | return asunicode(x)
72 |
--------------------------------------------------------------------------------
/docs/3rd-party-py3k-compat-code/statsmodels_py3k.py:
--------------------------------------------------------------------------------
1 | """
2 | Python 3 compatibility tools.
3 |
4 | """
5 |
6 | __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
7 | 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
8 | 'asstr', 'open_latin1']
9 |
10 | import sys
11 |
12 | if sys.version_info[0] >= 3:
13 | import io
14 | bytes = bytes
15 | unicode = str
16 | asunicode = str
17 | def asbytes(s):
18 | if isinstance(s, bytes):
19 | return s
20 | return s.encode('latin1')
21 | def asstr(s):
22 | if isinstance(s, str):
23 | return s
24 | return s.decode('latin1')
25 | def asstr2(s): #added JP, not in numpy version
26 | if isinstance(s, str):
27 | return s
28 | elif isinstance(s, bytes):
29 | return s.decode('latin1')
30 | else:
31 | return str(s)
32 | def isfileobj(f):
33 | return isinstance(f, io.FileIO)
34 | def open_latin1(filename, mode='r'):
35 | return open(filename, mode=mode, encoding='iso-8859-1')
36 | strchar = 'U'
37 | from io import BytesIO, StringIO #statsmodels
38 | else:
39 | bytes = str
40 | unicode = unicode
41 | asbytes = str
42 | asstr = str
43 | asstr2 = str
44 | strchar = 'S'
45 | def isfileobj(f):
46 | return isinstance(f, file)
47 | def asunicode(s):
48 | if isinstance(s, unicode):
49 | return s
50 | return s.decode('ascii')
51 | def open_latin1(filename, mode='r'):
52 | return open(filename, mode=mode)
53 | from StringIO import StringIO
54 | BytesIO = StringIO
55 |
56 | def getexception():
57 | return sys.exc_info()[1]
58 |
59 | def asbytes_nested(x):
60 | if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
61 | return [asbytes_nested(y) for y in x]
62 | else:
63 | return asbytes(x)
64 |
65 | def asunicode_nested(x):
66 | if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
67 | return [asunicode_nested(y) for y in x]
68 | else:
69 | return asunicode(x)
70 |
--------------------------------------------------------------------------------
/docs/_static/python-future-icon-32.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/docs/_static/python-future-icon-32.ico
--------------------------------------------------------------------------------
/docs/_static/python-future-icon-white-32.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/docs/_static/python-future-icon-white-32.ico
--------------------------------------------------------------------------------
/docs/_static/python-future-logo-textless-transparent.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/docs/_static/python-future-logo-textless-transparent.png
--------------------------------------------------------------------------------
/docs/_static/python-future-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/docs/_static/python-future-logo.png
--------------------------------------------------------------------------------
/docs/_static/python-future-logo.tiff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/docs/_static/python-future-logo.tiff
--------------------------------------------------------------------------------
/docs/_templates/layout.html:
--------------------------------------------------------------------------------
1 | {# Import the theme's layout. #}
2 | {% extends "!layout.html" %}
3 |
4 | {% block extrahead %}
5 | {{ super() }}
6 |
11 | {% endblock %}
12 |
13 | {% block footer %}
14 | {{ super() }}
15 |
26 | {% endblock %}
27 |
28 |
29 | {# Import the theme's layout. #}
30 |
31 |
32 | {# Include our new CSS file into existing ones. #}
33 | {% set css_files = css_files + ['_static/my-styles.css'] %}
34 |
--------------------------------------------------------------------------------
/docs/_templates/navbar.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
18 |
19 |
20 |
21 | {% if theme_navbar_links %}
22 | {%- for link in theme_navbar_links %}
23 | - {{ link[0] }}
24 | {%- endfor %}
25 | {% endif %}
26 | {% block navbartoc %}
27 | {% include "globaltoc.html" %}
28 | {% if theme_navbar_pagenav %}
29 | {% include "navbartoc.html" %}
30 | {% endif %}
31 | {% endblock %}
32 | {% if theme_navbar_sidebarrel %}
33 | {% block sidebarrel %}
34 | {% include "relations.html" %}
35 | {% endblock %}
36 | {% endif %}
37 | {% block navbarextra %}
38 | {% endblock %}
39 | {% if theme_source_link_position == "nav" %}
40 |
41 | - {%- if show_source and has_source and sourcename %}
42 | {{ _('Source') }}
44 | {%- endif %}
45 |
46 |
47 | {% endif %}
48 |
49 |
50 | {% block navbarsearch %}
51 | {% include "navbarsearchbox.html" %}
52 | {% endblock %}
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/docs/_templates/sidebarintro.html:
--------------------------------------------------------------------------------
1 |
3 | Easy, clean, reliable Python 2/3 compatibility
4 | Table of Contents
5 |
16 |
22 |
--------------------------------------------------------------------------------
/docs/_templates/sidebarlogo.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/docs/_templates/sidebartoc.html:
--------------------------------------------------------------------------------
1 | {{ toctree(maxdepth=2, collapse=True, includehidden=True) }}
2 |
--------------------------------------------------------------------------------
/docs/_themes/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2010 by Armin Ronacher.
2 |
3 | Some rights reserved.
4 |
5 | Redistribution and use in source and binary forms of the theme, with or
6 | without modification, are permitted provided that the following conditions
7 | are met:
8 |
9 | * Redistributions of source code must retain the above copyright
10 | notice, this list of conditions and the following disclaimer.
11 |
12 | * Redistributions in binary form must reproduce the above
13 | copyright notice, this list of conditions and the following
14 | disclaimer in the documentation and/or other materials provided
15 | with the distribution.
16 |
17 | * The names of the contributors may not be used to endorse or
18 | promote products derived from this software without specific
19 | prior written permission.
20 |
21 | We kindly ask you to only use these themes in an unmodified manner just
22 | for Flask and Flask-related products, not for unrelated projects. If you
23 | like the visual style and want to use it for your own projects, please
24 | consider making some larger changes to the themes (such as changing
25 | font faces, sizes, colors or margins).
26 |
27 | THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 | ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE
37 | POSSIBILITY OF SUCH DAMAGE.
38 |
--------------------------------------------------------------------------------
/docs/_themes/README:
--------------------------------------------------------------------------------
1 | Flask Sphinx Styles
2 | ===================
3 |
4 | This repository contains sphinx styles for Flask and Flask related
5 | projects. To use this style in your Sphinx documentation, follow
6 | this guide:
7 |
8 | 1. put this folder as _themes into your docs folder. Alternatively
9 | you can also use git submodules to check out the contents there.
10 | 2. add this to your conf.py:
11 |
12 | sys.path.append(os.path.abspath('_themes'))
13 | html_theme_path = ['_themes']
14 | html_theme = 'flask'
15 |
16 | The following themes exist:
17 |
18 | - 'flask' - the standard flask documentation theme for large
19 | projects
20 | - 'flask_small' - small one-page theme. Intended to be used by
21 | very small addon libraries for flask.
22 |
23 | The following options exist for the flask_small theme:
24 |
25 | [options]
26 | index_logo = '' filename of a picture in _static
27 | to be used as replacement for the
28 | h1 in the index.rst file.
29 | index_logo_height = 120px height of the index logo
30 | github_fork = '' repository name on github for the
31 | "fork me" badge
32 |
--------------------------------------------------------------------------------
/docs/_themes/future/layout.html:
--------------------------------------------------------------------------------
1 | {%- extends "basic/layout.html" %}
2 | {%- block relbar2 %}{% endblock %}
3 | {%- block footer %}
4 |
8 | {%- endblock %}
9 |
--------------------------------------------------------------------------------
/docs/_themes/future/relations.html:
--------------------------------------------------------------------------------
1 | Related Topics
2 |
20 |
--------------------------------------------------------------------------------
/docs/_themes/future/theme.conf:
--------------------------------------------------------------------------------
1 | [theme]
2 | inherit = basic
3 | stylesheet = future.css
4 |
--------------------------------------------------------------------------------
/docs/automatic_conversion.rst:
--------------------------------------------------------------------------------
1 | .. _automatic-conversion:
2 |
3 | Automatic conversion to Py2/3
4 | =============================
5 |
6 | The ``future`` source tree includes scripts called ``futurize`` and
7 | ``pasteurize`` to aid in making Python 2 code or Python 3 code compatible with
8 | both platforms (Py2/3) using the :mod:`future` module. These are based on
9 | ``lib2to3`` and use fixers from ``2to3``, ``3to2``, and ``python-modernize``.
10 |
11 | ``futurize`` passes Python 2 code through all the appropriate fixers to turn it
12 | into valid Python 3 code, and then adds ``__future__`` and ``future`` package
13 | imports.
14 |
15 | For conversions from Python 3 code to Py2/3, use the ``pasteurize`` script
16 | instead. This converts Py3-only constructs (e.g. new metaclass syntax) and adds
17 | ``__future__`` and ``future`` imports to the top of each module.
18 |
19 | In both cases, the result should be relatively clean Py3-style code that runs
20 | mostly unchanged on both Python 2 and Python 3.
21 |
22 |
23 | .. include:: futurize.rst
24 |
25 | .. include:: futurize_cheatsheet.rst
26 |
27 | .. include:: pasteurize.rst
28 |
29 | .. include:: conversion_limitations.rst
30 |
--------------------------------------------------------------------------------
/docs/bind_method.rst:
--------------------------------------------------------------------------------
1 | .. _bind-method:
2 |
3 | Binding a method to a class
4 | ---------------------------
5 |
6 | Python 2 draws a distinction between bound and unbound methods, whereas
7 | in Python 3 this distinction is gone: unbound methods have been removed
8 | from the language. To bind a method to a class compatibly across Python
9 | 3 and Python 2, you can use the :func:`bind_method` helper function::
10 |
11 | from future.utils import bind_method
12 |
13 | class Greeter(object):
14 | pass
15 |
16 | def greet(self, message):
17 | print(message)
18 |
19 | bind_method(Greeter, 'greet', greet)
20 |
21 | g = Greeter()
22 | g.greet('Hi!')
23 |
24 |
25 | On Python 3, calling ``bind_method(cls, name, func)`` is equivalent to
26 | calling ``setattr(cls, name, func)``. On Python 2 it is equivalent to::
27 |
28 | import types
29 | setattr(cls, name, types.MethodType(func, None, cls))
30 |
--------------------------------------------------------------------------------
/docs/contents.rst.inc:
--------------------------------------------------------------------------------
1 | Contents
2 | ========
3 |
4 | .. toctree::
5 | :maxdepth: 3
6 |
7 | whatsnew
8 | overview
9 | quickstart
10 | compatible_idioms
11 | imports
12 | what_else
13 | automatic_conversion
14 | faq
15 | stdlib_incompatibilities
16 | older_interfaces
17 | changelog
18 | credits
19 | reference
20 |
21 | Indices and tables
22 | ******************
23 |
24 | * :ref:`genindex`
25 | * :ref:`modindex`
26 | * :ref:`search`
27 |
--------------------------------------------------------------------------------
/docs/conversion_limitations.rst:
--------------------------------------------------------------------------------
1 | .. _futurize-limitations:
2 |
3 | Known limitations
4 | -----------------
5 |
6 | ``futurize`` and ``pasteurize`` are useful to automate much of the
7 | work of porting, particularly the boring repetitive text substitutions. They also
8 | help to flag which parts of the code require attention.
9 |
10 | Nevertheless, ``futurize`` and ``pasteurize`` are still incomplete and make
11 | some mistakes, like 2to3, on which they are based. Please report bugs on
12 | `GitHub `_. Contributions to
13 | the ``lib2to3``-based fixers for ``futurize`` and ``pasteurize`` are
14 | particularly welcome! Please see :ref:`contributing`.
15 |
16 | ``futurize`` doesn't currently make the following change automatically:
17 |
18 | 1. Strings containing ``\U`` produce a ``SyntaxError`` on Python 3. An example is::
19 |
20 | s = 'C:\Users'.
21 |
22 | Python 2 expands this to ``s = 'C:\\Users'``, but Python 3 requires a raw
23 | prefix (``r'...'``). This also applies to multi-line strings (including
24 | multi-line docstrings).
25 |
26 | Also see the tests in ``future/tests/test_futurize.py`` marked
27 | ``@expectedFailure`` or ``@skip`` for known limitations.
28 |
--------------------------------------------------------------------------------
/docs/custom_str_methods.rst:
--------------------------------------------------------------------------------
1 | .. _custom-str-methods:
2 |
3 | Custom __str__ methods
4 | ----------------------
5 |
6 | If you define a custom ``__str__`` method for any of your classes,
7 | functions like ``print()`` expect ``__str__`` on Py2 to return a byte
8 | string, whereas on Py3 they expect a (unicode) string.
9 |
10 | Use the following decorator to map the ``__str__`` to ``__unicode__`` on
11 | Py2 and define ``__str__`` to encode it as utf-8::
12 |
13 | from future.utils import python_2_unicode_compatible
14 |
15 | @python_2_unicode_compatible
16 | class MyClass(object):
17 | def __str__(self):
18 | return u'Unicode string: \u5b54\u5b50'
19 | a = MyClass()
20 |
21 | # This then prints the name of a Chinese philosopher:
22 | print(a)
23 |
24 | This decorator is identical to the decorator of the same name in
25 | :mod:`django.utils.encoding`.
26 |
27 | This decorator is a no-op on Python 3.
28 |
--------------------------------------------------------------------------------
/docs/dev_notes.rst:
--------------------------------------------------------------------------------
1 | Notes
2 | -----
3 | This module only supports Python 2.7, and Python 3.4+.
4 |
5 | The following renames are already supported on Python 2.7 without any
6 | additional work from us::
7 |
8 | reload() -> imp.reload()
9 | reduce() -> functools.reduce()
10 | StringIO.StringIO -> io.StringIO
11 | Bytes.BytesIO -> io.BytesIO
12 |
13 | Old things that can one day be fixed automatically by futurize.py::
14 |
15 | string.uppercase -> string.ascii_uppercase # works on either Py2.7 or Py3+
16 | sys.maxint -> sys.maxsize # but this isn't identical
17 |
--------------------------------------------------------------------------------
/docs/development.rst:
--------------------------------------------------------------------------------
1 | .. developer-docs
2 |
3 | Developer docs
4 | ==============
5 |
6 | The easiest way to start developing ``python-future`` is as follows:
7 |
8 | 1. Install Anaconda Python distribution
9 |
10 | 2. Run::
11 |
12 | conda install -n future2 python=2.7 pip
13 | conda install -n future3 python=3.4 pip
14 |
15 | git clone https://github.com/PythonCharmers/python-future
16 |
17 | 3. If you are using Anaconda Python distribution, this comes without a ``test``
18 | module on Python 2.x. Copy ``Python-2.7.6/Lib/test`` from the Python source tree
19 | to ``~/anaconda/envs/yourenvname/lib/python2.7/site-packages/`.
20 |
--------------------------------------------------------------------------------
/docs/func_annotations.rst:
--------------------------------------------------------------------------------
1 | .. _func_annotations:
2 |
3 | Function annotations
4 | ====================
5 |
6 | Function annotations are a piece of syntax introduced in Python 3.0 that was
7 | not backported to Python 2.x. (See PEP 3107:
8 | http://www.python.org/dev/peps/pep-3107/). They cause Python 2 to raise a
9 | SyntaxError.
10 |
11 | To rewrite Python 3 code with function annotations to be compatible with both
12 | Python 3 and Python 2, you can replace the annotation syntax with a dictionary
13 | called ``__annotations__`` as an attribute on your functions. For example, code
14 | such as this::
15 |
16 | def _parse(self, filename: str, dir='.') -> list:
17 | pass
18 |
19 | can be re-expressed like this::
20 |
21 | def _parse(self, filename, dir='.'):
22 | pass
23 | _parse.__annotations__ = {'filename': str, 'return': list}
24 |
25 | As described in PEP 3107, the annotation for a function's return value
26 | corresponds to the ``'return'`` key in the dictionary.
27 |
28 | (Note that PEP 3107 describes annotations as belonging to a
29 | ``func_annotations`` attribute. This attribute was renamed in Python 3.2 to
30 | ``__annotations__``.)
31 |
32 | Be aware that some libraries that consume function annotations, such as
33 | `Reticulated `_, have their own
34 | semantics for supporting earlier Python versions, such as decorators. If you
35 | are using such a library, please use its own mechanism for providing
36 | compatibility with earlier Python versions, rather than the generic equivalent
37 | above.
38 |
--------------------------------------------------------------------------------
/docs/future-builtins.rst:
--------------------------------------------------------------------------------
1 | .. _future-builtins:
2 |
3 | ``future.builtins``
4 | ===================
5 |
6 | The ``future.builtins`` module is also accessible as ``builtins`` on Py2.
7 |
8 | - ``pow()`` supports fractional exponents of negative numbers like in Py3::
9 |
10 | >>> from builtins import pow
11 | >>> pow(-1, 0.5)
12 | (6.123233995736766e-17+1j)
13 |
14 | - ``round()`` uses Banker's Rounding as in Py3 to the nearest even last digit::
15 |
16 | >>> from builtins import round
17 | >>> assert round(0.1250, 2) == 0.12
18 |
--------------------------------------------------------------------------------
/docs/futurize_overview.rst:
--------------------------------------------------------------------------------
1 | The ``futurize`` script passes Python 2 code through all the appropriate fixers
2 | to turn it into valid Python 3 code, and then adds ``__future__`` and
3 | ``future`` package imports to re-enable compatibility with Python 2.
4 |
5 | For example, running ``futurize`` turns this Python 2 code:
6 |
7 | .. code-block:: python
8 |
9 | import ConfigParser # Py2 module name
10 |
11 | class Upper(object):
12 | def __init__(self, iterable):
13 | self._iter = iter(iterable)
14 | def next(self): # Py2-style iterator interface
15 | return next(self._iter).upper()
16 | def __iter__(self):
17 | return self
18 |
19 | itr = Upper('hello')
20 | print next(itr),
21 | for letter in itr:
22 | print letter, # Py2-style print statement
23 |
24 | into this code which runs on both Py2 and Py3:
25 |
26 | .. code-block:: python
27 |
28 | from __future__ import print_function
29 | from future import standard_library
30 | standard_library.install_aliases()
31 | from future.builtins import next
32 | from future.builtins import object
33 | import configparser # Py3-style import
34 |
35 | class Upper(object):
36 | def __init__(self, iterable):
37 | self._iter = iter(iterable)
38 | def __next__(self): # Py3-style iterator interface
39 | return next(self._iter).upper()
40 | def __iter__(self):
41 | return self
42 |
43 | itr = Upper('hello')
44 | print(next(itr), end=' ') # Py3-style print function
45 | for letter in itr:
46 | print(letter, end=' ')
47 |
48 |
49 | To write out all the changes to your Python files that ``futurize`` suggests,
50 | use the ``-w`` flag.
51 |
52 | For complex projects, it is probably best to divide the porting into two stages.
53 | Stage 1 is for "safe" changes that modernize the code but do not break Python
54 | 2.7 compatibility or introduce a dependency on the ``future`` package. Stage 2
55 | is to complete the process.
56 |
--------------------------------------------------------------------------------
/docs/hindsight.rst:
--------------------------------------------------------------------------------
1 | In a perfect world, the new metaclass syntax should ideally be available in
2 | Python 2 as a `__future__`` import like ``from __future__ import
3 | new_metaclass_syntax``.
4 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | Easy, clean, reliable Python 2/3 compatibility
2 | ==============================================
3 |
4 | ``python-future`` is the missing compatibility layer between Python 2 and
5 | Python 3. It allows you to use a single, clean Python 3.x-compatible
6 | codebase to support both Python 2 and Python 3 with minimal overhead.
7 |
8 |
9 | .. include:: contents.rst.inc
10 |
--------------------------------------------------------------------------------
/docs/int_object.rst:
--------------------------------------------------------------------------------
1 | .. _int-object:
2 |
3 | int
4 | ---
5 |
6 | Python 3's ``int`` type is very similar to Python 2's ``long``, except
7 | for the representation (which omits the ``L`` suffix in Python 2). Python
8 | 2's usual (short) integers have been removed from Python 3, as has the
9 | ``long`` builtin name.
10 |
11 | Python 3::
12 |
13 | >>> 2**64
14 | 18446744073709551616
15 |
16 | Python 2::
17 |
18 | >>> 2**64
19 | 18446744073709551616L
20 |
21 | ``future`` includes a backport of Python 3's ``int`` that
22 | is a subclass of Python 2's ``long`` with the same representation
23 | behaviour as Python 3's ``int``. To ensure an integer is long compatibly with
24 | both Py3 and Py2, cast it like this::
25 |
26 | >>> from builtins import int
27 | >>> must_be_a_long_integer = int(1234)
28 |
29 | The backported ``int`` object helps with writing doctests and simplifies code
30 | that deals with ``long`` and ``int`` as special cases on Py2. An example is the
31 | following code from ``xlwt-future`` (called by the ``xlwt.antlr.BitSet`` class)
32 | for writing out Excel ``.xls`` spreadsheets. With ``future``, the code is::
33 |
34 | from builtins import int
35 |
36 | def longify(data):
37 | """
38 | Turns data (an int or long, or a list of ints or longs) into a
39 | list of longs.
40 | """
41 | if not data:
42 | return [int(0)]
43 | if not isinstance(data, list):
44 | return [int(data)]
45 | return list(map(int, data))
46 |
47 |
48 | Without ``future`` (or with ``future`` < 0.7), this might be::
49 |
50 | def longify(data):
51 | """
52 | Turns data (an int or long, or a list of ints or longs) into a
53 | list of longs.
54 | """
55 | if not data:
56 | if PY3:
57 | return [0]
58 | else:
59 | return [long(0)]
60 | if not isinstance(data,list):
61 | if PY3:
62 | return [int(data)]
63 | else:
64 | return [long(data)]
65 | if PY3:
66 | return list(map(int, data)) # same as returning data, but with up-front typechecking
67 | else:
68 | return list(map(long, data))
69 |
--------------------------------------------------------------------------------
/docs/limitations.rst:
--------------------------------------------------------------------------------
1 | limitations of the ``future`` module and differences between Py2 and Py3 that are not (yet) handled
2 | ===================================================================================================
3 |
4 | The following attributes on functions in Python 3 are not provided in Python
5 | 2.7:
6 |
7 | __func__: see six.get_method_function()
8 | __self__: see six.get_method_self()
9 | __self__.__class__
10 |
11 |
12 | Limitations of the ``futurize`` script
13 | --------------------------------------
14 | The ``futurize`` script is not yet mature; like ``2to3``, on which it is based,
15 | it makes mistakes. Nevertheless, it should be useful for automatically
16 | performing a lot of the repetitive code-substitution tasks when porting from
17 | Py2 to Py2/3.
18 |
19 | Some new Python 3.3 features that cause SyntaxErrors on earlier versions
20 | are not currently handled by the ``futurize`` script. This includes:
21 |
22 | - ``yield ... from`` syntax for generators in Py3.3
23 |
24 | - ``raise ... from`` syntax for exceptions. (This is simple to fix
25 | manually by creating a temporary variable.)
26 |
27 | Also:
28 |
29 | - Usage of ``file('myfile', 'w')`` as a synonym for ``open`` doesn't seem
30 | to be converted currently.
31 |
32 | - ``isinstance(var, basestring)`` should sometimes be converted to
33 | ``isinstance(var, str) or isinstance(var, bytes)``, or sometimes simply
34 | ``isinstance(var, str)``, depending on the context. Currently it is always
35 | converted to ``isinstance(var, str)``.
36 |
37 | - Caveats with bytes indexing!::
38 |
39 | b'\x00'[0] != 0
40 | b'\x01'[0] != 1
41 |
42 | ``futurize`` does not yet wrap all byte-string literals in a ``bytes()``
43 | call. This is on the to-do list. See :ref:`bytes-object` for more information.
44 |
45 |
46 | Notes
47 | -----
48 | - Ensure you are using new-style classes on Py2. Py3 doesn't require
49 | inheritance from ``object`` for this, but Py2 does. ``pasteurize``
50 | adds this back in automatically, but ensure you do this too
51 | when writing your classes, otherwise weird breakage when e.g. calling
52 | ``super()`` may occur.
53 |
--------------------------------------------------------------------------------
/docs/metaclasses.rst:
--------------------------------------------------------------------------------
1 | Metaclasses
2 | -----------
3 |
4 | Python 3 and Python 2 syntax for metaclasses are incompatible.
5 | ``future`` provides a function (from ``jinja2/_compat.py``) called
6 | :func:`with_metaclass` that can assist with specifying metaclasses
7 | portably across Py3 and Py2. Use it like this::
8 |
9 | from future.utils import with_metaclass
10 |
11 | class BaseForm(object):
12 | pass
13 |
14 | class FormType(type):
15 | pass
16 |
17 | class Form(with_metaclass(FormType, BaseForm)):
18 | pass
19 |
--------------------------------------------------------------------------------
/docs/open_function.rst:
--------------------------------------------------------------------------------
1 | .. _open-function:
2 |
3 | open()
4 | ------
5 |
6 | The Python 3 builtin :func:`open` function for opening files returns file
7 | contents as (unicode) strings unless the binary (``b``) flag is passed, as in::
8 |
9 | open(filename, 'rb')
10 |
11 | in which case its methods like :func:`read` return Py3 :class:`bytes` objects.
12 |
13 | On Py2 with ``future`` installed, the :mod:`builtins` module provides an
14 | ``open`` function that is mostly compatible with that on Python 3 (e.g. it
15 | offers keyword arguments like ``encoding``). This maps to the ``open`` backport
16 | available in the standard library :mod:`io` module on Py2.7.
17 |
18 | One difference to be aware of between the Python 3 ``open`` and
19 | ``future.builtins.open`` on Python 2 is that the return types of methods such
20 | as :func:`read()` from the file object that ``open`` returns are not
21 | automatically cast from native bytes or unicode strings on Python 2 to the
22 | corresponding ``future.builtins.bytes`` or ``future.builtins.str`` types. If you
23 | need the returned data to behave the exactly same way on Py2 as on Py3, you can
24 | cast it explicitly as follows::
25 |
26 | from __future__ import unicode_literals
27 | from builtins import open, bytes
28 |
29 | data = open('image.png', 'rb').read()
30 | # On Py2, data is a standard 8-bit str with loose Unicode coercion.
31 | # data + u'' would likely raise a UnicodeDecodeError
32 |
33 | data = bytes(data)
34 | # Now it behaves like a Py3 bytes object...
35 |
36 | assert data[:4] == b'\x89PNG'
37 | assert data[4] == 13 # integer
38 | # Raises TypeError:
39 | # data + u''
40 |
--------------------------------------------------------------------------------
/docs/other/fix_notebook_html_colour.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | A script to re-enable colour in .html files produced from IPython notebooks.
6 |
7 | Based on a script in a GitHub gist with this copyright notice:
8 |
9 | #----------------------------------------------------------------------------
10 | # Copyright (c) 2013 - Damián Avila
11 | #
12 | # Distributed under the terms of the Modified BSD License.
13 | #
14 | # A little snippet to fix @media print issue printing slides from IPython
15 | #-----------------------------------------------------------------------------
16 | """
17 |
18 | import io
19 | import sys
20 |
21 | notebook = sys.argv[1]
22 | assert notebook.endswith('.html')
23 | # notebook = 'jevans.ipynb'
24 | path = notebook[:-5] + '.html'
25 | flag = u'@media print{*{text-shadow:none !important;color:#000 !important'
26 |
27 | with io.open(path, 'r') as in_file:
28 | data = in_file.readlines()
29 | for i, line in enumerate(data):
30 | if line[:64] == flag:
31 | data[i] = data[i].replace('color:#000 !important;', '')
32 |
33 | with io.open(path, 'w') as out_file:
34 | out_file.writelines(data)
35 |
36 | print("You can now print your slides")
37 |
--------------------------------------------------------------------------------
/docs/other/lessons.txt:
--------------------------------------------------------------------------------
1 | The escape() function in this file in Django 1.4:
2 |
3 | /home/user/VirtualEnvs/mezzanine/local/lib/python2.7/site-packages/django/utils/html.py
4 |
5 | atttempts to use the unicode replace method with byte strings. This
6 | causes this exception when running the Mezzanine tests using the newstr
7 | object:
8 |
9 | File "/home/user/VirtualEnvs/mezzanine/local/lib/python2.7/site-packages/django/utils/html.py", line 36, in escape
10 | return mark_safe(force_unicode(html).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", '''))
11 | File "/home/user/VirtualEnvs/mezzanine/local/lib/python2.7/site-packages/future-0.9.0_dev-py2.7.egg/future/builtins/backports/__init__.py", line 145, in wrapper
12 | raise TypeError(errmsg.format(mytype))
13 | TypeError: argument can't be
14 |
15 |
16 | Comment to add to prevent Pylint from issuing warnings on ``from
17 | future.builtins import *``:
18 |
19 | # pylint: disable=W0622,W0401
20 |
21 | INCOMPATIBLE: array.array()
22 |
23 | Python 2:
24 | >>> array.array(b'b')
25 | array.array(b'b')
26 |
27 | >>> array.array(u'u')
28 | TypeError: must be char, not unicode
29 |
30 | Python 3:
31 | >>> array.array(b'b')
32 | TypeError: must be a unicode character, not bytes
33 |
34 | >>> array.array(u'b')
35 | array('b')
36 |
37 | Maybe use on Py2:
38 | >>> array.array(u'b'.encode('ascii')) ??
39 |
40 | Long int syntax (e.g. 1000000L) is incompatible with Py3.
41 | We probably shouldn't shadow int with long on Py2 because then isinstance(1, int) is False
42 |
43 | Python 2's bytes object is nothing like Python 3's bytes object!
44 | Running test_bytes.py from Py3 on Py2 (after fixing imports) gives this:
45 |
46 | --------------------------------------------------------------
47 | Ran 203 tests in 0.209s
48 |
49 | FAILED (failures=31, errors=55, skipped=1)
50 |
--------------------------------------------------------------------------------
/docs/other/todo.txt:
--------------------------------------------------------------------------------
1 | Import open() from codecs to shadow the Py2 open()?
2 |
--------------------------------------------------------------------------------
/docs/other/upload_future_docs.sh:
--------------------------------------------------------------------------------
1 | # On the local machine
2 |
3 | git checkout v0.16.0 # or whatever
4 | rm -Rf docs/build/
5 | cd docs; make html
6 | cp cheatsheet.pdf ~/shared/
7 | cd build
8 | touch ~/shared/python-future-html-docs.zip
9 | rm ~/shared/python-future-html-docs.zip
10 | zip -r ~/shared/python-future-html-docs.zip *
11 |
12 | scp ~/shared/python-future-html-docs.zip ubuntu@python-future.org:
13 | scp ~/shared/cheatsheet.pdf ubuntu@python-future.org:
14 | ssh ubuntu@python-future.org
15 |
16 |
17 | # On the remote machine:
18 |
19 | cd /var/www/python-future.org/
20 | unzip -o ~/python-future-html-docs.zip
21 | chmod a+r * html/* html/_static/*
22 | cp ~/cheatsheet.pdf ./html/compatible_idioms.pdf
23 | cp ~/cheatsheet.pdf ./html/cheatsheet.pdf
24 |
--------------------------------------------------------------------------------
/docs/overview.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../README.rst
2 |
--------------------------------------------------------------------------------
/docs/pasteurize.rst:
--------------------------------------------------------------------------------
1 | .. _backwards-conversion:
2 |
3 | ``pasteurize``: Py3 to Py2/3
4 | ----------------------------
5 |
6 | Running ``pasteurize -w mypy3module.py`` turns this Python 3 code::
7 |
8 | import configparser
9 | import copyreg
10 |
11 | class Blah:
12 | pass
13 | print('Hello', end=None)
14 |
15 | into this code which runs on both Py2 and Py3::
16 |
17 | from __future__ import print_function
18 | from future import standard_library
19 | standard_library.install_hooks()
20 |
21 | import configparser
22 | import copyreg
23 |
24 | class Blah(object):
25 | pass
26 | print('Hello', end=None)
27 |
28 | Notice that both ``futurize`` and ``pasteurize`` create explicit new-style
29 | classes that inherit from ``object`` on both Python versions, and both
30 | refer to stdlib modules (as well as builtins) under their Py3 names.
31 |
32 | Note also that the ``configparser`` module is a special case; there is a full
33 | backport available on PyPI (https://pypi.org/project/configparser/), so, as
34 | of v0.16.0, ``python-future`` no longer provides a ``configparser`` package
35 | alias. To use the resulting code on Py2, install the ``configparser`` backport
36 | with ``pip install configparser`` or by adding it to your ``requirements.txt``
37 | file.
38 |
39 | ``pasteurize`` also handles the following Python 3 features:
40 |
41 | - keyword-only arguments
42 | - metaclasses (using :func:`~future.utils.with_metaclass`)
43 | - extended tuple unpacking (PEP 3132)
44 |
45 | To handle function annotations (PEP 3107), see :ref:`func_annotations`.
46 |
--------------------------------------------------------------------------------
/docs/reference.rst:
--------------------------------------------------------------------------------
1 | API Reference (in progress)
2 | ***************************
3 |
4 | **NOTE: This page is still a work in progress... We need to go through our
5 | docstrings and make them sphinx-compliant, and figure out how to improve
6 | formatting with the sphinx-bootstrap-theme plugin. Pull requests would be
7 | very welcome.**
8 |
9 |
10 | .. contents::
11 | :local:
12 | :depth: 2
13 |
14 | future.builtins Interface
15 | =========================
16 |
17 | .. automodule:: future.builtins
18 | :members:
19 |
20 | .. Docs are also in future-builtins.rst. Extract these and put them into the
21 | .. relevant docstrings.
22 |
23 |
24 | Backported types from Python 3
25 | ==============================
26 |
27 | .. automodule:: future.types
28 | :members:
29 |
30 |
31 | future.standard_library Interface
32 | =================================
33 |
34 | .. automodule:: future.standard_library
35 | :members:
36 |
37 |
38 | future.utils Interface
39 | ======================
40 |
41 | .. automodule:: future.utils
42 | :members:
43 |
44 |
45 | past.builtins Interface
46 | =========================
47 |
48 | .. automodule:: past.builtins
49 | :members:
50 |
51 | .. Docs are also in future-builtins.rst. Extract these and put them into the
52 | .. relevant docstrings.
53 |
54 |
55 | Forward-ported types from Python 2
56 | ==================================
57 |
58 | .. automodule:: past.types
59 | :members:
60 |
61 |
62 |
63 | .. bytes
64 | .. -----
65 | .. .. automodule:: future.types.newbytes
66 | ..
67 | .. dict
68 | .. -----
69 | .. .. automodule:: future.types.newdict
70 | ..
71 | .. int
72 | .. ---
73 | .. .. automodule:: future.builtins.backports.newint
74 | ..
75 | .. range
76 | .. -----
77 | .. .. automodule:: future.types.newrange
78 | ..
79 | .. str
80 | .. ---
81 | .. .. automodule:: future.types.newstr
82 |
--------------------------------------------------------------------------------
/docs/requirements.txt:
--------------------------------------------------------------------------------
1 | sphinx==3.2.1
2 | Pallets-Sphinx-Themes==2.2.1
3 | setuptools==70.0.0
4 |
--------------------------------------------------------------------------------
/docs/roadmap.rst:
--------------------------------------------------------------------------------
1 | Development roadmap
2 | ===================
3 |
4 | futurize script
5 | ---------------
6 |
7 | 1. "Safe" mode -- from Py2 to modern Py2 or Py3 to more-compatible Py3
8 |
9 | - Split the fixers into two categories: safe and bold
10 | - Safe is highly unlikely to break existing Py2 or Py3 support. The
11 | output of this still requires :mod:`future` imports. Examples:
12 |
13 | - Compatible metaclass syntax on Py3
14 | - Explicit inheritance from object on Py3
15 |
16 | - Bold might make assumptions about which strings on Py2 should be
17 | unicode strings and which should be bytestrings.
18 |
19 | - We should also build up a database of which standard library
20 | interfaces on Py2 and Py3 accept unicode strings versus
21 | byte-strings, which have changed, and which haven't.
22 |
23 | 2. Windows support
24 |
25 | future package
26 | --------------
27 |
28 | - [Done] Add more tests for bytes ... preferably all from test_bytes.py in Py3.3.
29 | - [Done] Add remove_hooks() and install_hooks() as functions in the
30 | :mod:`future.standard_library` module. (See the uprefix module for how
31 | to do this.)
32 |
33 | Experimental:
34 | - Add::
35 |
36 | from future import bytes_literals
37 | from future import new_metaclass_syntax
38 | from future import new_style_classes
39 |
40 | - [Done] Maybe::
41 |
42 | from future.builtins import str
43 |
44 | should import a custom str is a Py3 str-like object which inherits from unicode and
45 | removes the decode() method and has any other Py3-like behaviours
46 | (possibly stricter casting?)
47 |
--------------------------------------------------------------------------------
/docs/upgrading.rst:
--------------------------------------------------------------------------------
1 | .. upgrading
2 |
3 | Upgrading
4 | *********
5 |
6 | We strive to support compatibility between versions of ``python-future``. Part of this involves keeping around old interfaces and marking them as deprecated for a period to allow projects to transition in a straightforward manner to using the new interfaces.
7 |
8 |
9 | .. upgrading-to-v0.12
10 |
11 | Upgrading to v0.12
12 | ==================
13 |
--------------------------------------------------------------------------------
/docs/utilities.rst:
--------------------------------------------------------------------------------
1 | .. _utilities-guide:
2 |
3 | Utilities
4 | ---------
5 |
6 | :mod:`future` also provides some useful functions and decorators to ease
7 | backward compatibility with Py2 in the :mod:`future.utils` and
8 | :mod:`past.utils` modules. These are a selection of the most useful functions
9 | from ``six`` and various home-grown Py2/3 compatibility modules from popular
10 | Python projects, such as Jinja2, Pandas, IPython, and Django. The goal is to
11 | consolidate these in one place, tested and documented, obviating the need for
12 | every project to repeat this work.
13 |
14 | Examples::
15 |
16 | # Functions like print() expect __str__ on Py2 to return a byte
17 | # string. This decorator maps the __str__ to __unicode__ on Py2 and
18 | # defines __str__ to encode it as utf-8:
19 |
20 | from future.utils import python_2_unicode_compatible
21 |
22 | @python_2_unicode_compatible
23 | class MyClass(object):
24 | def __str__(self):
25 | return u'Unicode string: \u5b54\u5b50'
26 | a = MyClass()
27 |
28 | # This then prints the Chinese characters for Confucius:
29 | print(a)
30 |
31 |
32 | # Iterators on Py3 require a __next__() method, whereas on Py2 this
33 | # is called next(). This decorator allows Py3-style iterators to work
34 | # identically on Py2:
35 |
36 | @implements_iterator
37 | class Upper(object):
38 | def __init__(self, iterable):
39 | self._iter = iter(iterable)
40 | def __next__(self): # note the Py3 interface
41 | return next(self._iter).upper()
42 | def __iter__(self):
43 | return self
44 |
45 | print(list(Upper('hello')))
46 | # prints ['H', 'E', 'L', 'L', 'O']
47 |
48 | On Python 3 these decorators are no-ops.
49 |
--------------------------------------------------------------------------------
/docs/what_else.rst:
--------------------------------------------------------------------------------
1 | .. _what-else:
2 |
3 | What else you need to know
4 | **************************
5 |
6 | The following points are important to know about when writing Python 2/3
7 | compatible code.
8 |
9 | .. _what-else-essentials:
10 |
11 | .. include:: bytes_object.rst
12 | .. include:: str_object.rst
13 | .. include:: dict_object.rst
14 | .. include:: int_object.rst
15 | .. include:: isinstance.rst
16 | .. include:: open_function.rst
17 | .. include:: custom_str_methods.rst
18 | .. include:: custom_iterators.rst
19 |
20 | .. _what-else-advanced:
21 |
22 | .. include:: bind_method.rst
23 | .. include:: metaclasses.rst
24 |
25 | ..
26 |
--------------------------------------------------------------------------------
/docs/whatsnew.rst:
--------------------------------------------------------------------------------
1 | .. _whats-new:
2 |
3 | What's New
4 | **********
5 |
6 | What's new in version 1.0.0 (2024-02-21)
7 | ========================================
8 |
9 | The new version number of 1.0.0 indicates that the python-future project, like
10 | Python 2, is now done.
11 |
12 | The most important change in this release is adding support for Python 3.12
13 | (ba1cc50 and a6222d2 and bcced95).
14 |
15 | This release also includes these fixes:
16 |
17 | - Small updates to the docs
18 | - Add SECURITY.md describing security policy (0598d1b)
19 | - Fix pasteurize: NameError: name 'unicode' is not defined (de68c10)
20 | - Move CI to GitHub Actions (8cd11e8)
21 | - Add setuptools to requirements for building docs (0c347ff)
22 | - Fix typos in docs (350e87a)
23 | - Make the fix_unpacking fixer more robust (de68c10)
24 | - Small improvements to shell scripts according to shellcheck (6153844)
25 |
26 |
27 | Previous versions
28 | =================
29 |
30 | See :ref:`whats-old`.
31 |
--------------------------------------------------------------------------------
/docs/why_python3.rst:
--------------------------------------------------------------------------------
1 | .. _why-python3:
2 |
3 | Why Python 3?
4 | =============
5 |
6 | - Python 2.7 is the final Python 2.x release. Python 3.x is the future.
7 | The Python ecosystem needs to consolidate. A split or schism between
8 | different incompatible versions is not healthy for growing the
9 | community.
10 | - Function annotations
11 | - Decimal module 100x faster. As fast as floats.
12 | - Easier to learn. (Less cruft in language and stdlib, more consistency, better docstrings, etc.)
13 | - Much safer handling of unicode text and encodings: fewer bugs.
14 | - More memory efficiency (shared dict keys (PEP 412) and space-efficient
15 | Unicode representation (PEP 393))
16 | - Exception chaining
17 |
18 | Why are Unicode strings better on Python 3?
19 | -------------------------------------------
20 |
21 | - it is not the default string type (you have to prefix the string
22 | with a u to get Unicode);
23 |
24 | - it is missing some functionality, e.g. casefold;
25 |
26 | - there are two distinct implementations, narrow builds and wide builds;
27 |
28 | - wide builds take up to four times more memory per string as needed;
29 |
30 | - narrow builds take up to two times more memory per string as needed;
31 |
32 | - worse, narrow builds have very naive (possibly even "broken")
33 | handling of code points in the Supplementary Multilingual Planes.
34 |
35 | The unicode string type in Python 3 is better because:
36 |
37 | - it is the default string type;
38 |
39 | - it includes more functionality;
40 |
41 | - starting in Python 3.3, it gets rid of the distinction between
42 | narrow and wide builds;
43 |
44 | - which reduces the memory overhead of strings by up to a factor
45 | of four in many cases;
46 |
47 | - and fixes the issue of SMP code points.
48 |
49 | (quote from a mailing list post by Steve D'Aprano on 2014-01-17).
50 |
51 |
52 | New features
53 | ------------
54 |
55 | Standard library:
56 | ~~~~~~~~~~~~~~~~~
57 |
58 | - SSL contexts in http.client
59 | -
60 |
61 |
62 |
63 | Non-arguments for Python 3
64 | ==========================
65 |
66 | -
67 |
--------------------------------------------------------------------------------
/futurize.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | futurize.py
4 | ===========
5 |
6 | This script is only used by the unit tests. Another script called
7 | "futurize" is created automatically (without the .py extension) by
8 | setuptools.
9 |
10 | futurize.py attempts to turn Py2 code into valid, clean Py3 code that is
11 | also compatible with Py2 when using the ``future`` package.
12 |
13 |
14 | Licensing
15 | ---------
16 | Copyright 2013-2024 Python Charmers, Australia.
17 | The software is distributed under an MIT licence. See LICENSE.txt.
18 | """
19 |
20 | import sys
21 |
22 | from libfuturize.main import main
23 |
24 | sys.exit(main())
25 |
--------------------------------------------------------------------------------
/pasteurize.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | pasteurize.py
4 | =============
5 |
6 | This script is only used by the unit tests. Another script called "pasteurize"
7 | is created automatically (without the .py extension) by setuptools.
8 |
9 | pasteurize.py attempts to turn Py3 code into relatively clean Py3 code that is
10 | also compatible with Py2 when using the ``future`` package.
11 |
12 |
13 | Licensing
14 | ---------
15 | Copyright 2013-2024 Python Charmers, Australia.
16 | The software is distributed under an MIT licence. See LICENSE.txt.
17 | """
18 |
19 | import sys
20 |
21 | from libpasteurize.main import main
22 |
23 | sys.exit(main())
24 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | # py.test config file
2 | [pytest]
3 | norecursedirs = build docs/_build disabled_test_email disabled_test_xmlrpc disabled_test_xmlrpcnet disabled/* disabled* disabled/test_email/*
4 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | license_file = LICENSE.txt
3 |
--------------------------------------------------------------------------------
/src/__init__.py:
--------------------------------------------------------------------------------
1 | # Make this a package only for the sake of importing
2 | # src.future.__version__ etc. from setup.py
3 |
--------------------------------------------------------------------------------
/src/_dummy_thread/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 | __future_module__ = True
4 |
5 | if sys.version_info[0] < 3:
6 | from dummy_thread import *
7 | else:
8 | raise ImportError('This package should not be accessible on Python 3. '
9 | 'Either you are trying to run from the python-future src folder '
10 | 'or your installation of python-future is corrupted.')
11 |
--------------------------------------------------------------------------------
/src/_markupbase/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 | __future_module__ = True
4 |
5 | if sys.version_info[0] < 3:
6 | from markupbase import *
7 | else:
8 | raise ImportError('This package should not be accessible on Python 3. '
9 | 'Either you are trying to run from the python-future src folder '
10 | 'or your installation of python-future is corrupted.')
11 |
--------------------------------------------------------------------------------
/src/_thread/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 | __future_module__ = True
4 |
5 | if sys.version_info[0] < 3:
6 | from thread import *
7 | else:
8 | raise ImportError('This package should not be accessible on Python 3. '
9 | 'Either you are trying to run from the python-future src folder '
10 | 'or your installation of python-future is corrupted.')
11 |
--------------------------------------------------------------------------------
/src/builtins/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 | __future_module__ = True
4 |
5 | if sys.version_info[0] < 3:
6 | from __builtin__ import *
7 | # Overwrite any old definitions with the equivalent future.builtins ones:
8 | from future.builtins import *
9 | else:
10 | raise ImportError('This package should not be accessible on Python 3. '
11 | 'Either you are trying to run from the python-future src folder '
12 | 'or your installation of python-future is corrupted.')
13 |
--------------------------------------------------------------------------------
/src/copyreg/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] < 3:
5 | from copy_reg import *
6 | else:
7 | raise ImportError('This package should not be accessible on Python 3. '
8 | 'Either you are trying to run from the python-future src folder '
9 | 'or your installation of python-future is corrupted.')
10 |
--------------------------------------------------------------------------------
/src/future/backports/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | future.backports package
3 | """
4 |
5 | from __future__ import absolute_import
6 |
7 | import sys
8 |
9 | __future_module__ = True
10 | from future.standard_library import import_top_level_modules
11 |
12 |
13 | if sys.version_info[0] >= 3:
14 | import_top_level_modules()
15 |
16 |
17 | from .misc import (ceil,
18 | OrderedDict,
19 | Counter,
20 | ChainMap,
21 | check_output,
22 | count,
23 | recursive_repr,
24 | _count_elements,
25 | cmp_to_key
26 | )
27 |
--------------------------------------------------------------------------------
/src/future/backports/email/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2001-2007 Python Software Foundation
2 | # Author: Barry Warsaw
3 | # Contact: email-sig@python.org
4 |
5 | """
6 | Backport of the Python 3.3 email package for Python-Future.
7 |
8 | A package for parsing, handling, and generating email messages.
9 | """
10 | from __future__ import unicode_literals
11 | from __future__ import division
12 | from __future__ import absolute_import
13 |
14 | # Install the surrogate escape handler here because this is used by many
15 | # modules in the email package.
16 | from future.utils import surrogateescape
17 | surrogateescape.register_surrogateescape()
18 | # (Should this be done globally by ``future``?)
19 |
20 |
21 | __version__ = '5.1.0'
22 |
23 | __all__ = [
24 | 'base64mime',
25 | 'charset',
26 | 'encoders',
27 | 'errors',
28 | 'feedparser',
29 | 'generator',
30 | 'header',
31 | 'iterators',
32 | 'message',
33 | 'message_from_file',
34 | 'message_from_binary_file',
35 | 'message_from_string',
36 | 'message_from_bytes',
37 | 'mime',
38 | 'parser',
39 | 'quoprimime',
40 | 'utils',
41 | ]
42 |
43 |
44 |
45 | # Some convenience routines. Don't import Parser and Message as side-effects
46 | # of importing email since those cascadingly import most of the rest of the
47 | # email package.
48 | def message_from_string(s, *args, **kws):
49 | """Parse a string into a Message object model.
50 |
51 | Optional _class and strict are passed to the Parser constructor.
52 | """
53 | from future.backports.email.parser import Parser
54 | return Parser(*args, **kws).parsestr(s)
55 |
56 | def message_from_bytes(s, *args, **kws):
57 | """Parse a bytes string into a Message object model.
58 |
59 | Optional _class and strict are passed to the Parser constructor.
60 | """
61 | from future.backports.email.parser import BytesParser
62 | return BytesParser(*args, **kws).parsebytes(s)
63 |
64 | def message_from_file(fp, *args, **kws):
65 | """Read a file and parse its contents into a Message object model.
66 |
67 | Optional _class and strict are passed to the Parser constructor.
68 | """
69 | from future.backports.email.parser import Parser
70 | return Parser(*args, **kws).parse(fp)
71 |
72 | def message_from_binary_file(fp, *args, **kws):
73 | """Read a binary file and parse its contents into a Message object model.
74 |
75 | Optional _class and strict are passed to the Parser constructor.
76 | """
77 | from future.backports.email.parser import BytesParser
78 | return BytesParser(*args, **kws).parse(fp)
79 |
--------------------------------------------------------------------------------
/src/future/backports/email/mime/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/src/future/backports/email/mime/__init__.py
--------------------------------------------------------------------------------
/src/future/backports/email/mime/application.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2001-2006 Python Software Foundation
2 | # Author: Keith Dart
3 | # Contact: email-sig@python.org
4 |
5 | """Class representing application/* type MIME documents."""
6 | from __future__ import unicode_literals
7 | from __future__ import division
8 | from __future__ import absolute_import
9 |
10 | from future.backports.email import encoders
11 | from future.backports.email.mime.nonmultipart import MIMENonMultipart
12 |
13 | __all__ = ["MIMEApplication"]
14 |
15 |
16 | class MIMEApplication(MIMENonMultipart):
17 | """Class for generating application/* MIME documents."""
18 |
19 | def __init__(self, _data, _subtype='octet-stream',
20 | _encoder=encoders.encode_base64, **_params):
21 | """Create an application/* type MIME document.
22 |
23 | _data is a string containing the raw application data.
24 |
25 | _subtype is the MIME content type subtype, defaulting to
26 | 'octet-stream'.
27 |
28 | _encoder is a function which will perform the actual encoding for
29 | transport of the application data, defaulting to base64 encoding.
30 |
31 | Any additional keyword arguments are passed to the base class
32 | constructor, which turns them into parameters on the Content-Type
33 | header.
34 | """
35 | if _subtype is None:
36 | raise TypeError('Invalid application MIME subtype')
37 | MIMENonMultipart.__init__(self, 'application', _subtype, **_params)
38 | self.set_payload(_data)
39 | _encoder(self)
40 |
--------------------------------------------------------------------------------
/src/future/backports/email/mime/base.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2001-2006 Python Software Foundation
2 | # Author: Barry Warsaw
3 | # Contact: email-sig@python.org
4 |
5 | """Base class for MIME specializations."""
6 | from __future__ import absolute_import, division, unicode_literals
7 | from future.backports.email import message
8 |
9 | __all__ = ['MIMEBase']
10 |
11 |
12 | class MIMEBase(message.Message):
13 | """Base class for MIME specializations."""
14 |
15 | def __init__(self, _maintype, _subtype, **_params):
16 | """This constructor adds a Content-Type: and a MIME-Version: header.
17 |
18 | The Content-Type: header is taken from the _maintype and _subtype
19 | arguments. Additional parameters for this header are taken from the
20 | keyword arguments.
21 | """
22 | message.Message.__init__(self)
23 | ctype = '%s/%s' % (_maintype, _subtype)
24 | self.add_header('Content-Type', ctype, **_params)
25 | self['MIME-Version'] = '1.0'
26 |
--------------------------------------------------------------------------------
/src/future/backports/email/mime/image.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2001-2006 Python Software Foundation
2 | # Author: Barry Warsaw
3 | # Contact: email-sig@python.org
4 |
5 | """Class representing image/* type MIME documents."""
6 | from __future__ import unicode_literals
7 | from __future__ import division
8 | from __future__ import absolute_import
9 |
10 | __all__ = ['MIMEImage']
11 |
12 | import imghdr
13 |
14 | from future.backports.email import encoders
15 | from future.backports.email.mime.nonmultipart import MIMENonMultipart
16 |
17 |
18 | class MIMEImage(MIMENonMultipart):
19 | """Class for generating image/* type MIME documents."""
20 |
21 | def __init__(self, _imagedata, _subtype=None,
22 | _encoder=encoders.encode_base64, **_params):
23 | """Create an image/* type MIME document.
24 |
25 | _imagedata is a string containing the raw image data. If this data
26 | can be decoded by the standard Python `imghdr' module, then the
27 | subtype will be automatically included in the Content-Type header.
28 | Otherwise, you can specify the specific image subtype via the _subtype
29 | parameter.
30 |
31 | _encoder is a function which will perform the actual encoding for
32 | transport of the image data. It takes one argument, which is this
33 | Image instance. It should use get_payload() and set_payload() to
34 | change the payload to the encoded form. It should also add any
35 | Content-Transfer-Encoding or other headers to the message as
36 | necessary. The default encoding is Base64.
37 |
38 | Any additional keyword arguments are passed to the base class
39 | constructor, which turns them into parameters on the Content-Type
40 | header.
41 | """
42 | if _subtype is None:
43 | _subtype = imghdr.what(None, _imagedata)
44 | if _subtype is None:
45 | raise TypeError('Could not guess image MIME subtype')
46 | MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
47 | self.set_payload(_imagedata)
48 | _encoder(self)
49 |
--------------------------------------------------------------------------------
/src/future/backports/email/mime/message.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2001-2006 Python Software Foundation
2 | # Author: Barry Warsaw
3 | # Contact: email-sig@python.org
4 |
5 | """Class representing message/* MIME documents."""
6 | from __future__ import unicode_literals
7 | from __future__ import division
8 | from __future__ import absolute_import
9 |
10 | __all__ = ['MIMEMessage']
11 |
12 | from future.backports.email import message
13 | from future.backports.email.mime.nonmultipart import MIMENonMultipart
14 |
15 |
16 | class MIMEMessage(MIMENonMultipart):
17 | """Class representing message/* MIME documents."""
18 |
19 | def __init__(self, _msg, _subtype='rfc822'):
20 | """Create a message/* type MIME document.
21 |
22 | _msg is a message object and must be an instance of Message, or a
23 | derived class of Message, otherwise a TypeError is raised.
24 |
25 | Optional _subtype defines the subtype of the contained message. The
26 | default is "rfc822" (this is defined by the MIME standard, even though
27 | the term "rfc822" is technically outdated by RFC 2822).
28 | """
29 | MIMENonMultipart.__init__(self, 'message', _subtype)
30 | if not isinstance(_msg, message.Message):
31 | raise TypeError('Argument is not an instance of Message')
32 | # It's convenient to use this base class method. We need to do it
33 | # this way or we'll get an exception
34 | message.Message.attach(self, _msg)
35 | # And be sure our default type is set correctly
36 | self.set_default_type('message/rfc822')
37 |
--------------------------------------------------------------------------------
/src/future/backports/email/mime/multipart.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2002-2006 Python Software Foundation
2 | # Author: Barry Warsaw
3 | # Contact: email-sig@python.org
4 |
5 | """Base class for MIME multipart/* type messages."""
6 | from __future__ import unicode_literals
7 | from __future__ import division
8 | from __future__ import absolute_import
9 |
10 | __all__ = ['MIMEMultipart']
11 |
12 | from future.backports.email.mime.base import MIMEBase
13 |
14 |
15 | class MIMEMultipart(MIMEBase):
16 | """Base class for MIME multipart/* type messages."""
17 |
18 | def __init__(self, _subtype='mixed', boundary=None, _subparts=None,
19 | **_params):
20 | """Creates a multipart/* type message.
21 |
22 | By default, creates a multipart/mixed message, with proper
23 | Content-Type and MIME-Version headers.
24 |
25 | _subtype is the subtype of the multipart content type, defaulting to
26 | `mixed'.
27 |
28 | boundary is the multipart boundary string. By default it is
29 | calculated as needed.
30 |
31 | _subparts is a sequence of initial subparts for the payload. It
32 | must be an iterable object, such as a list. You can always
33 | attach new subparts to the message by using the attach() method.
34 |
35 | Additional parameters for the Content-Type header are taken from the
36 | keyword arguments (or passed into the _params argument).
37 | """
38 | MIMEBase.__init__(self, 'multipart', _subtype, **_params)
39 |
40 | # Initialise _payload to an empty list as the Message superclass's
41 | # implementation of is_multipart assumes that _payload is a list for
42 | # multipart messages.
43 | self._payload = []
44 |
45 | if _subparts:
46 | for p in _subparts:
47 | self.attach(p)
48 | if boundary:
49 | self.set_boundary(boundary)
50 |
--------------------------------------------------------------------------------
/src/future/backports/email/mime/nonmultipart.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2002-2006 Python Software Foundation
2 | # Author: Barry Warsaw
3 | # Contact: email-sig@python.org
4 |
5 | """Base class for MIME type messages that are not multipart."""
6 | from __future__ import unicode_literals
7 | from __future__ import division
8 | from __future__ import absolute_import
9 |
10 | __all__ = ['MIMENonMultipart']
11 |
12 | from future.backports.email import errors
13 | from future.backports.email.mime.base import MIMEBase
14 |
15 |
16 | class MIMENonMultipart(MIMEBase):
17 | """Base class for MIME multipart/* type messages."""
18 |
19 | def attach(self, payload):
20 | # The public API prohibits attaching multiple subparts to MIMEBase
21 | # derived subtypes since none of them are, by definition, of content
22 | # type multipart/*
23 | raise errors.MultipartConversionError(
24 | 'Cannot attach additional subparts to non-multipart/*')
25 |
--------------------------------------------------------------------------------
/src/future/backports/email/mime/text.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2001-2006 Python Software Foundation
2 | # Author: Barry Warsaw
3 | # Contact: email-sig@python.org
4 |
5 | """Class representing text/* type MIME documents."""
6 | from __future__ import unicode_literals
7 | from __future__ import division
8 | from __future__ import absolute_import
9 |
10 | __all__ = ['MIMEText']
11 |
12 | from future.backports.email.encoders import encode_7or8bit
13 | from future.backports.email.mime.nonmultipart import MIMENonMultipart
14 |
15 |
16 | class MIMEText(MIMENonMultipart):
17 | """Class for generating text/* type MIME documents."""
18 |
19 | def __init__(self, _text, _subtype='plain', _charset=None):
20 | """Create a text/* type MIME document.
21 |
22 | _text is the string for this message object.
23 |
24 | _subtype is the MIME sub content type, defaulting to "plain".
25 |
26 | _charset is the character set parameter added to the Content-Type
27 | header. This defaults to "us-ascii". Note that as a side-effect, the
28 | Content-Transfer-Encoding header will also be set.
29 | """
30 |
31 | # If no _charset was specified, check to see if there are non-ascii
32 | # characters present. If not, use 'us-ascii', otherwise use utf-8.
33 | # XXX: This can be removed once #7304 is fixed.
34 | if _charset is None:
35 | try:
36 | _text.encode('us-ascii')
37 | _charset = 'us-ascii'
38 | except UnicodeEncodeError:
39 | _charset = 'utf-8'
40 |
41 | MIMENonMultipart.__init__(self, 'text', _subtype,
42 | **{'charset': _charset})
43 |
44 | self.set_payload(_text, _charset)
45 |
--------------------------------------------------------------------------------
/src/future/backports/html/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | General functions for HTML manipulation, backported from Py3.
3 |
4 | Note that this uses Python 2.7 code with the corresponding Python 3
5 | module names and locations.
6 | """
7 |
8 | from __future__ import unicode_literals
9 |
10 |
11 | _escape_map = {ord('&'): '&', ord('<'): '<', ord('>'): '>'}
12 | _escape_map_full = {ord('&'): '&', ord('<'): '<', ord('>'): '>',
13 | ord('"'): '"', ord('\''): '''}
14 |
15 | # NB: this is a candidate for a bytes/string polymorphic interface
16 |
17 | def escape(s, quote=True):
18 | """
19 | Replace special characters "&", "<" and ">" to HTML-safe sequences.
20 | If the optional flag quote is true (the default), the quotation mark
21 | characters, both double quote (") and single quote (') characters are also
22 | translated.
23 | """
24 | assert not isinstance(s, bytes), 'Pass a unicode string'
25 | if quote:
26 | return s.translate(_escape_map_full)
27 | return s.translate(_escape_map)
28 |
--------------------------------------------------------------------------------
/src/future/backports/http/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/src/future/backports/http/__init__.py
--------------------------------------------------------------------------------
/src/future/backports/test/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | test package backported for python-future.
3 |
4 | Its primary purpose is to allow use of "import test.support" for running
5 | the Python standard library unit tests using the new Python 3 stdlib
6 | import location.
7 |
8 | Python 3 renamed test.test_support to test.support.
9 | """
10 |
--------------------------------------------------------------------------------
/src/future/backports/test/badcert.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIICXwIBAAKBgQC8ddrhm+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9L
3 | opdJhTvbGfEj0DQs1IE8M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVH
4 | fhi/VwovESJlaBOp+WMnfhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQAB
5 | AoGBAK0FZpaKj6WnJZN0RqhhK+ggtBWwBnc0U/ozgKz2j1s3fsShYeiGtW6CK5nU
6 | D1dZ5wzhbGThI7LiOXDvRucc9n7vUgi0alqPQ/PFodPxAN/eEYkmXQ7W2k7zwsDA
7 | IUK0KUhktQbLu8qF/m8qM86ba9y9/9YkXuQbZ3COl5ahTZrhAkEA301P08RKv3KM
8 | oXnGU2UHTuJ1MAD2hOrPxjD4/wxA/39EWG9bZczbJyggB4RHu0I3NOSFjAm3HQm0
9 | ANOu5QK9owJBANgOeLfNNcF4pp+UikRFqxk5hULqRAWzVxVrWe85FlPm0VVmHbb/
10 | loif7mqjU8o1jTd/LM7RD9f2usZyE2psaw8CQQCNLhkpX3KO5kKJmS9N7JMZSc4j
11 | oog58yeYO8BBqKKzpug0LXuQultYv2K4veaIO04iL9VLe5z9S/Q1jaCHBBuXAkEA
12 | z8gjGoi1AOp6PBBLZNsncCvcV/0aC+1se4HxTNo2+duKSDnbq+ljqOM+E7odU+Nq
13 | ewvIWOG//e8fssd0mq3HywJBAJ8l/c8GVmrpFTx8r/nZ2Pyyjt3dH1widooDXYSV
14 | q6Gbf41Llo5sYAtmxdndTLASuHKecacTgZVhy0FryZpLKrU=
15 | -----END RSA PRIVATE KEY-----
16 | -----BEGIN CERTIFICATE-----
17 | Just bad cert data
18 | -----END CERTIFICATE-----
19 | -----BEGIN RSA PRIVATE KEY-----
20 | MIICXwIBAAKBgQC8ddrhm+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9L
21 | opdJhTvbGfEj0DQs1IE8M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVH
22 | fhi/VwovESJlaBOp+WMnfhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQAB
23 | AoGBAK0FZpaKj6WnJZN0RqhhK+ggtBWwBnc0U/ozgKz2j1s3fsShYeiGtW6CK5nU
24 | D1dZ5wzhbGThI7LiOXDvRucc9n7vUgi0alqPQ/PFodPxAN/eEYkmXQ7W2k7zwsDA
25 | IUK0KUhktQbLu8qF/m8qM86ba9y9/9YkXuQbZ3COl5ahTZrhAkEA301P08RKv3KM
26 | oXnGU2UHTuJ1MAD2hOrPxjD4/wxA/39EWG9bZczbJyggB4RHu0I3NOSFjAm3HQm0
27 | ANOu5QK9owJBANgOeLfNNcF4pp+UikRFqxk5hULqRAWzVxVrWe85FlPm0VVmHbb/
28 | loif7mqjU8o1jTd/LM7RD9f2usZyE2psaw8CQQCNLhkpX3KO5kKJmS9N7JMZSc4j
29 | oog58yeYO8BBqKKzpug0LXuQultYv2K4veaIO04iL9VLe5z9S/Q1jaCHBBuXAkEA
30 | z8gjGoi1AOp6PBBLZNsncCvcV/0aC+1se4HxTNo2+duKSDnbq+ljqOM+E7odU+Nq
31 | ewvIWOG//e8fssd0mq3HywJBAJ8l/c8GVmrpFTx8r/nZ2Pyyjt3dH1widooDXYSV
32 | q6Gbf41Llo5sYAtmxdndTLASuHKecacTgZVhy0FryZpLKrU=
33 | -----END RSA PRIVATE KEY-----
34 | -----BEGIN CERTIFICATE-----
35 | Just bad cert data
36 | -----END CERTIFICATE-----
37 |
--------------------------------------------------------------------------------
/src/future/backports/test/badkey.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | Bad Key, though the cert should be OK
3 | -----END RSA PRIVATE KEY-----
4 | -----BEGIN CERTIFICATE-----
5 | MIICpzCCAhCgAwIBAgIJAP+qStv1cIGNMA0GCSqGSIb3DQEBBQUAMIGJMQswCQYD
6 | VQQGEwJVUzERMA8GA1UECBMIRGVsYXdhcmUxEzARBgNVBAcTCldpbG1pbmd0b24x
7 | IzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMQwwCgYDVQQLEwNT
8 | U0wxHzAdBgNVBAMTFnNvbWVtYWNoaW5lLnB5dGhvbi5vcmcwHhcNMDcwODI3MTY1
9 | NDUwWhcNMTMwMjE2MTY1NDUwWjCBiTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCERl
10 | bGF3YXJlMRMwEQYDVQQHEwpXaWxtaW5ndG9uMSMwIQYDVQQKExpQeXRob24gU29m
11 | dHdhcmUgRm91bmRhdGlvbjEMMAoGA1UECxMDU1NMMR8wHQYDVQQDExZzb21lbWFj
12 | aGluZS5weXRob24ub3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8ddrh
13 | m+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9LopdJhTvbGfEj0DQs1IE8
14 | M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVHfhi/VwovESJlaBOp+WMn
15 | fhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQABoxUwEzARBglghkgBhvhC
16 | AQEEBAMCBkAwDQYJKoZIhvcNAQEFBQADgYEAF4Q5BVqmCOLv1n8je/Jw9K669VXb
17 | 08hyGzQhkemEBYQd6fzQ9A/1ZzHkJKb1P6yreOLSEh4KcxYPyrLRC1ll8nr5OlCx
18 | CMhKkTnR6qBsdNV0XtdU2+N25hqW+Ma4ZeqsN/iiJVCGNOZGnvQuvCAGWF8+J/f/
19 | iHkC6gGdBJhogs4=
20 | -----END CERTIFICATE-----
21 | -----BEGIN RSA PRIVATE KEY-----
22 | Bad Key, though the cert should be OK
23 | -----END RSA PRIVATE KEY-----
24 | -----BEGIN CERTIFICATE-----
25 | MIICpzCCAhCgAwIBAgIJAP+qStv1cIGNMA0GCSqGSIb3DQEBBQUAMIGJMQswCQYD
26 | VQQGEwJVUzERMA8GA1UECBMIRGVsYXdhcmUxEzARBgNVBAcTCldpbG1pbmd0b24x
27 | IzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMQwwCgYDVQQLEwNT
28 | U0wxHzAdBgNVBAMTFnNvbWVtYWNoaW5lLnB5dGhvbi5vcmcwHhcNMDcwODI3MTY1
29 | NDUwWhcNMTMwMjE2MTY1NDUwWjCBiTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCERl
30 | bGF3YXJlMRMwEQYDVQQHEwpXaWxtaW5ndG9uMSMwIQYDVQQKExpQeXRob24gU29m
31 | dHdhcmUgRm91bmRhdGlvbjEMMAoGA1UECxMDU1NMMR8wHQYDVQQDExZzb21lbWFj
32 | aGluZS5weXRob24ub3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8ddrh
33 | m+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9LopdJhTvbGfEj0DQs1IE8
34 | M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVHfhi/VwovESJlaBOp+WMn
35 | fhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQABoxUwEzARBglghkgBhvhC
36 | AQEEBAMCBkAwDQYJKoZIhvcNAQEFBQADgYEAF4Q5BVqmCOLv1n8je/Jw9K669VXb
37 | 08hyGzQhkemEBYQd6fzQ9A/1ZzHkJKb1P6yreOLSEh4KcxYPyrLRC1ll8nr5OlCx
38 | CMhKkTnR6qBsdNV0XtdU2+N25hqW+Ma4ZeqsN/iiJVCGNOZGnvQuvCAGWF8+J/f/
39 | iHkC6gGdBJhogs4=
40 | -----END CERTIFICATE-----
41 |
--------------------------------------------------------------------------------
/src/future/backports/test/dh512.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN DH PARAMETERS-----
2 | MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak
3 | XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC
4 | -----END DH PARAMETERS-----
5 |
6 | These are the 512 bit DH parameters from "Assigned Number for SKIP Protocols"
7 | (http://www.skip-vpn.org/spec/numbers.html).
8 | See there for how they were generated.
9 | Note that g is not a generator, but this is not a problem since p is a safe prime.
10 |
--------------------------------------------------------------------------------
/src/future/backports/test/keycert.passwd.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | Proc-Type: 4,ENCRYPTED
3 | DEK-Info: DES-EDE3-CBC,1A8D9D2A02EC698A
4 |
5 | kJYbfZ8L0sfe9Oty3gw0aloNnY5E8fegRfQLZlNoxTl6jNt0nIwI8kDJ36CZgR9c
6 | u3FDJm/KqrfUoz8vW+qEnWhSG7QPX2wWGPHd4K94Yz/FgrRzZ0DoK7XxXq9gOtVA
7 | AVGQhnz32p+6WhfGsCr9ArXEwRZrTk/FvzEPaU5fHcoSkrNVAGX8IpSVkSDwEDQr
8 | Gv17+cfk99UV1OCza6yKHoFkTtrC+PZU71LomBabivS2Oc4B9hYuSR2hF01wTHP+
9 | YlWNagZOOVtNz4oKK9x9eNQpmfQXQvPPTfusexKIbKfZrMvJoxcm1gfcZ0H/wK6P
10 | 6wmXSG35qMOOztCZNtperjs1wzEBXznyK8QmLcAJBjkfarABJX9vBEzZV0OUKhy+
11 | noORFwHTllphbmydLhu6ehLUZMHPhzAS5UN7srtpSN81eerDMy0RMUAwA7/PofX1
12 | 94Me85Q8jP0PC9ETdsJcPqLzAPETEYu0ELewKRcrdyWi+tlLFrpE5KT/s5ecbl9l
13 | 7B61U4Kfd1PIXc/siINhU3A3bYK+845YyUArUOnKf1kEox7p1RpD7yFqVT04lRTo
14 | cibNKATBusXSuBrp2G6GNuhWEOSafWCKJQAzgCYIp6ZTV2khhMUGppc/2H3CF6cO
15 | zX0KtlPVZC7hLkB6HT8SxYUwF1zqWY7+/XPPdc37MeEZ87Q3UuZwqORLY+Z0hpgt
16 | L5JXBCoklZhCAaN2GqwFLXtGiRSRFGY7xXIhbDTlE65Wv1WGGgDLMKGE1gOz3yAo
17 | 2jjG1+yAHJUdE69XTFHSqSkvaloA1W03LdMXZ9VuQJ/ySXCie6ABAQ==
18 | -----END RSA PRIVATE KEY-----
19 | -----BEGIN CERTIFICATE-----
20 | MIICVDCCAb2gAwIBAgIJANfHOBkZr8JOMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNV
21 | BAYTAlhZMRcwFQYDVQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9u
22 | IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDEw
23 | MDgyMzAxNTZaFw0yMDEwMDUyMzAxNTZaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH
24 | Ew5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZvdW5k
25 | YXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
26 | gYkCgYEA21vT5isq7F68amYuuNpSFlKDPrMUCa4YWYqZRt2OZ+/3NKaZ2xAiSwr7
27 | 6MrQF70t5nLbSPpqE5+5VrS58SY+g/sXLiFd6AplH1wJZwh78DofbFYXUggktFMt
28 | pTyiX8jtP66bkcPkDADA089RI1TQR6Ca+n7HFa7c1fabVV6i3zkCAwEAAaMYMBYw
29 | FAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBBQUAA4GBAHPctQBEQ4wd
30 | BJ6+JcpIraopLn8BGhbjNWj40mmRqWB/NAWF6M5ne7KpGAu7tLeG4hb1zLaldK8G
31 | lxy2GPSRF6LFS48dpEj2HbMv2nvv6xxalDMJ9+DicWgAKTQ6bcX2j3GUkCR0g/T1
32 | CRlNBAAlvhKzO7Clpf9l0YKBEfraJByX
33 | -----END CERTIFICATE-----
34 |
--------------------------------------------------------------------------------
/src/future/backports/test/keycert.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANtb0+YrKuxevGpm
3 | LrjaUhZSgz6zFAmuGFmKmUbdjmfv9zSmmdsQIksK++jK0Be9LeZy20j6ahOfuVa0
4 | ufEmPoP7Fy4hXegKZR9cCWcIe/A6H2xWF1IIJLRTLaU8ol/I7T+um5HD5AwAwNPP
5 | USNU0Eegmvp+xxWu3NX2m1Veot85AgMBAAECgYA3ZdZ673X0oexFlq7AAmrutkHt
6 | CL7LvwrpOiaBjhyTxTeSNWzvtQBkIU8DOI0bIazA4UreAFffwtvEuPmonDb3F+Iq
7 | SMAu42XcGyVZEl+gHlTPU9XRX7nTOXVt+MlRRRxL6t9GkGfUAXI3XxJDXW3c0vBK
8 | UL9xqD8cORXOfE06rQJBAP8mEX1ERkR64Ptsoe4281vjTlNfIbs7NMPkUnrn9N/Y
9 | BLhjNIfQ3HFZG8BTMLfX7kCS9D593DW5tV4Z9BP/c6cCQQDcFzCcVArNh2JSywOQ
10 | ZfTfRbJg/Z5Lt9Fkngv1meeGNPgIMLN8Sg679pAOOWmzdMO3V706rNPzSVMME7E5
11 | oPIfAkEA8pDddarP5tCvTTgUpmTFbakm0KoTZm2+FzHcnA4jRh+XNTjTOv98Y6Ik
12 | eO5d1ZnKXseWvkZncQgxfdnMqqpj5wJAcNq/RVne1DbYlwWchT2Si65MYmmJ8t+F
13 | 0mcsULqjOnEMwf5e+ptq5LzwbyrHZYq5FNk7ocufPv/ZQrcSSC+cFwJBAKvOJByS
14 | x56qyGeZLOQlWS2JS3KJo59XuLFGqcbgN9Om9xFa41Yb4N9NvplFivsvZdw3m1Q/
15 | SPIXQuT8RMPDVNQ=
16 | -----END PRIVATE KEY-----
17 | -----BEGIN CERTIFICATE-----
18 | MIICVDCCAb2gAwIBAgIJANfHOBkZr8JOMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNV
19 | BAYTAlhZMRcwFQYDVQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9u
20 | IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDEw
21 | MDgyMzAxNTZaFw0yMDEwMDUyMzAxNTZaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH
22 | Ew5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZvdW5k
23 | YXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
24 | gYkCgYEA21vT5isq7F68amYuuNpSFlKDPrMUCa4YWYqZRt2OZ+/3NKaZ2xAiSwr7
25 | 6MrQF70t5nLbSPpqE5+5VrS58SY+g/sXLiFd6AplH1wJZwh78DofbFYXUggktFMt
26 | pTyiX8jtP66bkcPkDADA089RI1TQR6Ca+n7HFa7c1fabVV6i3zkCAwEAAaMYMBYw
27 | FAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBBQUAA4GBAHPctQBEQ4wd
28 | BJ6+JcpIraopLn8BGhbjNWj40mmRqWB/NAWF6M5ne7KpGAu7tLeG4hb1zLaldK8G
29 | lxy2GPSRF6LFS48dpEj2HbMv2nvv6xxalDMJ9+DicWgAKTQ6bcX2j3GUkCR0g/T1
30 | CRlNBAAlvhKzO7Clpf9l0YKBEfraJByX
31 | -----END CERTIFICATE-----
32 |
--------------------------------------------------------------------------------
/src/future/backports/test/keycert2.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJnsJZVrppL+W5I9
3 | zGQrrawWwE5QJpBK9nWw17mXrZ03R1cD9BamLGivVISbPlRlAVnZBEyh1ATpsB7d
4 | CUQ+WHEvALquvx4+Yw5l+fXeiYRjrLRBYZuVy8yNtXzU3iWcGObcYRkUdiXdOyP7
5 | sLF2YZHRvQZpzgDBKkrraeQ81w21AgMBAAECgYBEm7n07FMHWlE+0kT0sXNsLYfy
6 | YE+QKZnJw9WkaDN+zFEEPELkhZVt5BjsMraJr6v2fIEqF0gGGJPkbenffVq2B5dC
7 | lWUOxvJHufMK4sM3Cp6s/gOp3LP+QkzVnvJSfAyZU6l+4PGX5pLdUsXYjPxgzjzL
8 | S36tF7/2Uv1WePyLUQJBAMsPhYzUXOPRgmbhcJiqi9A9c3GO8kvSDYTCKt3VMnqz
9 | HBn6MQ4VQasCD1F+7jWTI0FU/3vdw8non/Fj8hhYqZcCQQDCDRdvmZqDiZnpMqDq
10 | L6ZSrLTVtMvZXZbgwForaAD9uHj51TME7+eYT7EG2YCgJTXJ4YvRJEnPNyskwdKt
11 | vTSTAkEAtaaN/vyemEJ82BIGStwONNw0ILsSr5cZ9tBHzqiA/tipY+e36HRFiXhP
12 | QcU9zXlxyWkDH8iz9DSAmE2jbfoqwwJANlMJ65E543cjIlitGcKLMnvtCCLcKpb7
13 | xSG0XJB6Lo11OKPJ66jp0gcFTSCY1Lx2CXVd+gfJrfwI1Pp562+bhwJBAJ9IfDPU
14 | R8OpO9v1SGd8x33Owm7uXOpB9d63/T70AD1QOXjKUC4eXYbt0WWfWuny/RNPRuyh
15 | w7DXSfUF+kPKolU=
16 | -----END PRIVATE KEY-----
17 | -----BEGIN CERTIFICATE-----
18 | MIICXTCCAcagAwIBAgIJAIO3upAG445fMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNV
19 | BAYTAlhZMRcwFQYDVQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9u
20 | IFNvZnR3YXJlIEZvdW5kYXRpb24xFTATBgNVBAMTDGZha2Vob3N0bmFtZTAeFw0x
21 | MDEwMDkxNTAxMDBaFw0yMDEwMDYxNTAxMDBaMGIxCzAJBgNVBAYTAlhZMRcwFQYD
22 | VQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZv
23 | dW5kYXRpb24xFTATBgNVBAMTDGZha2Vob3N0bmFtZTCBnzANBgkqhkiG9w0BAQEF
24 | AAOBjQAwgYkCgYEAmewllWumkv5bkj3MZCutrBbATlAmkEr2dbDXuZetnTdHVwP0
25 | FqYsaK9UhJs+VGUBWdkETKHUBOmwHt0JRD5YcS8Auq6/Hj5jDmX59d6JhGOstEFh
26 | m5XLzI21fNTeJZwY5txhGRR2Jd07I/uwsXZhkdG9BmnOAMEqSutp5DzXDbUCAwEA
27 | AaMbMBkwFwYDVR0RBBAwDoIMZmFrZWhvc3RuYW1lMA0GCSqGSIb3DQEBBQUAA4GB
28 | AH+iMClLLGSaKWgwXsmdVo4FhTZZHo8Uprrtg3N9FxEeE50btpDVQysgRt5ias3K
29 | m+bME9zbKwvbVWD5zZdjus4pDgzwF/iHyccL8JyYhxOvS/9zmvAtFXj/APIIbZFp
30 | IT75d9f88ScIGEtknZQejnrdhB64tYki/EqluiuKBqKD
31 | -----END CERTIFICATE-----
32 |
--------------------------------------------------------------------------------
/src/future/backports/test/nokia.pem:
--------------------------------------------------------------------------------
1 | # Certificate for projects.developer.nokia.com:443 (see issue 13034)
2 | -----BEGIN CERTIFICATE-----
3 | MIIFLDCCBBSgAwIBAgIQLubqdkCgdc7lAF9NfHlUmjANBgkqhkiG9w0BAQUFADCB
4 | vDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
5 | ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2Ug
6 | YXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAoYykxMDE2MDQGA1UEAxMt
7 | VmVyaVNpZ24gQ2xhc3MgMyBJbnRlcm5hdGlvbmFsIFNlcnZlciBDQSAtIEczMB4X
8 | DTExMDkyMTAwMDAwMFoXDTEyMDkyMDIzNTk1OVowcTELMAkGA1UEBhMCRkkxDjAM
9 | BgNVBAgTBUVzcG9vMQ4wDAYDVQQHFAVFc3BvbzEOMAwGA1UEChQFTm9raWExCzAJ
10 | BgNVBAsUAkJJMSUwIwYDVQQDFBxwcm9qZWN0cy5kZXZlbG9wZXIubm9raWEuY29t
11 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCr92w1bpHYSYxUEx8N/8Iddda2
12 | lYi+aXNtQfV/l2Fw9Ykv3Ipw4nLeGTj18FFlAZgMdPRlgrzF/NNXGw/9l3/qKdow
13 | CypkQf8lLaxb9Ze1E/KKmkRJa48QTOqvo6GqKuTI6HCeGlG1RxDb8YSKcQWLiytn
14 | yj3Wp4MgRQO266xmMQIDAQABo4IB9jCCAfIwQQYDVR0RBDowOIIccHJvamVjdHMu
15 | ZGV2ZWxvcGVyLm5va2lhLmNvbYIYcHJvamVjdHMuZm9ydW0ubm9raWEuY29tMAkG
16 | A1UdEwQCMAAwCwYDVR0PBAQDAgWgMEEGA1UdHwQ6MDgwNqA0oDKGMGh0dHA6Ly9T
17 | VlJJbnRsLUczLWNybC52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNybDBEBgNVHSAE
18 | PTA7MDkGC2CGSAGG+EUBBxcDMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3LnZl
19 | cmlzaWduLmNvbS9ycGEwKAYDVR0lBCEwHwYJYIZIAYb4QgQBBggrBgEFBQcDAQYI
20 | KwYBBQUHAwIwcgYIKwYBBQUHAQEEZjBkMCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz
21 | cC52ZXJpc2lnbi5jb20wPAYIKwYBBQUHMAKGMGh0dHA6Ly9TVlJJbnRsLUczLWFp
22 | YS52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNlcjBuBggrBgEFBQcBDARiMGChXqBc
23 | MFowWDBWFglpbWFnZS9naWYwITAfMAcGBSsOAwIaBBRLa7kolgYMu9BSOJsprEsH
24 | iyEFGDAmFiRodHRwOi8vbG9nby52ZXJpc2lnbi5jb20vdnNsb2dvMS5naWYwDQYJ
25 | KoZIhvcNAQEFBQADggEBACQuPyIJqXwUyFRWw9x5yDXgMW4zYFopQYOw/ItRY522
26 | O5BsySTh56BWS6mQB07XVfxmYUGAvRQDA5QHpmY8jIlNwSmN3s8RKo+fAtiNRlcL
27 | x/mWSfuMs3D/S6ev3D6+dpEMZtjrhOdctsarMKp8n/hPbwhAbg5hVjpkW5n8vz2y
28 | 0KxvvkA1AxpLwpVv7OlK17ttzIHw8bp9HTlHBU5s8bKz4a565V/a5HI0CSEv/+0y
29 | ko4/ghTnZc1CkmUngKKeFMSah/mT/xAh8XnE2l1AazFa8UKuYki1e+ArHaGZc4ix
30 | UYOtiRphwfuYQhRZ7qX9q2MMkCMI65XNK/SaFrAbbG0=
31 | -----END CERTIFICATE-----
32 |
--------------------------------------------------------------------------------
/src/future/backports/test/nullcert.pem:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/src/future/backports/test/nullcert.pem
--------------------------------------------------------------------------------
/src/future/backports/test/ssl_cert.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICVDCCAb2gAwIBAgIJANfHOBkZr8JOMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNV
3 | BAYTAlhZMRcwFQYDVQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9u
4 | IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDEw
5 | MDgyMzAxNTZaFw0yMDEwMDUyMzAxNTZaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH
6 | Ew5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZvdW5k
7 | YXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
8 | gYkCgYEA21vT5isq7F68amYuuNpSFlKDPrMUCa4YWYqZRt2OZ+/3NKaZ2xAiSwr7
9 | 6MrQF70t5nLbSPpqE5+5VrS58SY+g/sXLiFd6AplH1wJZwh78DofbFYXUggktFMt
10 | pTyiX8jtP66bkcPkDADA089RI1TQR6Ca+n7HFa7c1fabVV6i3zkCAwEAAaMYMBYw
11 | FAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBBQUAA4GBAHPctQBEQ4wd
12 | BJ6+JcpIraopLn8BGhbjNWj40mmRqWB/NAWF6M5ne7KpGAu7tLeG4hb1zLaldK8G
13 | lxy2GPSRF6LFS48dpEj2HbMv2nvv6xxalDMJ9+DicWgAKTQ6bcX2j3GUkCR0g/T1
14 | CRlNBAAlvhKzO7Clpf9l0YKBEfraJByX
15 | -----END CERTIFICATE-----
16 |
--------------------------------------------------------------------------------
/src/future/backports/test/ssl_key.passwd.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | Proc-Type: 4,ENCRYPTED
3 | DEK-Info: DES-EDE3-CBC,1A8D9D2A02EC698A
4 |
5 | kJYbfZ8L0sfe9Oty3gw0aloNnY5E8fegRfQLZlNoxTl6jNt0nIwI8kDJ36CZgR9c
6 | u3FDJm/KqrfUoz8vW+qEnWhSG7QPX2wWGPHd4K94Yz/FgrRzZ0DoK7XxXq9gOtVA
7 | AVGQhnz32p+6WhfGsCr9ArXEwRZrTk/FvzEPaU5fHcoSkrNVAGX8IpSVkSDwEDQr
8 | Gv17+cfk99UV1OCza6yKHoFkTtrC+PZU71LomBabivS2Oc4B9hYuSR2hF01wTHP+
9 | YlWNagZOOVtNz4oKK9x9eNQpmfQXQvPPTfusexKIbKfZrMvJoxcm1gfcZ0H/wK6P
10 | 6wmXSG35qMOOztCZNtperjs1wzEBXznyK8QmLcAJBjkfarABJX9vBEzZV0OUKhy+
11 | noORFwHTllphbmydLhu6ehLUZMHPhzAS5UN7srtpSN81eerDMy0RMUAwA7/PofX1
12 | 94Me85Q8jP0PC9ETdsJcPqLzAPETEYu0ELewKRcrdyWi+tlLFrpE5KT/s5ecbl9l
13 | 7B61U4Kfd1PIXc/siINhU3A3bYK+845YyUArUOnKf1kEox7p1RpD7yFqVT04lRTo
14 | cibNKATBusXSuBrp2G6GNuhWEOSafWCKJQAzgCYIp6ZTV2khhMUGppc/2H3CF6cO
15 | zX0KtlPVZC7hLkB6HT8SxYUwF1zqWY7+/XPPdc37MeEZ87Q3UuZwqORLY+Z0hpgt
16 | L5JXBCoklZhCAaN2GqwFLXtGiRSRFGY7xXIhbDTlE65Wv1WGGgDLMKGE1gOz3yAo
17 | 2jjG1+yAHJUdE69XTFHSqSkvaloA1W03LdMXZ9VuQJ/ySXCie6ABAQ==
18 | -----END RSA PRIVATE KEY-----
19 |
--------------------------------------------------------------------------------
/src/future/backports/test/ssl_key.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANtb0+YrKuxevGpm
3 | LrjaUhZSgz6zFAmuGFmKmUbdjmfv9zSmmdsQIksK++jK0Be9LeZy20j6ahOfuVa0
4 | ufEmPoP7Fy4hXegKZR9cCWcIe/A6H2xWF1IIJLRTLaU8ol/I7T+um5HD5AwAwNPP
5 | USNU0Eegmvp+xxWu3NX2m1Veot85AgMBAAECgYA3ZdZ673X0oexFlq7AAmrutkHt
6 | CL7LvwrpOiaBjhyTxTeSNWzvtQBkIU8DOI0bIazA4UreAFffwtvEuPmonDb3F+Iq
7 | SMAu42XcGyVZEl+gHlTPU9XRX7nTOXVt+MlRRRxL6t9GkGfUAXI3XxJDXW3c0vBK
8 | UL9xqD8cORXOfE06rQJBAP8mEX1ERkR64Ptsoe4281vjTlNfIbs7NMPkUnrn9N/Y
9 | BLhjNIfQ3HFZG8BTMLfX7kCS9D593DW5tV4Z9BP/c6cCQQDcFzCcVArNh2JSywOQ
10 | ZfTfRbJg/Z5Lt9Fkngv1meeGNPgIMLN8Sg679pAOOWmzdMO3V706rNPzSVMME7E5
11 | oPIfAkEA8pDddarP5tCvTTgUpmTFbakm0KoTZm2+FzHcnA4jRh+XNTjTOv98Y6Ik
12 | eO5d1ZnKXseWvkZncQgxfdnMqqpj5wJAcNq/RVne1DbYlwWchT2Si65MYmmJ8t+F
13 | 0mcsULqjOnEMwf5e+ptq5LzwbyrHZYq5FNk7ocufPv/ZQrcSSC+cFwJBAKvOJByS
14 | x56qyGeZLOQlWS2JS3KJo59XuLFGqcbgN9Om9xFa41Yb4N9NvplFivsvZdw3m1Q/
15 | SPIXQuT8RMPDVNQ=
16 | -----END PRIVATE KEY-----
17 |
--------------------------------------------------------------------------------
/src/future/backports/total_ordering.py:
--------------------------------------------------------------------------------
1 | """
2 | For Python < 2.7.2. total_ordering in versions prior to 2.7.2 is buggy.
3 | See http://bugs.python.org/issue10042 for details. For these versions use
4 | code borrowed from Python 2.7.3.
5 |
6 | From django.utils.
7 | """
8 |
9 | import sys
10 | if sys.version_info >= (2, 7, 2):
11 | from functools import total_ordering
12 | else:
13 | def total_ordering(cls):
14 | """Class decorator that fills in missing ordering methods"""
15 | convert = {
16 | '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
17 | ('__le__', lambda self, other: self < other or self == other),
18 | ('__ge__', lambda self, other: not self < other)],
19 | '__le__': [('__ge__', lambda self, other: not self <= other or self == other),
20 | ('__lt__', lambda self, other: self <= other and not self == other),
21 | ('__gt__', lambda self, other: not self <= other)],
22 | '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
23 | ('__ge__', lambda self, other: self > other or self == other),
24 | ('__le__', lambda self, other: not self > other)],
25 | '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
26 | ('__gt__', lambda self, other: self >= other and not self == other),
27 | ('__lt__', lambda self, other: not self >= other)]
28 | }
29 | roots = set(dir(cls)) & set(convert)
30 | if not roots:
31 | raise ValueError('must define at least one ordering operation: < > <= >=')
32 | root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
33 | for opname, opfunc in convert[root]:
34 | if opname not in roots:
35 | opfunc.__name__ = opname
36 | opfunc.__doc__ = getattr(int, opname).__doc__
37 | setattr(cls, opname, opfunc)
38 | return cls
39 |
--------------------------------------------------------------------------------
/src/future/backports/urllib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/src/future/backports/urllib/__init__.py
--------------------------------------------------------------------------------
/src/future/backports/xmlrpc/__init__.py:
--------------------------------------------------------------------------------
1 | # This directory is a Python package.
2 |
--------------------------------------------------------------------------------
/src/future/builtins/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | A module that brings in equivalents of the new and modified Python 3
3 | builtins into Py2. Has no effect on Py3.
4 |
5 | See the docs `here `_
6 | (``docs/what-else.rst``) for more information.
7 |
8 | """
9 |
10 | from future.builtins.iterators import (filter, map, zip)
11 | # The isinstance import is no longer needed. We provide it only for
12 | # backward-compatibility with future v0.8.2. It will be removed in future v1.0.
13 | from future.builtins.misc import (ascii, chr, hex, input, isinstance, next,
14 | oct, open, pow, round, super, max, min)
15 | from future.utils import PY3
16 |
17 | if PY3:
18 | import builtins
19 | bytes = builtins.bytes
20 | dict = builtins.dict
21 | int = builtins.int
22 | list = builtins.list
23 | object = builtins.object
24 | range = builtins.range
25 | str = builtins.str
26 | __all__ = []
27 | else:
28 | from future.types import (newbytes as bytes,
29 | newdict as dict,
30 | newint as int,
31 | newlist as list,
32 | newobject as object,
33 | newrange as range,
34 | newstr as str)
35 | from future import utils
36 |
37 |
38 | if not utils.PY3:
39 | # We only import names that shadow the builtins on Py2. No other namespace
40 | # pollution on Py2.
41 |
42 | # Only shadow builtins on Py2; no new names
43 | __all__ = ['filter', 'map', 'zip',
44 | 'ascii', 'chr', 'hex', 'input', 'next', 'oct', 'open', 'pow',
45 | 'round', 'super',
46 | 'bytes', 'dict', 'int', 'list', 'object', 'range', 'str', 'max', 'min'
47 | ]
48 |
49 | else:
50 | # No namespace pollution on Py3
51 | __all__ = []
52 |
--------------------------------------------------------------------------------
/src/future/builtins/disabled.py:
--------------------------------------------------------------------------------
1 | """
2 | This disables builtin functions (and one exception class) which are
3 | removed from Python 3.3.
4 |
5 | This module is designed to be used like this::
6 |
7 | from future.builtins.disabled import *
8 |
9 | This disables the following obsolete Py2 builtin functions::
10 |
11 | apply, cmp, coerce, execfile, file, input, long,
12 | raw_input, reduce, reload, unicode, xrange
13 |
14 | We don't hack __builtin__, which is very fragile because it contaminates
15 | imported modules too. Instead, we just create new functions with
16 | the same names as the obsolete builtins from Python 2 which raise
17 | NameError exceptions when called.
18 |
19 | Note that both ``input()`` and ``raw_input()`` are among the disabled
20 | functions (in this module). Although ``input()`` exists as a builtin in
21 | Python 3, the Python 2 ``input()`` builtin is unsafe to use because it
22 | can lead to shell injection. Therefore we shadow it by default upon ``from
23 | future.builtins.disabled import *``, in case someone forgets to import our
24 | replacement ``input()`` somehow and expects Python 3 semantics.
25 |
26 | See the ``future.builtins.misc`` module for a working version of
27 | ``input`` with Python 3 semantics.
28 |
29 | (Note that callable() is not among the functions disabled; this was
30 | reintroduced into Python 3.2.)
31 |
32 | This exception class is also disabled:
33 |
34 | StandardError
35 |
36 | """
37 |
38 | from __future__ import division, absolute_import, print_function
39 |
40 | from future import utils
41 |
42 |
43 | OBSOLETE_BUILTINS = ['apply', 'chr', 'cmp', 'coerce', 'execfile', 'file',
44 | 'input', 'long', 'raw_input', 'reduce', 'reload',
45 | 'unicode', 'xrange', 'StandardError']
46 |
47 |
48 | def disabled_function(name):
49 | '''
50 | Returns a function that cannot be called
51 | '''
52 | def disabled(*args, **kwargs):
53 | '''
54 | A function disabled by the ``future`` module. This function is
55 | no longer a builtin in Python 3.
56 | '''
57 | raise NameError('obsolete Python 2 builtin {0} is disabled'.format(name))
58 | return disabled
59 |
60 |
61 | if not utils.PY3:
62 | for fname in OBSOLETE_BUILTINS:
63 | locals()[fname] = disabled_function(fname)
64 | __all__ = OBSOLETE_BUILTINS
65 | else:
66 | __all__ = []
67 |
--------------------------------------------------------------------------------
/src/future/builtins/iterators.py:
--------------------------------------------------------------------------------
1 | """
2 | This module is designed to be used as follows::
3 |
4 | from future.builtins.iterators import *
5 |
6 | And then, for example::
7 |
8 | for i in range(10**15):
9 | pass
10 |
11 | for (a, b) in zip(range(10**15), range(-10**15, 0)):
12 | pass
13 |
14 | Note that this is standard Python 3 code, plus some imports that do
15 | nothing on Python 3.
16 |
17 | The iterators this brings in are::
18 |
19 | - ``range``
20 | - ``filter``
21 | - ``map``
22 | - ``zip``
23 |
24 | On Python 2, ``range`` is a pure-Python backport of Python 3's ``range``
25 | iterator with slicing support. The other iterators (``filter``, ``map``,
26 | ``zip``) are from the ``itertools`` module on Python 2. On Python 3 these
27 | are available in the module namespace but not exported for * imports via
28 | __all__ (zero no namespace pollution).
29 |
30 | Note that these are also available in the standard library
31 | ``future_builtins`` module on Python 2 -- but not Python 3, so using
32 | the standard library version is not portable, nor anywhere near complete.
33 | """
34 |
35 | from __future__ import division, absolute_import, print_function
36 |
37 | import itertools
38 | from future import utils
39 |
40 | if not utils.PY3:
41 | filter = itertools.ifilter
42 | map = itertools.imap
43 | from future.types import newrange as range
44 | zip = itertools.izip
45 | __all__ = ['filter', 'map', 'range', 'zip']
46 | else:
47 | import builtins
48 | filter = builtins.filter
49 | map = builtins.map
50 | range = builtins.range
51 | zip = builtins.zip
52 | __all__ = []
53 |
--------------------------------------------------------------------------------
/src/future/builtins/new_min_max.py:
--------------------------------------------------------------------------------
1 | import itertools
2 |
3 | from future import utils
4 | if utils.PY2:
5 | from __builtin__ import max as _builtin_max, min as _builtin_min
6 | else:
7 | from builtins import max as _builtin_max, min as _builtin_min
8 |
9 | _SENTINEL = object()
10 |
11 |
12 | def newmin(*args, **kwargs):
13 | return new_min_max(_builtin_min, *args, **kwargs)
14 |
15 |
16 | def newmax(*args, **kwargs):
17 | return new_min_max(_builtin_max, *args, **kwargs)
18 |
19 |
20 | def new_min_max(_builtin_func, *args, **kwargs):
21 | """
22 | To support the argument "default" introduced in python 3.4 for min and max
23 | :param _builtin_func: builtin min or builtin max
24 | :param args:
25 | :param kwargs:
26 | :return: returns the min or max based on the arguments passed
27 | """
28 |
29 | for key, _ in kwargs.items():
30 | if key not in set(['key', 'default']):
31 | raise TypeError('Illegal argument %s', key)
32 |
33 | if len(args) == 0:
34 | raise TypeError
35 |
36 | if len(args) != 1 and kwargs.get('default', _SENTINEL) is not _SENTINEL:
37 | raise TypeError
38 |
39 | if len(args) == 1:
40 | iterator = iter(args[0])
41 | try:
42 | first = next(iterator)
43 | except StopIteration:
44 | if kwargs.get('default', _SENTINEL) is not _SENTINEL:
45 | return kwargs.get('default')
46 | else:
47 | raise ValueError('{}() arg is an empty sequence'.format(_builtin_func.__name__))
48 | else:
49 | iterator = itertools.chain([first], iterator)
50 | if kwargs.get('key') is not None:
51 | return _builtin_func(iterator, key=kwargs.get('key'))
52 | else:
53 | return _builtin_func(iterator)
54 |
55 | if len(args) > 1:
56 | if kwargs.get('key') is not None:
57 | return _builtin_func(args, key=kwargs.get('key'))
58 | else:
59 | return _builtin_func(args)
60 |
--------------------------------------------------------------------------------
/src/future/builtins/newnext.py:
--------------------------------------------------------------------------------
1 | '''
2 | This module provides a newnext() function in Python 2 that mimics the
3 | behaviour of ``next()`` in Python 3, falling back to Python 2's behaviour for
4 | compatibility if this fails.
5 |
6 | ``newnext(iterator)`` calls the iterator's ``__next__()`` method if it exists. If this
7 | doesn't exist, it falls back to calling a ``next()`` method.
8 |
9 | For example:
10 |
11 | >>> class Odds(object):
12 | ... def __init__(self, start=1):
13 | ... self.value = start - 2
14 | ... def __next__(self): # note the Py3 interface
15 | ... self.value += 2
16 | ... return self.value
17 | ... def __iter__(self):
18 | ... return self
19 | ...
20 | >>> iterator = Odds()
21 | >>> next(iterator)
22 | 1
23 | >>> next(iterator)
24 | 3
25 |
26 | If you are defining your own custom iterator class as above, it is preferable
27 | to explicitly decorate the class with the @implements_iterator decorator from
28 | ``future.utils`` as follows:
29 |
30 | >>> @implements_iterator
31 | ... class Odds(object):
32 | ... # etc
33 | ... pass
34 |
35 | This next() function is primarily for consuming iterators defined in Python 3
36 | code elsewhere that we would like to run on Python 2 or 3.
37 | '''
38 |
39 | _builtin_next = next
40 |
41 | _SENTINEL = object()
42 |
43 | def newnext(iterator, default=_SENTINEL):
44 | """
45 | next(iterator[, default])
46 |
47 | Return the next item from the iterator. If default is given and the iterator
48 | is exhausted, it is returned instead of raising StopIteration.
49 | """
50 |
51 | # args = []
52 | # if default is not _SENTINEL:
53 | # args.append(default)
54 | try:
55 | try:
56 | return iterator.__next__()
57 | except AttributeError:
58 | try:
59 | return iterator.next()
60 | except AttributeError:
61 | raise TypeError("'{0}' object is not an iterator".format(
62 | iterator.__class__.__name__))
63 | except StopIteration as e:
64 | if default is _SENTINEL:
65 | raise e
66 | else:
67 | return default
68 |
69 |
70 | __all__ = ['newnext']
71 |
--------------------------------------------------------------------------------
/src/future/moves/__init__.py:
--------------------------------------------------------------------------------
1 | # future.moves package
2 | from __future__ import absolute_import
3 | import sys
4 | __future_module__ = True
5 | from future.standard_library import import_top_level_modules
6 |
7 | if sys.version_info[0] >= 3:
8 | import_top_level_modules()
9 |
--------------------------------------------------------------------------------
/src/future/moves/_dummy_thread.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3, PY39_PLUS
3 |
4 |
5 | if PY39_PLUS:
6 | # _dummy_thread and dummy_threading modules were both deprecated in
7 | # Python 3.7 and removed in Python 3.9
8 | from _thread import *
9 | elif PY3:
10 | from _dummy_thread import *
11 | else:
12 | __future_module__ = True
13 | from dummy_thread import *
14 |
--------------------------------------------------------------------------------
/src/future/moves/_markupbase.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from _markupbase import *
6 | else:
7 | __future_module__ = True
8 | from markupbase import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/_thread.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from _thread import *
6 | else:
7 | __future_module__ = True
8 | from thread import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/builtins.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from builtins import *
6 | else:
7 | __future_module__ = True
8 | from __builtin__ import *
9 | # Overwrite any old definitions with the equivalent future.builtins ones:
10 | from future.builtins import *
11 |
--------------------------------------------------------------------------------
/src/future/moves/collections.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | from future.utils import PY2, PY26
5 | __future_module__ = True
6 |
7 | from collections import *
8 |
9 | if PY2:
10 | from UserDict import UserDict
11 | from UserList import UserList
12 | from UserString import UserString
13 |
14 | if PY26:
15 | from future.backports.misc import OrderedDict, Counter
16 |
17 | if sys.version_info < (3, 3):
18 | from future.backports.misc import ChainMap, _count_elements
19 |
--------------------------------------------------------------------------------
/src/future/moves/configparser.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY2
4 |
5 | if PY2:
6 | from ConfigParser import *
7 | else:
8 | from configparser import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/copyreg.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | import copyreg, sys
6 | # A "*" import uses Python 3's copyreg.__all__ which does not include
7 | # all public names in the API surface for copyreg, this avoids that
8 | # problem by just making our module _be_ a reference to the actual module.
9 | sys.modules['future.moves.copyreg'] = copyreg
10 | else:
11 | __future_module__ = True
12 | from copy_reg import *
13 |
--------------------------------------------------------------------------------
/src/future/moves/dbm/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from dbm import *
6 | else:
7 | __future_module__ = True
8 | from whichdb import *
9 | from anydbm import *
10 |
11 | # Py3.3's dbm/__init__.py imports ndbm but doesn't expose it via __all__.
12 | # In case some (badly written) code depends on dbm.ndbm after import dbm,
13 | # we simulate this:
14 | if PY3:
15 | from dbm import ndbm
16 | else:
17 | try:
18 | from future.moves.dbm import ndbm
19 | except ImportError:
20 | ndbm = None
21 |
--------------------------------------------------------------------------------
/src/future/moves/dbm/dumb.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from dbm.dumb import *
7 | else:
8 | __future_module__ = True
9 | from dumbdbm import *
10 |
--------------------------------------------------------------------------------
/src/future/moves/dbm/gnu.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from dbm.gnu import *
7 | else:
8 | __future_module__ = True
9 | from gdbm import *
10 |
--------------------------------------------------------------------------------
/src/future/moves/dbm/ndbm.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from dbm.ndbm import *
7 | else:
8 | __future_module__ = True
9 | from dbm import *
10 |
--------------------------------------------------------------------------------
/src/future/moves/html/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 | __future_module__ = True
4 |
5 | if PY3:
6 | from html import *
7 | else:
8 | # cgi.escape isn't good enough for the single Py3.3 html test to pass.
9 | # Define it inline here instead. From the Py3.4 stdlib. Note that the
10 | # html.escape() function from the Py3.3 stdlib is not suitable for use on
11 | # Py2.x.
12 | """
13 | General functions for HTML manipulation.
14 | """
15 |
16 | def escape(s, quote=True):
17 | """
18 | Replace special characters "&", "<" and ">" to HTML-safe sequences.
19 | If the optional flag quote is true (the default), the quotation mark
20 | characters, both double quote (") and single quote (') characters are also
21 | translated.
22 | """
23 | s = s.replace("&", "&") # Must be done first!
24 | s = s.replace("<", "<")
25 | s = s.replace(">", ">")
26 | if quote:
27 | s = s.replace('"', """)
28 | s = s.replace('\'', "'")
29 | return s
30 |
31 | __all__ = ['escape']
32 |
--------------------------------------------------------------------------------
/src/future/moves/html/entities.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from html.entities import *
6 | else:
7 | __future_module__ = True
8 | from htmlentitydefs import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/html/parser.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 | __future_module__ = True
4 |
5 | if PY3:
6 | from html.parser import *
7 | else:
8 | from HTMLParser import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/http/__init__.py:
--------------------------------------------------------------------------------
1 | from future.utils import PY3
2 |
3 | if not PY3:
4 | __future_module__ = True
5 |
--------------------------------------------------------------------------------
/src/future/moves/http/client.py:
--------------------------------------------------------------------------------
1 | from future.utils import PY3
2 |
3 | if PY3:
4 | from http.client import *
5 | else:
6 | from httplib import *
7 | from httplib import HTTPMessage
8 | __future_module__ = True
9 |
--------------------------------------------------------------------------------
/src/future/moves/http/cookiejar.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from http.cookiejar import *
6 | else:
7 | __future_module__ = True
8 | from cookielib import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/http/cookies.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from http.cookies import *
6 | else:
7 | __future_module__ = True
8 | from Cookie import *
9 | from Cookie import Morsel # left out of __all__ on Py2.7!
10 |
--------------------------------------------------------------------------------
/src/future/moves/http/server.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from http.server import *
6 | else:
7 | __future_module__ = True
8 | from BaseHTTPServer import *
9 | from CGIHTTPServer import *
10 | from SimpleHTTPServer import *
11 | try:
12 | from CGIHTTPServer import _url_collapse_path # needed for a test
13 | except ImportError:
14 | try:
15 | # Python 2.7.0 to 2.7.3
16 | from CGIHTTPServer import (
17 | _url_collapse_path_split as _url_collapse_path)
18 | except ImportError:
19 | # Doesn't exist on Python 2.6.x. Ignore it.
20 | pass
21 |
--------------------------------------------------------------------------------
/src/future/moves/itertools.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from itertools import *
4 | try:
5 | zip_longest = izip_longest
6 | filterfalse = ifilterfalse
7 | except NameError:
8 | pass
9 |
--------------------------------------------------------------------------------
/src/future/moves/multiprocessing.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | from multiprocessing import *
5 | if not PY3:
6 | __future_module__ = True
7 | from multiprocessing.queues import SimpleQueue
8 |
--------------------------------------------------------------------------------
/src/future/moves/pickle.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from pickle import *
6 | else:
7 | __future_module__ = True
8 | try:
9 | from cPickle import *
10 | except ImportError:
11 | from pickle import *
12 |
--------------------------------------------------------------------------------
/src/future/moves/queue.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from queue import *
6 | else:
7 | __future_module__ = True
8 | from Queue import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/reprlib.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from reprlib import *
6 | else:
7 | __future_module__ = True
8 | from repr import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/socketserver.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from socketserver import *
6 | else:
7 | __future_module__ = True
8 | from SocketServer import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/subprocess.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY2, PY26
3 |
4 | from subprocess import *
5 |
6 | if PY2:
7 | __future_module__ = True
8 | from commands import getoutput, getstatusoutput
9 |
10 | if PY26:
11 | from future.backports.misc import check_output
12 |
--------------------------------------------------------------------------------
/src/future/moves/sys.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY2
4 |
5 | from sys import *
6 |
7 | if PY2:
8 | from __builtin__ import intern
9 |
--------------------------------------------------------------------------------
/src/future/moves/test/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if not PY3:
5 | __future_module__ = True
6 |
--------------------------------------------------------------------------------
/src/future/moves/test/support.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | import sys
4 |
5 | from future.standard_library import suspend_hooks
6 | from future.utils import PY3
7 |
8 | if PY3:
9 | from test.support import *
10 | if sys.version_info[:2] >= (3, 10):
11 | from test.support.os_helper import (
12 | EnvironmentVarGuard,
13 | TESTFN,
14 | )
15 | from test.support.warnings_helper import check_warnings
16 | else:
17 | __future_module__ = True
18 | with suspend_hooks():
19 | from test.test_support import *
20 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 | __future_module__ = True
4 |
5 | if not PY3:
6 | from Tkinter import *
7 | from Tkinter import (_cnfmerge, _default_root, _flatten,
8 | _support_default_root, _test,
9 | _tkinter, _setit)
10 |
11 | try: # >= 2.7.4
12 | from Tkinter import (_join)
13 | except ImportError:
14 | pass
15 |
16 | try: # >= 2.7.4
17 | from Tkinter import (_stringify)
18 | except ImportError:
19 | pass
20 |
21 | try: # >= 2.7.9
22 | from Tkinter import (_splitdict)
23 | except ImportError:
24 | pass
25 |
26 | else:
27 | from tkinter import *
28 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/colorchooser.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.colorchooser import *
7 | else:
8 | try:
9 | from tkColorChooser import *
10 | except ImportError:
11 | raise ImportError('The tkColorChooser module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/commondialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.commondialog import *
7 | else:
8 | try:
9 | from tkCommonDialog import *
10 | except ImportError:
11 | raise ImportError('The tkCommonDialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/constants.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.constants import *
7 | else:
8 | try:
9 | from Tkconstants import *
10 | except ImportError:
11 | raise ImportError('The Tkconstants module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/dialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.dialog import *
7 | else:
8 | try:
9 | from Dialog import *
10 | except ImportError:
11 | raise ImportError('The Dialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/dnd.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.dnd import *
7 | else:
8 | try:
9 | from Tkdnd import *
10 | except ImportError:
11 | raise ImportError('The Tkdnd module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/filedialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.filedialog import *
7 | else:
8 | try:
9 | from FileDialog import *
10 | except ImportError:
11 | raise ImportError('The FileDialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
14 | try:
15 | from tkFileDialog import *
16 | except ImportError:
17 | raise ImportError('The tkFileDialog module is missing. Does your Py2 '
18 | 'installation include tkinter?')
19 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/font.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.font import *
7 | else:
8 | try:
9 | from tkFont import *
10 | except ImportError:
11 | raise ImportError('The tkFont module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/messagebox.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.messagebox import *
7 | else:
8 | try:
9 | from tkMessageBox import *
10 | except ImportError:
11 | raise ImportError('The tkMessageBox module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/scrolledtext.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.scrolledtext import *
7 | else:
8 | try:
9 | from ScrolledText import *
10 | except ImportError:
11 | raise ImportError('The ScrolledText module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/simpledialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.simpledialog import *
7 | else:
8 | try:
9 | from SimpleDialog import *
10 | except ImportError:
11 | raise ImportError('The SimpleDialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/tix.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.tix import *
7 | else:
8 | try:
9 | from Tix import *
10 | except ImportError:
11 | raise ImportError('The Tix module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/tkinter/ttk.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.ttk import *
7 | else:
8 | try:
9 | from ttk import *
10 | except ImportError:
11 | raise ImportError('The ttk module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/future/moves/urllib/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if not PY3:
5 | __future_module__ = True
6 |
--------------------------------------------------------------------------------
/src/future/moves/urllib/error.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.standard_library import suspend_hooks
3 |
4 | from future.utils import PY3
5 |
6 | if PY3:
7 | from urllib.error import *
8 | else:
9 | __future_module__ = True
10 |
11 | # We use this method to get at the original Py2 urllib before any renaming magic
12 | # ContentTooShortError = sys.py2_modules['urllib'].ContentTooShortError
13 |
14 | with suspend_hooks():
15 | from urllib import ContentTooShortError
16 | from urllib2 import URLError, HTTPError
17 |
--------------------------------------------------------------------------------
/src/future/moves/urllib/parse.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.standard_library import suspend_hooks
3 |
4 | from future.utils import PY3
5 |
6 | if PY3:
7 | from urllib.parse import *
8 | else:
9 | __future_module__ = True
10 | from urlparse import (ParseResult, SplitResult, parse_qs, parse_qsl,
11 | urldefrag, urljoin, urlparse, urlsplit,
12 | urlunparse, urlunsplit)
13 |
14 | # we use this method to get at the original py2 urllib before any renaming
15 | # quote = sys.py2_modules['urllib'].quote
16 | # quote_plus = sys.py2_modules['urllib'].quote_plus
17 | # unquote = sys.py2_modules['urllib'].unquote
18 | # unquote_plus = sys.py2_modules['urllib'].unquote_plus
19 | # urlencode = sys.py2_modules['urllib'].urlencode
20 | # splitquery = sys.py2_modules['urllib'].splitquery
21 |
22 | with suspend_hooks():
23 | from urllib import (quote,
24 | quote_plus,
25 | unquote,
26 | unquote_plus,
27 | urlencode,
28 | splitquery)
29 |
--------------------------------------------------------------------------------
/src/future/moves/urllib/response.py:
--------------------------------------------------------------------------------
1 | from future import standard_library
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from urllib.response import *
6 | else:
7 | __future_module__ = True
8 | with standard_library.suspend_hooks():
9 | from urllib import (addbase,
10 | addclosehook,
11 | addinfo,
12 | addinfourl)
13 |
--------------------------------------------------------------------------------
/src/future/moves/urllib/robotparser.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from urllib.robotparser import *
6 | else:
7 | __future_module__ = True
8 | from robotparser import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/winreg.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from winreg import *
6 | else:
7 | __future_module__ = True
8 | from _winreg import *
9 |
--------------------------------------------------------------------------------
/src/future/moves/xmlrpc/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/src/future/moves/xmlrpc/__init__.py
--------------------------------------------------------------------------------
/src/future/moves/xmlrpc/client.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from xmlrpc.client import *
6 | else:
7 | from xmlrpclib import *
8 |
--------------------------------------------------------------------------------
/src/future/moves/xmlrpc/server.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from xmlrpc.server import *
6 | else:
7 | from xmlrpclib import *
8 |
--------------------------------------------------------------------------------
/src/future/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/src/future/tests/__init__.py
--------------------------------------------------------------------------------
/src/future/types/newdict.py:
--------------------------------------------------------------------------------
1 | """
2 | A dict subclass for Python 2 that behaves like Python 3's dict
3 |
4 | Example use:
5 |
6 | >>> from builtins import dict
7 | >>> d1 = dict() # instead of {} for an empty dict
8 | >>> d2 = dict(key1='value1', key2='value2')
9 |
10 | The keys, values and items methods now return iterators on Python 2.x
11 | (with set-like behaviour on Python 2.7).
12 |
13 | >>> for d in (d1, d2):
14 | ... assert not isinstance(d.keys(), list)
15 | ... assert not isinstance(d.values(), list)
16 | ... assert not isinstance(d.items(), list)
17 | """
18 |
19 | import sys
20 |
21 | from future.utils import with_metaclass
22 | from future.types.newobject import newobject
23 |
24 |
25 | _builtin_dict = dict
26 | ver = sys.version_info
27 |
28 |
29 | class BaseNewDict(type):
30 | def __instancecheck__(cls, instance):
31 | if cls == newdict:
32 | return isinstance(instance, _builtin_dict)
33 | else:
34 | return issubclass(instance.__class__, cls)
35 |
36 |
37 | class newdict(with_metaclass(BaseNewDict, _builtin_dict)):
38 | """
39 | A backport of the Python 3 dict object to Py2
40 | """
41 |
42 | if ver >= (3,):
43 | # Inherit items, keys and values from `dict` in 3.x
44 | pass
45 | elif ver >= (2, 7):
46 | items = dict.viewitems
47 | keys = dict.viewkeys
48 | values = dict.viewvalues
49 | else:
50 | items = dict.iteritems
51 | keys = dict.iterkeys
52 | values = dict.itervalues
53 |
54 | def __new__(cls, *args, **kwargs):
55 | """
56 | dict() -> new empty dictionary
57 | dict(mapping) -> new dictionary initialized from a mapping object's
58 | (key, value) pairs
59 | dict(iterable) -> new dictionary initialized as if via:
60 | d = {}
61 | for k, v in iterable:
62 | d[k] = v
63 | dict(**kwargs) -> new dictionary initialized with the name=value pairs
64 | in the keyword argument list. For example: dict(one=1, two=2)
65 | """
66 |
67 | return super(newdict, cls).__new__(cls, *args)
68 |
69 | def __native__(self):
70 | """
71 | Hook for the future.utils.native() function
72 | """
73 | return dict(self)
74 |
75 |
76 | __all__ = ['newdict']
77 |
--------------------------------------------------------------------------------
/src/future/types/newmemoryview.py:
--------------------------------------------------------------------------------
1 | """
2 | A pretty lame implementation of a memoryview object for Python 2.6.
3 | """
4 | from numbers import Integral
5 | import string
6 |
7 | from future.utils import istext, isbytes, PY2, with_metaclass
8 | from future.types import no, issubset
9 |
10 | if PY2:
11 | from collections import Iterable
12 | else:
13 | from collections.abc import Iterable
14 |
15 | # class BaseNewBytes(type):
16 | # def __instancecheck__(cls, instance):
17 | # return isinstance(instance, _builtin_bytes)
18 |
19 |
20 | class newmemoryview(object): # with_metaclass(BaseNewBytes, _builtin_bytes)):
21 | """
22 | A pretty lame backport of the Python 2.7 and Python 3.x
23 | memoryviewview object to Py2.6.
24 | """
25 | def __init__(self, obj):
26 | return obj
27 |
28 |
29 | __all__ = ['newmemoryview']
30 |
--------------------------------------------------------------------------------
/src/future/types/newopen.py:
--------------------------------------------------------------------------------
1 | """
2 | A substitute for the Python 3 open() function.
3 |
4 | Note that io.open() is more complete but maybe slower. Even so, the
5 | completeness may be a better default. TODO: compare these
6 | """
7 |
8 | _builtin_open = open
9 |
10 | class newopen(object):
11 | """Wrapper providing key part of Python 3 open() interface.
12 |
13 | From IPython's py3compat.py module. License: BSD.
14 | """
15 | def __init__(self, fname, mode="r", encoding="utf-8"):
16 | self.f = _builtin_open(fname, mode)
17 | self.enc = encoding
18 |
19 | def write(self, s):
20 | return self.f.write(s.encode(self.enc))
21 |
22 | def read(self, size=-1):
23 | return self.f.read(size).decode(self.enc)
24 |
25 | def close(self):
26 | return self.f.close()
27 |
28 | def __enter__(self):
29 | return self
30 |
31 | def __exit__(self, etype, value, traceback):
32 | self.f.close()
33 |
--------------------------------------------------------------------------------
/src/html/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] < 3:
5 | from future.moves.html import *
6 | else:
7 | raise ImportError('This package should not be accessible on Python 3. '
8 | 'Either you are trying to run from the python-future src folder '
9 | 'or your installation of python-future is corrupted.')
10 |
--------------------------------------------------------------------------------
/src/html/entities.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from future.utils import PY3
3 |
4 | if PY3:
5 | from html.entities import *
6 | else:
7 | from future.moves.html.entities import *
8 |
--------------------------------------------------------------------------------
/src/html/parser.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 | __future_module__ = True
4 |
5 | if sys.version_info[0] >= 3:
6 | raise ImportError('Cannot import module from python-future source folder')
7 | else:
8 | from future.moves.html.parser import *
9 |
--------------------------------------------------------------------------------
/src/http/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] < 3:
5 | pass
6 | else:
7 | raise ImportError('This package should not be accessible on Python 3. '
8 | 'Either you are trying to run from the python-future src folder '
9 | 'or your installation of python-future is corrupted.')
10 |
--------------------------------------------------------------------------------
/src/http/cookiejar.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | assert sys.version_info[0] < 3
5 |
6 | from cookielib import *
7 |
--------------------------------------------------------------------------------
/src/http/cookies.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | assert sys.version_info[0] < 3
5 |
6 | from Cookie import *
7 | from Cookie import Morsel # left out of __all__ on Py2.7!
8 |
--------------------------------------------------------------------------------
/src/http/server.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | assert sys.version_info[0] < 3
5 |
6 | from BaseHTTPServer import *
7 | from CGIHTTPServer import *
8 | from SimpleHTTPServer import *
9 | try:
10 | from CGIHTTPServer import _url_collapse_path # needed for a test
11 | except ImportError:
12 | try:
13 | # Python 2.7.0 to 2.7.3
14 | from CGIHTTPServer import (
15 | _url_collapse_path_split as _url_collapse_path)
16 | except ImportError:
17 | # Doesn't exist on Python 2.6.x. Ignore it.
18 | pass
19 |
--------------------------------------------------------------------------------
/src/libfuturize/__init__.py:
--------------------------------------------------------------------------------
1 | # empty to make this a package
2 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_add__future__imports_except_unicode_literals.py:
--------------------------------------------------------------------------------
1 | """
2 | Fixer for adding:
3 |
4 | from __future__ import absolute_import
5 | from __future__ import division
6 | from __future__ import print_function
7 |
8 | This is "stage 1": hopefully uncontroversial changes.
9 |
10 | Stage 2 adds ``unicode_literals``.
11 | """
12 |
13 | from lib2to3 import fixer_base
14 | from libfuturize.fixer_util import future_import
15 |
16 | class FixAddFutureImportsExceptUnicodeLiterals(fixer_base.BaseFix):
17 | BM_compatible = True
18 | PATTERN = "file_input"
19 |
20 | run_order = 9
21 |
22 | def transform(self, node, results):
23 | # Reverse order:
24 | future_import(u"absolute_import", node)
25 | future_import(u"division", node)
26 | future_import(u"print_function", node)
27 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_basestring.py:
--------------------------------------------------------------------------------
1 | """
2 | Fixer that adds ``from past.builtins import basestring`` if there is a
3 | reference to ``basestring``
4 | """
5 |
6 | from lib2to3 import fixer_base
7 |
8 | from libfuturize.fixer_util import touch_import_top
9 |
10 |
11 | class FixBasestring(fixer_base.BaseFix):
12 | BM_compatible = True
13 |
14 | PATTERN = "'basestring'"
15 |
16 | def transform(self, node, results):
17 | touch_import_top(u'past.builtins', 'basestring', node)
18 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_bytes.py:
--------------------------------------------------------------------------------
1 | """Optional fixer that changes all unprefixed string literals "..." to b"...".
2 |
3 | br'abcd' is a SyntaxError on Python 2 but valid on Python 3.
4 | ur'abcd' is a SyntaxError on Python 3 but valid on Python 2.
5 |
6 | """
7 | from __future__ import unicode_literals
8 |
9 | import re
10 | from lib2to3.pgen2 import token
11 | from lib2to3 import fixer_base
12 |
13 | _literal_re = re.compile(r"[^bBuUrR]?[\'\"]")
14 |
15 | class FixBytes(fixer_base.BaseFix):
16 | BM_compatible = True
17 | PATTERN = "STRING"
18 |
19 | def transform(self, node, results):
20 | if node.type == token.STRING:
21 | if _literal_re.match(node.value):
22 | new = node.clone()
23 | new.value = u'b' + new.value
24 | return new
25 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_cmp.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | """
3 | Fixer for the cmp() function on Py2, which was removed in Py3.
4 |
5 | Adds this import line::
6 |
7 | from past.builtins import cmp
8 |
9 | if cmp() is called in the code.
10 | """
11 |
12 | from __future__ import unicode_literals
13 | from lib2to3 import fixer_base
14 |
15 | from libfuturize.fixer_util import touch_import_top
16 |
17 |
18 | expression = "name='cmp'"
19 |
20 |
21 | class FixCmp(fixer_base.BaseFix):
22 | BM_compatible = True
23 | run_order = 9
24 |
25 | PATTERN = """
26 | power<
27 | ({0}) trailer< '(' args=[any] ')' >
28 | rest=any* >
29 | """.format(expression)
30 |
31 | def transform(self, node, results):
32 | name = results["name"]
33 | touch_import_top(u'past.builtins', name.value, node)
34 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_division.py:
--------------------------------------------------------------------------------
1 | """
2 | UNFINISHED
3 | For the ``future`` package.
4 |
5 | Adds this import line:
6 |
7 | from __future__ import division
8 |
9 | at the top so the code runs identically on Py3 and Py2.6/2.7
10 | """
11 |
12 | from libpasteurize.fixes.fix_division import FixDivision
13 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_execfile.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | """
3 | Fixer for the execfile() function on Py2, which was removed in Py3.
4 |
5 | The Lib/lib2to3/fixes/fix_execfile.py module has some problems: see
6 | python-future issue #37. This fixer merely imports execfile() from
7 | past.builtins and leaves the code alone.
8 |
9 | Adds this import line::
10 |
11 | from past.builtins import execfile
12 |
13 | for the function execfile() that was removed from Py3.
14 | """
15 |
16 | from __future__ import unicode_literals
17 | from lib2to3 import fixer_base
18 |
19 | from libfuturize.fixer_util import touch_import_top
20 |
21 |
22 | expression = "name='execfile'"
23 |
24 |
25 | class FixExecfile(fixer_base.BaseFix):
26 | BM_compatible = True
27 | run_order = 9
28 |
29 | PATTERN = """
30 | power<
31 | ({0}) trailer< '(' args=[any] ')' >
32 | rest=any* >
33 | """.format(expression)
34 |
35 | def transform(self, node, results):
36 | name = results["name"]
37 | touch_import_top(u'past.builtins', name.value, node)
38 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_future_builtins.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | Adds this import line::
5 |
6 | from builtins import XYZ
7 |
8 | for each of the functions XYZ that is used in the module.
9 |
10 | Adds these imports after any other imports (in an initial block of them).
11 | """
12 |
13 | from __future__ import unicode_literals
14 |
15 | from lib2to3 import fixer_base
16 | from lib2to3.pygram import python_symbols as syms
17 | from lib2to3.fixer_util import Name, Call, in_special_context
18 |
19 | from libfuturize.fixer_util import touch_import_top
20 |
21 | # All builtins are:
22 | # from future.builtins.iterators import (filter, map, zip)
23 | # from future.builtins.misc import (ascii, chr, hex, input, isinstance, oct, open, round, super)
24 | # from future.types import (bytes, dict, int, range, str)
25 | # We don't need isinstance any more.
26 |
27 | replaced_builtin_fns = '''filter map zip
28 | ascii chr hex input next oct
29 | bytes range str raw_input'''.split()
30 | # This includes raw_input as a workaround for the
31 | # lib2to3 fixer for raw_input on Py3 (only), allowing
32 | # the correct import to be included. (Py3 seems to run
33 | # the fixers the wrong way around, perhaps ignoring the
34 | # run_order class attribute below ...)
35 |
36 | expression = '|'.join(["name='{0}'".format(name) for name in replaced_builtin_fns])
37 |
38 |
39 | class FixFutureBuiltins(fixer_base.BaseFix):
40 | BM_compatible = True
41 | run_order = 7
42 |
43 | # Currently we only match uses as a function. This doesn't match e.g.:
44 | # if isinstance(s, str):
45 | # ...
46 | PATTERN = """
47 | power<
48 | ({0}) trailer< '(' [arglist=any] ')' >
49 | rest=any* >
50 | |
51 | power<
52 | 'map' trailer< '(' [arglist=any] ')' >
53 | >
54 | """.format(expression)
55 |
56 | def transform(self, node, results):
57 | name = results["name"]
58 | touch_import_top(u'builtins', name.value, node)
59 | # name.replace(Name(u"input", prefix=name.prefix))
60 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_future_standard_library.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | Changes any imports needed to reflect the standard library reorganization. Also
5 | Also adds these import lines:
6 |
7 | from future import standard_library
8 | standard_library.install_aliases()
9 |
10 | after any __future__ imports but before any other imports.
11 | """
12 |
13 | from lib2to3.fixes.fix_imports import FixImports
14 | from libfuturize.fixer_util import touch_import_top
15 |
16 |
17 | class FixFutureStandardLibrary(FixImports):
18 | run_order = 8
19 |
20 | def transform(self, node, results):
21 | result = super(FixFutureStandardLibrary, self).transform(node, results)
22 | # TODO: add a blank line between any __future__ imports and this?
23 | touch_import_top(u'future', u'standard_library', node)
24 | return result
25 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_future_standard_library_urllib.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | A special fixer that ensures that these lines have been added::
5 |
6 | from future import standard_library
7 | standard_library.install_hooks()
8 |
9 | even if the only module imported was ``urllib``, in which case the regular fixer
10 | wouldn't have added these lines.
11 |
12 | """
13 |
14 | from lib2to3.fixes.fix_urllib import FixUrllib
15 | from libfuturize.fixer_util import touch_import_top, find_root
16 |
17 |
18 | class FixFutureStandardLibraryUrllib(FixUrllib): # not a subclass of FixImports
19 | run_order = 8
20 |
21 | def transform(self, node, results):
22 | # transform_member() in lib2to3/fixes/fix_urllib.py breaks node so find_root(node)
23 | # no longer works after the super() call below. So we find the root first:
24 | root = find_root(node)
25 | result = super(FixFutureStandardLibraryUrllib, self).transform(node, results)
26 | # TODO: add a blank line between any __future__ imports and this?
27 | touch_import_top(u'future', u'standard_library', root)
28 | return result
29 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_input.py:
--------------------------------------------------------------------------------
1 | """
2 | Fixer for input.
3 |
4 | Does a check for `from builtins import input` before running the lib2to3 fixer.
5 | The fixer will not run when the input is already present.
6 |
7 |
8 | this:
9 | a = input()
10 | becomes:
11 | from builtins import input
12 | a = eval(input())
13 |
14 | and this:
15 | from builtins import input
16 | a = input()
17 | becomes (no change):
18 | from builtins import input
19 | a = input()
20 | """
21 |
22 | import lib2to3.fixes.fix_input
23 | from lib2to3.fixer_util import does_tree_import
24 |
25 |
26 | class FixInput(lib2to3.fixes.fix_input.FixInput):
27 | def transform(self, node, results):
28 |
29 | if does_tree_import('builtins', 'input', node):
30 | return
31 |
32 | return super(FixInput, self).transform(node, results)
33 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_object.py:
--------------------------------------------------------------------------------
1 | """
2 | Fixer that adds ``from builtins import object`` if there is a line
3 | like this:
4 | class Foo(object):
5 | """
6 |
7 | from lib2to3 import fixer_base
8 |
9 | from libfuturize.fixer_util import touch_import_top
10 |
11 |
12 | class FixObject(fixer_base.BaseFix):
13 |
14 | PATTERN = u"classdef< 'class' NAME '(' name='object' ')' colon=':' any >"
15 |
16 | def transform(self, node, results):
17 | touch_import_top(u'builtins', 'object', node)
18 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_oldstr_wrap.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | Adds this import line:
5 |
6 | from past.builtins import str as oldstr
7 |
8 | at the top and wraps any unadorned string literals 'abc' or explicit byte-string
9 | literals b'abc' in oldstr() calls so the code has the same behaviour on Py3 as
10 | on Py2.6/2.7.
11 | """
12 |
13 | from __future__ import unicode_literals
14 | import re
15 | from lib2to3 import fixer_base
16 | from lib2to3.pgen2 import token
17 | from lib2to3.fixer_util import syms
18 | from libfuturize.fixer_util import (future_import, touch_import_top,
19 | wrap_in_fn_call)
20 |
21 |
22 | _literal_re = re.compile(r"[^uUrR]?[\'\"]")
23 |
24 |
25 | class FixOldstrWrap(fixer_base.BaseFix):
26 | BM_compatible = True
27 | PATTERN = "STRING"
28 |
29 | def transform(self, node, results):
30 | if node.type == token.STRING:
31 | touch_import_top(u'past.types', u'oldstr', node)
32 | if _literal_re.match(node.value):
33 | new = node.clone()
34 | # Strip any leading space or comments:
35 | # TODO: check: do we really want to do this?
36 | new.prefix = u''
37 | new.value = u'b' + new.value
38 | wrapped = wrap_in_fn_call("oldstr", [new], prefix=node.prefix)
39 | return wrapped
40 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_order___future__imports.py:
--------------------------------------------------------------------------------
1 | """
2 | UNFINISHED
3 |
4 | Fixer for turning multiple lines like these:
5 |
6 | from __future__ import division
7 | from __future__ import absolute_import
8 | from __future__ import print_function
9 |
10 | into a single line like this:
11 |
12 | from __future__ import (absolute_import, division, print_function)
13 |
14 | This helps with testing of ``futurize``.
15 | """
16 |
17 | from lib2to3 import fixer_base
18 | from libfuturize.fixer_util import future_import
19 |
20 | class FixOrderFutureImports(fixer_base.BaseFix):
21 | BM_compatible = True
22 | PATTERN = "file_input"
23 |
24 | run_order = 10
25 |
26 | # def match(self, node):
27 | # """
28 | # Match only once per file
29 | # """
30 | # if hasattr(node, 'type') and node.type == syms.file_input:
31 | # return True
32 | # return False
33 |
34 | def transform(self, node, results):
35 | # TODO # write me
36 | pass
37 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_print_with_import.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | Turns any print statements into functions and adds this import line:
5 |
6 | from __future__ import print_function
7 |
8 | at the top to retain compatibility with Python 2.6+.
9 | """
10 |
11 | from libfuturize.fixes.fix_print import FixPrint
12 | from libfuturize.fixer_util import future_import
13 |
14 | class FixPrintWithImport(FixPrint):
15 | run_order = 7
16 | def transform(self, node, results):
17 | # Add the __future__ import first. (Otherwise any shebang or encoding
18 | # comment line attached as a prefix to the print statement will be
19 | # copied twice and appear twice.)
20 | future_import(u'print_function', node)
21 | n_stmt = super(FixPrintWithImport, self).transform(node, results)
22 | return n_stmt
23 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_remove_old__future__imports.py:
--------------------------------------------------------------------------------
1 | """
2 | Fixer for removing any of these lines:
3 |
4 | from __future__ import with_statement
5 | from __future__ import nested_scopes
6 | from __future__ import generators
7 |
8 | The reason is that __future__ imports like these are required to be the first
9 | line of code (after docstrings) on Python 2.6+, which can get in the way.
10 |
11 | These imports are always enabled in Python 2.6+, which is the minimum sane
12 | version to target for Py2/3 compatibility.
13 | """
14 |
15 | from lib2to3 import fixer_base
16 | from libfuturize.fixer_util import remove_future_import
17 |
18 | class FixRemoveOldFutureImports(fixer_base.BaseFix):
19 | BM_compatible = True
20 | PATTERN = "file_input"
21 | run_order = 1
22 |
23 | def transform(self, node, results):
24 | remove_future_import(u"with_statement", node)
25 | remove_future_import(u"nested_scopes", node)
26 | remove_future_import(u"generators", node)
27 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_unicode_keep_u.py:
--------------------------------------------------------------------------------
1 | """Fixer that changes unicode to str and unichr to chr, but -- unlike the
2 | lib2to3 fix_unicode.py fixer, does not change u"..." into "...".
3 |
4 | The reason is that Py3.3+ supports the u"..." string prefix, and, if
5 | present, the prefix may provide useful information for disambiguating
6 | between byte strings and unicode strings, which is often the hardest part
7 | of the porting task.
8 |
9 | """
10 |
11 | from lib2to3.pgen2 import token
12 | from lib2to3 import fixer_base
13 |
14 | _mapping = {u"unichr" : u"chr", u"unicode" : u"str"}
15 |
16 | class FixUnicodeKeepU(fixer_base.BaseFix):
17 | BM_compatible = True
18 | PATTERN = "'unicode' | 'unichr'"
19 |
20 | def transform(self, node, results):
21 | if node.type == token.NAME:
22 | new = node.clone()
23 | new.value = _mapping[node.value]
24 | return new
25 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_unicode_literals_import.py:
--------------------------------------------------------------------------------
1 | """
2 | Adds this import:
3 |
4 | from __future__ import unicode_literals
5 |
6 | """
7 |
8 | from lib2to3 import fixer_base
9 | from libfuturize.fixer_util import future_import
10 |
11 | class FixUnicodeLiteralsImport(fixer_base.BaseFix):
12 | BM_compatible = True
13 | PATTERN = "file_input"
14 |
15 | run_order = 9
16 |
17 | def transform(self, node, results):
18 | future_import(u"unicode_literals", node)
19 |
--------------------------------------------------------------------------------
/src/libfuturize/fixes/fix_xrange_with_import.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | Turns any xrange calls into range calls and adds this import line:
5 |
6 | from builtins import range
7 |
8 | at the top.
9 | """
10 |
11 | from lib2to3.fixes.fix_xrange import FixXrange
12 |
13 | from libfuturize.fixer_util import touch_import_top
14 |
15 |
16 | class FixXrangeWithImport(FixXrange):
17 | def transform(self, node, results):
18 | result = super(FixXrangeWithImport, self).transform(node, results)
19 | touch_import_top('builtins', 'range', node)
20 | return result
21 |
--------------------------------------------------------------------------------
/src/libpasteurize/__init__.py:
--------------------------------------------------------------------------------
1 | # empty to make this a package
2 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/feature_base.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Base classes for features that are backwards-incompatible.
3 |
4 | Usage:
5 | features = Features()
6 | features.add(Feature("py3k_feature", "power< 'py3k' any* >", "2.7"))
7 | PATTERN = features.PATTERN
8 | """
9 |
10 | pattern_unformatted = u"%s=%s" # name=pattern, for dict lookups
11 | message_unformatted = u"""
12 | %s is only supported in Python %s and above."""
13 |
14 | class Feature(object):
15 | u"""
16 | A feature has a name, a pattern, and a minimum version of Python 2.x
17 | required to use the feature (or 3.x if there is no backwards-compatible
18 | version of 2.x)
19 | """
20 | def __init__(self, name, PATTERN, version):
21 | self.name = name
22 | self._pattern = PATTERN
23 | self.version = version
24 |
25 | def message_text(self):
26 | u"""
27 | Format the above text with the name and minimum version required.
28 | """
29 | return message_unformatted % (self.name, self.version)
30 |
31 | class Features(set):
32 | u"""
33 | A set of features that generates a pattern for the features it contains.
34 | This set will act like a mapping in that we map names to patterns.
35 | """
36 | mapping = {}
37 |
38 | def update_mapping(self):
39 | u"""
40 | Called every time we care about the mapping of names to features.
41 | """
42 | self.mapping = dict([(f.name, f) for f in iter(self)])
43 |
44 | @property
45 | def PATTERN(self):
46 | u"""
47 | Uses the mapping of names to features to return a PATTERN suitable
48 | for using the lib2to3 patcomp.
49 | """
50 | self.update_mapping()
51 | return u" |\n".join([pattern_unformatted % (f.name, f._pattern) for f in iter(self)])
52 |
53 | def __getitem__(self, key):
54 | u"""
55 | Implement a simple mapping to get patterns from names.
56 | """
57 | return self.mapping[key]
58 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_add_all__future__imports.py:
--------------------------------------------------------------------------------
1 | """
2 | Fixer for adding:
3 |
4 | from __future__ import absolute_import
5 | from __future__ import division
6 | from __future__ import print_function
7 | from __future__ import unicode_literals
8 |
9 | This is done when converting from Py3 to both Py3/Py2.
10 | """
11 |
12 | from lib2to3 import fixer_base
13 | from libfuturize.fixer_util import future_import
14 |
15 | class FixAddAllFutureImports(fixer_base.BaseFix):
16 | BM_compatible = True
17 | PATTERN = "file_input"
18 | run_order = 1
19 |
20 | def transform(self, node, results):
21 | future_import(u"absolute_import", node)
22 | future_import(u"division", node)
23 | future_import(u"print_function", node)
24 | future_import(u"unicode_literals", node)
25 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_add_all_future_builtins.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | Adds this import line::
5 |
6 | from builtins import (ascii, bytes, chr, dict, filter, hex, input,
7 | int, list, map, next, object, oct, open, pow,
8 | range, round, str, super, zip)
9 |
10 | to a module, irrespective of whether each definition is used.
11 |
12 | Adds these imports after any other imports (in an initial block of them).
13 | """
14 |
15 | from __future__ import unicode_literals
16 |
17 | from lib2to3 import fixer_base
18 |
19 | from libfuturize.fixer_util import touch_import_top
20 |
21 |
22 | class FixAddAllFutureBuiltins(fixer_base.BaseFix):
23 | BM_compatible = True
24 | PATTERN = "file_input"
25 | run_order = 1
26 |
27 | def transform(self, node, results):
28 | # import_str = """(ascii, bytes, chr, dict, filter, hex, input,
29 | # int, list, map, next, object, oct, open, pow,
30 | # range, round, str, super, zip)"""
31 | touch_import_top(u'builtins', '*', node)
32 |
33 | # builtins = """ascii bytes chr dict filter hex input
34 | # int list map next object oct open pow
35 | # range round str super zip"""
36 | # for builtin in sorted(builtins.split(), reverse=True):
37 | # touch_import_top(u'builtins', builtin, node)
38 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_add_future_standard_library_import.py:
--------------------------------------------------------------------------------
1 | """
2 | For the ``future`` package.
3 |
4 | Adds this import line:
5 |
6 | from future import standard_library
7 |
8 | after any __future__ imports but before any other imports. Doesn't actually
9 | change the imports to Py3 style.
10 | """
11 |
12 | from lib2to3 import fixer_base
13 | from libfuturize.fixer_util import touch_import_top
14 |
15 | class FixAddFutureStandardLibraryImport(fixer_base.BaseFix):
16 | BM_compatible = True
17 | PATTERN = "file_input"
18 | run_order = 8
19 |
20 | def transform(self, node, results):
21 | # TODO: add a blank line between any __future__ imports and this?
22 | touch_import_top(u'future', u'standard_library', node)
23 | # TODO: also add standard_library.install_hooks()
24 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_annotations.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer to remove function annotations
3 | """
4 |
5 | from lib2to3 import fixer_base
6 | from lib2to3.pgen2 import token
7 | from lib2to3.fixer_util import syms
8 |
9 | warning_text = u"Removing function annotations completely."
10 |
11 | def param_without_annotations(node):
12 | return node.children[0]
13 |
14 | class FixAnnotations(fixer_base.BaseFix):
15 |
16 | warned = False
17 |
18 | def warn_once(self, node, reason):
19 | if not self.warned:
20 | self.warned = True
21 | self.warning(node, reason=reason)
22 |
23 | PATTERN = u"""
24 | funcdef< 'def' any parameters< '(' [params=any] ')' > ['->' ret=any] ':' any* >
25 | """
26 |
27 | def transform(self, node, results):
28 | u"""
29 | This just strips annotations from the funcdef completely.
30 | """
31 | params = results.get(u"params")
32 | ret = results.get(u"ret")
33 | if ret is not None:
34 | assert ret.prev_sibling.type == token.RARROW, u"Invalid return annotation"
35 | self.warn_once(node, reason=warning_text)
36 | ret.prev_sibling.remove()
37 | ret.remove()
38 | if params is None: return
39 | if params.type == syms.typedargslist:
40 | # more than one param in a typedargslist
41 | for param in params.children:
42 | if param.type == syms.tname:
43 | self.warn_once(node, reason=warning_text)
44 | param.replace(param_without_annotations(param))
45 | elif params.type == syms.tname:
46 | # one param
47 | self.warn_once(node, reason=warning_text)
48 | params.replace(param_without_annotations(params))
49 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_division.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer for division: from __future__ import division if needed
3 | """
4 |
5 | from lib2to3 import fixer_base
6 | from libfuturize.fixer_util import token, future_import
7 |
8 | def match_division(node):
9 | u"""
10 | __future__.division redefines the meaning of a single slash for division,
11 | so we match that and only that.
12 | """
13 | slash = token.SLASH
14 | return node.type == slash and not node.next_sibling.type == slash and \
15 | not node.prev_sibling.type == slash
16 |
17 | class FixDivision(fixer_base.BaseFix):
18 | run_order = 4 # this seems to be ignored?
19 |
20 | def match(self, node):
21 | u"""
22 | Since the tree needs to be fixed once and only once if and only if it
23 | matches, then we can start discarding matches after we make the first.
24 | """
25 | return match_division(node)
26 |
27 | def transform(self, node, results):
28 | future_import(u"division", node)
29 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_fullargspec.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer for getfullargspec -> getargspec
3 | """
4 |
5 | from lib2to3 import fixer_base
6 | from lib2to3.fixer_util import Name
7 |
8 | warn_msg = u"some of the values returned by getfullargspec are not valid in Python 2 and have no equivalent."
9 |
10 | class FixFullargspec(fixer_base.BaseFix):
11 |
12 | PATTERN = u"'getfullargspec'"
13 |
14 | def transform(self, node, results):
15 | self.warning(node, warn_msg)
16 | return Name(u"getargspec", prefix=node.prefix)
17 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_future_builtins.py:
--------------------------------------------------------------------------------
1 | """
2 | Adds this import line:
3 |
4 | from builtins import XYZ
5 |
6 | for each of the functions XYZ that is used in the module.
7 | """
8 |
9 | from __future__ import unicode_literals
10 |
11 | from lib2to3 import fixer_base
12 | from lib2to3.pygram import python_symbols as syms
13 | from lib2to3.fixer_util import Name, Call, in_special_context
14 |
15 | from libfuturize.fixer_util import touch_import_top
16 |
17 | # All builtins are:
18 | # from future.builtins.iterators import (filter, map, zip)
19 | # from future.builtins.misc import (ascii, chr, hex, input, isinstance, oct, open, round, super)
20 | # from future.types import (bytes, dict, int, range, str)
21 | # We don't need isinstance any more.
22 |
23 | replaced_builtins = '''filter map zip
24 | ascii chr hex input next oct open round super
25 | bytes dict int range str'''.split()
26 |
27 | expression = '|'.join(["name='{0}'".format(name) for name in replaced_builtins])
28 |
29 |
30 | class FixFutureBuiltins(fixer_base.BaseFix):
31 | BM_compatible = True
32 | run_order = 9
33 |
34 | # Currently we only match uses as a function. This doesn't match e.g.:
35 | # if isinstance(s, str):
36 | # ...
37 | PATTERN = """
38 | power<
39 | ({0}) trailer< '(' args=[any] ')' >
40 | rest=any* >
41 | """.format(expression)
42 |
43 | def transform(self, node, results):
44 | name = results["name"]
45 | touch_import_top(u'builtins', name.value, node)
46 | # name.replace(Name(u"input", prefix=name.prefix))
47 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_getcwd.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer for os.getcwd() -> os.getcwdu().
3 | Also warns about "from os import getcwd", suggesting the above form.
4 | """
5 |
6 | from lib2to3 import fixer_base
7 | from lib2to3.fixer_util import Name
8 |
9 | class FixGetcwd(fixer_base.BaseFix):
10 |
11 | PATTERN = u"""
12 | power< 'os' trailer< dot='.' name='getcwd' > any* >
13 | |
14 | import_from< 'from' 'os' 'import' bad='getcwd' >
15 | """
16 |
17 | def transform(self, node, results):
18 | if u"name" in results:
19 | name = results[u"name"]
20 | name.replace(Name(u"getcwdu", prefix=name.prefix))
21 | elif u"bad" in results:
22 | # Can't convert to getcwdu and then expect to catch every use.
23 | self.cannot_convert(node, u"import os, use os.getcwd() instead.")
24 | return
25 | else:
26 | raise ValueError(u"For some reason, the pattern matcher failed.")
27 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_memoryview.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer for memoryview(s) -> buffer(s).
3 | Explicit because some memoryview methods are invalid on buffer objects.
4 | """
5 |
6 | from lib2to3 import fixer_base
7 | from lib2to3.fixer_util import Name
8 |
9 |
10 | class FixMemoryview(fixer_base.BaseFix):
11 |
12 | explicit = True # User must specify that they want this.
13 |
14 | PATTERN = u"""
15 | power< name='memoryview' trailer< '(' [any] ')' >
16 | rest=any* >
17 | """
18 |
19 | def transform(self, node, results):
20 | name = results[u"name"]
21 | name.replace(Name(u"buffer", prefix=name.prefix))
22 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_newstyle.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer for "class Foo: ..." -> "class Foo(object): ..."
3 | """
4 |
5 | from lib2to3 import fixer_base
6 | from lib2to3.fixer_util import LParen, RParen, Name
7 |
8 | from libfuturize.fixer_util import touch_import_top
9 |
10 |
11 | def insert_object(node, idx):
12 | node.insert_child(idx, RParen())
13 | node.insert_child(idx, Name(u"object"))
14 | node.insert_child(idx, LParen())
15 |
16 | class FixNewstyle(fixer_base.BaseFix):
17 |
18 | # Match:
19 | # class Blah:
20 | # and:
21 | # class Blah():
22 |
23 | PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
24 |
25 | def transform(self, node, results):
26 | colon = results[u"colon"]
27 | idx = node.children.index(colon)
28 | if (node.children[idx-2].value == '(' and
29 | node.children[idx-1].value == ')'):
30 | del node.children[idx-2:idx]
31 | idx -= 2
32 | insert_object(node, idx)
33 | touch_import_top(u'builtins', 'object', node)
34 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_next.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer for:
3 | it.__next__() -> it.next().
4 | next(it) -> it.next().
5 | """
6 |
7 | from lib2to3.pgen2 import token
8 | from lib2to3.pygram import python_symbols as syms
9 | from lib2to3 import fixer_base
10 | from lib2to3.fixer_util import Name, Call, find_binding, Attr
11 |
12 | bind_warning = u"Calls to builtin next() possibly shadowed by global binding"
13 |
14 |
15 | class FixNext(fixer_base.BaseFix):
16 |
17 | PATTERN = u"""
18 | power< base=any+ trailer< '.' attr='__next__' > any* >
19 | |
20 | power< head='next' trailer< '(' arg=any ')' > any* >
21 | |
22 | classdef< 'class' base=any+ ':'
23 | suite< any*
24 | funcdef< 'def'
25 | attr='__next__'
26 | parameters< '(' NAME ')' > any+ >
27 | any* > >
28 | """
29 |
30 | def transform(self, node, results):
31 | assert results
32 |
33 | base = results.get(u"base")
34 | attr = results.get(u"attr")
35 | head = results.get(u"head")
36 | arg_ = results.get(u"arg")
37 | if arg_:
38 | arg = arg_.clone()
39 | head.replace(Attr(Name(unicode(arg),prefix=head.prefix),
40 | Name(u"next")))
41 | arg_.remove()
42 | elif base:
43 | attr.replace(Name(u"next", prefix=attr.prefix))
44 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_printfunction.py:
--------------------------------------------------------------------------------
1 | u"""
2 | Fixer for print: from __future__ import print_function.
3 | """
4 |
5 | from lib2to3 import fixer_base
6 | from libfuturize.fixer_util import future_import
7 |
8 | class FixPrintfunction(fixer_base.BaseFix):
9 |
10 | # explicit = True
11 |
12 | PATTERN = u"""
13 | power< 'print' trailer < '(' any* ')' > any* >
14 | """
15 |
16 | def transform(self, node, results):
17 | future_import(u"print_function", node)
18 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_raise.py:
--------------------------------------------------------------------------------
1 | u"""Fixer for 'raise E(V).with_traceback(T)' -> 'raise E, V, T'"""
2 |
3 | from lib2to3 import fixer_base
4 | from lib2to3.fixer_util import Comma, Node, Leaf, token, syms
5 |
6 | class FixRaise(fixer_base.BaseFix):
7 |
8 | PATTERN = u"""
9 | raise_stmt< 'raise' (power< name=any [trailer< '(' val=any* ')' >]
10 | [trailer< '.' 'with_traceback' > trailer< '(' trc=any ')' >] > | any) ['from' chain=any] >"""
11 |
12 | def transform(self, node, results):
13 | name, val, trc = (results.get(u"name"), results.get(u"val"), results.get(u"trc"))
14 | chain = results.get(u"chain")
15 | if chain is not None:
16 | self.warning(node, u"explicit exception chaining is not supported in Python 2")
17 | chain.prev_sibling.remove()
18 | chain.remove()
19 | if trc is not None:
20 | val = val[0] if val else Leaf(token.NAME, u"None")
21 | val.prefix = trc.prefix = u" "
22 | kids = [Leaf(token.NAME, u"raise"), name.clone(), Comma(),
23 | val.clone(), Comma(), trc.clone()]
24 | raise_stmt = Node(syms.raise_stmt, kids)
25 | node.replace(raise_stmt)
26 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_raise_.py:
--------------------------------------------------------------------------------
1 | u"""Fixer for
2 | raise E(V).with_traceback(T)
3 | to:
4 | from future.utils import raise_
5 | ...
6 | raise_(E, V, T)
7 |
8 | TODO: FIXME!!
9 |
10 | """
11 |
12 | from lib2to3 import fixer_base
13 | from lib2to3.fixer_util import Comma, Node, Leaf, token, syms
14 |
15 | class FixRaise(fixer_base.BaseFix):
16 |
17 | PATTERN = u"""
18 | raise_stmt< 'raise' (power< name=any [trailer< '(' val=any* ')' >]
19 | [trailer< '.' 'with_traceback' > trailer< '(' trc=any ')' >] > | any) ['from' chain=any] >"""
20 |
21 | def transform(self, node, results):
22 | FIXME
23 | name, val, trc = (results.get(u"name"), results.get(u"val"), results.get(u"trc"))
24 | chain = results.get(u"chain")
25 | if chain is not None:
26 | self.warning(node, u"explicit exception chaining is not supported in Python 2")
27 | chain.prev_sibling.remove()
28 | chain.remove()
29 | if trc is not None:
30 | val = val[0] if val else Leaf(token.NAME, u"None")
31 | val.prefix = trc.prefix = u" "
32 | kids = [Leaf(token.NAME, u"raise"), name.clone(), Comma(),
33 | val.clone(), Comma(), trc.clone()]
34 | raise_stmt = Node(syms.raise_stmt, kids)
35 | node.replace(raise_stmt)
36 |
--------------------------------------------------------------------------------
/src/libpasteurize/fixes/fix_throw.py:
--------------------------------------------------------------------------------
1 | u"""Fixer for 'g.throw(E(V).with_traceback(T))' -> 'g.throw(E, V, T)'"""
2 |
3 | from lib2to3 import fixer_base
4 | from lib2to3.pytree import Node, Leaf
5 | from lib2to3.pgen2 import token
6 | from lib2to3.fixer_util import Comma
7 |
8 | class FixThrow(fixer_base.BaseFix):
9 |
10 | PATTERN = u"""
11 | power< any trailer< '.' 'throw' >
12 | trailer< '(' args=power< exc=any trailer< '(' val=any* ')' >
13 | trailer< '.' 'with_traceback' > trailer< '(' trc=any ')' > > ')' > >
14 | """
15 |
16 | def transform(self, node, results):
17 | syms = self.syms
18 | exc, val, trc = (results[u"exc"], results[u"val"], results[u"trc"])
19 | val = val[0] if val else Leaf(token.NAME, u"None")
20 | val.prefix = trc.prefix = u" "
21 | kids = [exc.clone(), Comma(), val.clone(), Comma(), trc.clone()]
22 | args = results[u"args"]
23 | args.children = kids
24 |
--------------------------------------------------------------------------------
/src/past/builtins/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | A resurrection of some old functions from Python 2 for use in Python 3. These
3 | should be used sparingly, to help with porting efforts, since code using them
4 | is no longer standard Python 3 code.
5 |
6 | This module provides the following:
7 |
8 | 1. Implementations of these builtin functions which have no equivalent on Py3:
9 |
10 | - apply
11 | - chr
12 | - cmp
13 | - execfile
14 |
15 | 2. Aliases:
16 |
17 | - intern <- sys.intern
18 | - raw_input <- input
19 | - reduce <- functools.reduce
20 | - reload <- imp.reload
21 | - unichr <- chr
22 | - unicode <- str
23 | - xrange <- range
24 |
25 | 3. List-producing versions of the corresponding Python 3 iterator-producing functions:
26 |
27 | - filter
28 | - map
29 | - range
30 | - zip
31 |
32 | 4. Forward-ported Py2 types:
33 |
34 | - basestring
35 | - dict
36 | - str
37 | - long
38 | - unicode
39 |
40 | """
41 |
42 | from future.utils import PY3
43 | from past.builtins.noniterators import (filter, map, range, reduce, zip)
44 | # from past.builtins.misc import (ascii, hex, input, oct, open)
45 | if PY3:
46 | from past.types import (basestring,
47 | olddict as dict,
48 | oldstr as str,
49 | long,
50 | unicode)
51 | else:
52 | from __builtin__ import (basestring, dict, str, long, unicode)
53 |
54 | from past.builtins.misc import (apply, chr, cmp, execfile, intern, oct,
55 | raw_input, reload, unichr, unicode, xrange)
56 | from past import utils
57 |
58 |
59 | if utils.PY3:
60 | # We only import names that shadow the builtins on Py3. No other namespace
61 | # pollution on Py3.
62 |
63 | # Only shadow builtins on Py3; no new names
64 | __all__ = ['filter', 'map', 'range', 'reduce', 'zip',
65 | 'basestring', 'dict', 'str', 'long', 'unicode',
66 | 'apply', 'chr', 'cmp', 'execfile', 'intern', 'raw_input',
67 | 'reload', 'unichr', 'xrange'
68 | ]
69 |
70 | else:
71 | # No namespace pollution on Py2
72 | __all__ = []
73 |
--------------------------------------------------------------------------------
/src/past/types/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | Forward-ports of types from Python 2 for use with Python 3:
3 |
4 | - ``basestring``: equivalent to ``(str, bytes)`` in ``isinstance`` checks
5 | - ``dict``: with list-producing .keys() etc. methods
6 | - ``str``: bytes-like, but iterating over them doesn't product integers
7 | - ``long``: alias of Py3 int with ``L`` suffix in the ``repr``
8 | - ``unicode``: alias of Py3 str with ``u`` prefix in the ``repr``
9 |
10 | """
11 |
12 | from past import utils
13 |
14 | if utils.PY2:
15 | import __builtin__
16 | basestring = __builtin__.basestring
17 | dict = __builtin__.dict
18 | str = __builtin__.str
19 | long = __builtin__.long
20 | unicode = __builtin__.unicode
21 | __all__ = []
22 | else:
23 | from .basestring import basestring
24 | from .olddict import olddict
25 | from .oldstr import oldstr
26 | long = int
27 | unicode = str
28 | # from .unicode import unicode
29 | __all__ = ['basestring', 'olddict', 'oldstr', 'long', 'unicode']
30 |
--------------------------------------------------------------------------------
/src/past/types/basestring.py:
--------------------------------------------------------------------------------
1 | """
2 | An implementation of the basestring type for Python 3
3 |
4 | Example use:
5 |
6 | >>> s = b'abc'
7 | >>> assert isinstance(s, basestring)
8 | >>> from past.types import str as oldstr
9 | >>> s2 = oldstr(b'abc')
10 | >>> assert isinstance(s2, basestring)
11 |
12 | """
13 |
14 | import sys
15 |
16 | from past.utils import with_metaclass, PY2
17 |
18 | if PY2:
19 | str = unicode
20 |
21 | ver = sys.version_info[:2]
22 |
23 |
24 | class BaseBaseString(type):
25 | def __instancecheck__(cls, instance):
26 | return isinstance(instance, (bytes, str))
27 |
28 | def __subclasscheck__(cls, subclass):
29 | return super(BaseBaseString, cls).__subclasscheck__(subclass) or issubclass(subclass, (bytes, str))
30 |
31 |
32 | class basestring(with_metaclass(BaseBaseString)):
33 | """
34 | A minimal backport of the Python 2 basestring type to Py3
35 | """
36 |
37 |
38 | __all__ = ['basestring']
39 |
--------------------------------------------------------------------------------
/src/queue/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 | __future_module__ = True
4 |
5 | if sys.version_info[0] < 3:
6 | from Queue import *
7 | else:
8 | raise ImportError('This package should not be accessible on Python 3. '
9 | 'Either you are trying to run from the python-future src folder '
10 | 'or your installation of python-future is corrupted.')
11 |
--------------------------------------------------------------------------------
/src/reprlib/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] < 3:
5 | from repr import *
6 | else:
7 | raise ImportError('This package should not be accessible on Python 3. '
8 | 'Either you are trying to run from the python-future src folder '
9 | 'or your installation of python-future is corrupted.')
10 |
--------------------------------------------------------------------------------
/src/socketserver/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] < 3:
5 | from SocketServer import *
6 | else:
7 | raise ImportError('This package should not be accessible on Python 3. '
8 | 'Either you are trying to run from the python-future src folder '
9 | 'or your installation of python-future is corrupted.')
10 |
--------------------------------------------------------------------------------
/src/tkinter/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] < 3:
5 | from Tkinter import *
6 | from Tkinter import (_cnfmerge, _default_root, _flatten,
7 | _support_default_root, _test,
8 | _tkinter, _setit)
9 |
10 | try: # >= 2.7.4
11 | from Tkinter import (_join)
12 | except ImportError:
13 | pass
14 |
15 | try: # >= 2.7.4
16 | from Tkinter import (_stringify)
17 | except ImportError:
18 | pass
19 |
20 | try: # >= 2.7.9
21 | from Tkinter import (_splitdict)
22 | except ImportError:
23 | pass
24 |
25 | else:
26 | raise ImportError('This package should not be accessible on Python 3. '
27 | 'Either you are trying to run from the python-future src folder '
28 | 'or your installation of python-future is corrupted.')
29 |
--------------------------------------------------------------------------------
/src/tkinter/colorchooser.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.colorchooser import *
7 | else:
8 | try:
9 | from tkColorChooser import *
10 | except ImportError:
11 | raise ImportError('The tkColorChooser module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/commondialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.commondialog import *
7 | else:
8 | try:
9 | from tkCommonDialog import *
10 | except ImportError:
11 | raise ImportError('The tkCommonDialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/constants.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.constants import *
7 | else:
8 | try:
9 | from Tkconstants import *
10 | except ImportError:
11 | raise ImportError('The Tkconstants module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/dialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.dialog import *
7 | else:
8 | try:
9 | from Dialog import *
10 | except ImportError:
11 | raise ImportError('The Dialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/dnd.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.dnd import *
7 | else:
8 | try:
9 | from Tkdnd import *
10 | except ImportError:
11 | raise ImportError('The Tkdnd module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/filedialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.filedialog import *
7 | else:
8 | try:
9 | from FileDialog import *
10 | except ImportError:
11 | raise ImportError('The FileDialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 | try:
14 | from tkFileDialog import *
15 | except ImportError:
16 | raise ImportError('The tkFileDialog module is missing. Does your Py2 '
17 | 'installation include tkinter?')
18 |
--------------------------------------------------------------------------------
/src/tkinter/font.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.font import *
7 | else:
8 | try:
9 | from tkFont import *
10 | except ImportError:
11 | raise ImportError('The tkFont module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/messagebox.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.messagebox import *
7 | else:
8 | try:
9 | from tkMessageBox import *
10 | except ImportError:
11 | raise ImportError('The tkMessageBox module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/scrolledtext.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.scrolledtext import *
7 | else:
8 | try:
9 | from ScrolledText import *
10 | except ImportError:
11 | raise ImportError('The ScrolledText module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/simpledialog.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.simpledialog import *
7 | else:
8 | try:
9 | from SimpleDialog import *
10 | except ImportError:
11 | raise ImportError('The SimpleDialog module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/tix.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.tix import *
7 | else:
8 | try:
9 | from Tix import *
10 | except ImportError:
11 | raise ImportError('The Tix module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/tkinter/ttk.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.utils import PY3
4 |
5 | if PY3:
6 | from tkinter.ttk import *
7 | else:
8 | try:
9 | from ttk import *
10 | except ImportError:
11 | raise ImportError('The ttk module is missing. Does your Py2 '
12 | 'installation include tkinter?')
13 |
--------------------------------------------------------------------------------
/src/winreg/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 | __future_module__ = True
4 |
5 | if sys.version_info[0] < 3:
6 | from _winreg import *
7 | else:
8 | raise ImportError('This package should not be accessible on Python 3. '
9 | 'Either you are trying to run from the python-future src folder '
10 | 'or your installation of python-future is corrupted.')
11 |
--------------------------------------------------------------------------------
/src/xmlrpc/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] < 3:
5 | pass
6 | else:
7 | raise ImportError('This package should not be accessible on Python 3. '
8 | 'Either you are trying to run from the python-future src folder '
9 | 'or your installation of python-future is corrupted.')
10 |
--------------------------------------------------------------------------------
/src/xmlrpc/client.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | assert sys.version_info[0] < 3
5 | from xmlrpclib import *
6 |
--------------------------------------------------------------------------------
/src/xmlrpc/server.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import sys
3 |
4 | assert sys.version_info[0] < 3
5 | from xmlrpclib import *
6 |
--------------------------------------------------------------------------------
/test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -exo pipefail
4 |
5 | python --version
6 |
7 | if [ -e "/root/pip" ]
8 | then
9 | pip install /root/pip/*.zip /root/pip/*.whl /root/pip/*tar.gz
10 | else
11 | pip install pytest unittest2
12 | fi
13 |
14 | pytag="py${PYTHON_VERSION//./}"
15 |
16 | python setup.py bdist_wheel --python-tag="${pytag}"
17 | pip install dist/future-*-${pytag}-none-any.whl
18 | pytest tests/
19 |
--------------------------------------------------------------------------------
/tests/test_future/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/tests/test_future/__init__.py
--------------------------------------------------------------------------------
/tests/test_future/test_builtins_explicit_import.py:
--------------------------------------------------------------------------------
1 | """
2 | Tests to make sure that all builtins can be imported explicitly from the
3 | future.builtins namespace.
4 | """
5 |
6 | from __future__ import absolute_import, division, unicode_literals
7 | from future.builtins import (filter, map, zip)
8 | from future.builtins import (ascii, chr, hex, input, isinstance, next, oct, open)
9 | from future.builtins import (bytes, dict, int, range, round, str, super)
10 | from future.tests.base import unittest
11 |
12 |
13 | class TestBuiltinsExplicitImport(unittest.TestCase):
14 | pass
15 |
16 |
17 | if __name__ == '__main__':
18 | unittest.main()
19 |
--------------------------------------------------------------------------------
/tests/test_future/test_common_iterators.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from future.builtins.iterators import *
4 | from future.tests.base import unittest
5 |
6 |
7 | class TestIterators(unittest.TestCase):
8 | def test_range(self):
9 | self.assertNotEqual(type(range(10)), list)
10 | self.assertEqual(sum(range(10)), 45)
11 | self.assertTrue(9 in range(10))
12 | self.assertEqual(list(range(5)), [0, 1, 2, 3, 4])
13 | self.assertEqual(repr(range(10)), 'range(0, 10)')
14 | self.assertEqual(repr(range(1, 10)), 'range(1, 10)')
15 | self.assertEqual(repr(range(1, 1)), 'range(1, 1)')
16 | self.assertEqual(repr(range(-10, 10, 2)), 'range(-10, 10, 2)')
17 |
18 | def test_map(self):
19 | def square(x):
20 | return x**2
21 | self.assertNotEqual(type(map(square, range(10))), list)
22 | self.assertEqual(sum(map(square, range(10))), 285)
23 | self.assertEqual(list(map(square, range(3))), [0, 1, 4])
24 |
25 | def test_zip(self):
26 | a = range(10)
27 | b = ['a', 'b', 'c']
28 | self.assertNotEqual(type(zip(a, b)), list)
29 | self.assertEqual(list(zip(a, b)), [(0, 'a'), (1, 'b'), (2, 'c')])
30 |
31 | def test_filter(self):
32 | a = range(10)
33 | def is_odd(x):
34 | return x % 2 == 1
35 | self.assertNotEqual(type(filter(is_odd, a)), list)
36 | self.assertEqual(list(filter(is_odd, a)), [1, 3, 5, 7, 9])
37 |
38 | if __name__ == '__main__':
39 | unittest.main()
40 |
--------------------------------------------------------------------------------
/tests/test_future/test_count.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Tests for the backported class:`range` class.
4 | """
5 | from itertools import count as it_count
6 |
7 | from future.backports.misc import count
8 | from future.tests.base import unittest, skip26
9 |
10 |
11 | class CountTest(unittest.TestCase):
12 |
13 | """Test the count function."""
14 |
15 | def _test_count_func(self, func):
16 | self.assertEqual(next(func(1)), 1)
17 | self.assertEqual(next(func(start=1)), 1)
18 |
19 | c = func()
20 | self.assertEqual(next(c), 0)
21 | self.assertEqual(next(c), 1)
22 | self.assertEqual(next(c), 2)
23 | c = func(1, 1)
24 | self.assertEqual(next(c), 1)
25 | self.assertEqual(next(c), 2)
26 | c = func(step=1)
27 | self.assertEqual(next(c), 0)
28 | self.assertEqual(next(c), 1)
29 | c = func(start=1, step=1)
30 | self.assertEqual(next(c), 1)
31 | self.assertEqual(next(c), 2)
32 |
33 | c = func(-1)
34 | self.assertEqual(next(c), -1)
35 | self.assertEqual(next(c), 0)
36 | self.assertEqual(next(c), 1)
37 | c = func(1, -1)
38 | self.assertEqual(next(c), 1)
39 | self.assertEqual(next(c), 0)
40 | self.assertEqual(next(c), -1)
41 | c = func(-1, -1)
42 | self.assertEqual(next(c), -1)
43 | self.assertEqual(next(c), -2)
44 | self.assertEqual(next(c), -3)
45 |
46 | def test_count(self):
47 | """Test the count function."""
48 | self._test_count_func(count)
49 |
50 | @skip26
51 | def test_own_count(self):
52 | """Test own count implementation."""
53 | self._test_count_func(it_count)
54 |
55 |
56 | if __name__ == '__main__':
57 | unittest.main()
58 |
--------------------------------------------------------------------------------
/tests/test_future/test_decorators.py:
--------------------------------------------------------------------------------
1 | """
2 | Tests to make sure the decorators (implements_iterator and
3 | python2_unicode_compatible) are working.
4 | """
5 |
6 | from __future__ import absolute_import, division
7 | from future import utils
8 | from future.builtins import *
9 | from future.utils import implements_iterator, python_2_unicode_compatible
10 | from future.tests.base import unittest
11 |
12 |
13 | class TestDecorators(unittest.TestCase):
14 | def test_python_2_unicode_compatible_decorator(self):
15 | my_unicode_str = u'Unicode string: \u5b54\u5b50'
16 | # With the decorator:
17 | @python_2_unicode_compatible
18 | class A(object):
19 | def __str__(self):
20 | return my_unicode_str
21 | a = A()
22 | assert len(str(a)) == 18
23 | if not utils.PY3:
24 | assert hasattr(a, '__unicode__')
25 | self.assertEqual(str(a), my_unicode_str)
26 | self.assertTrue(isinstance(str(a).encode('utf-8'), bytes))
27 |
28 | # Manual equivalent on Py2 without the decorator:
29 | if not utils.PY3:
30 | class B(object):
31 | def __unicode__(self):
32 | return u'Unicode string: \u5b54\u5b50'
33 | def __str__(self):
34 | return unicode(self).encode('utf-8')
35 | b = B()
36 | assert str(a) == str(b)
37 |
38 | def test_implements_iterator(self):
39 |
40 | @implements_iterator
41 | class MyIter(object):
42 | def __next__(self):
43 | return 'Next!'
44 | def __iter__(self):
45 | return self
46 |
47 | itr = MyIter()
48 | self.assertEqual(next(itr), 'Next!')
49 |
50 | itr2 = MyIter()
51 | for i, item in enumerate(itr2):
52 | if i >= 3:
53 | break
54 | self.assertEqual(item, 'Next!')
55 |
56 | if __name__ == '__main__':
57 | unittest.main()
58 |
--------------------------------------------------------------------------------
/tests/test_future/test_email_generation.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Tests for email generation."""
3 |
4 | from __future__ import unicode_literals
5 |
6 | from future.backports.email.mime.multipart import MIMEMultipart
7 | from future.backports.email.mime.text import MIMEText
8 | from future.backports.email.utils import formatdate
9 | from future.tests.base import unittest
10 |
11 |
12 | class EmailGenerationTests(unittest.TestCase):
13 | def test_email_custom_header_can_contain_unicode(self):
14 | msg = MIMEMultipart()
15 | alternative = MIMEMultipart('alternative')
16 | alternative.attach(MIMEText('Plain content with Únicødê', _subtype='plain', _charset='utf-8'))
17 | alternative.attach(MIMEText('HTML content with Únicødê', _subtype='html', _charset='utf-8'))
18 | msg.attach(alternative)
19 |
20 | msg['Subject'] = 'Subject with Únicødê'
21 | msg['From'] = 'sender@test.com'
22 | msg['To'] = 'recipient@test.com'
23 | msg['Date'] = formatdate(None, localtime=True)
24 | msg['Message-ID'] = 'anIdWithÚnicødêForThisEmail'
25 |
26 | msg_lines = msg.as_string().split('\n')
27 | self.assertEqual(msg_lines[2], 'Subject: =?utf-8?b?U3ViamVjdCB3aXRoIMOabmljw7hkw6o=?=')
28 | self.assertEqual(msg_lines[6], 'Message-ID: =?utf-8?b?YW5JZFdpdGjDmm5pY8O4ZMOqRm9yVGhpc0VtYWls?=')
29 | self.assertEqual(msg_lines[17], 'UGxhaW4gY29udGVudCB3aXRoIMOabmljw7hkw6o=')
30 | self.assertEqual(msg_lines[24], 'SFRNTCBjb250ZW50IHdpdGggw5puaWPDuGTDqg==')
31 |
--------------------------------------------------------------------------------
/tests/test_future/test_email_multipart.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Tests for multipart emails."""
3 |
4 | from future.tests.base import unittest
5 | import future.backports.email as email
6 | import future.backports.email.mime.multipart
7 | from future.builtins import list
8 |
9 | class EmailMultiPartTests(unittest.TestCase):
10 | """Tests for handling multipart email Messages."""
11 |
12 | def test_multipart_serialize_without_boundary(self):
13 | """Tests that serializing an empty multipart email does not fail."""
14 | multipart_message = email.mime.multipart.MIMEMultipart()
15 | self.assertIsNot(multipart_message.as_string(), None)
16 |
17 | def test_multipart_set_boundary_does_not_change_header_type(self):
18 | """
19 | Tests that Message.set_boundary() does not cause Python2 errors.
20 |
21 | In particular, tests that set_boundary does not cause the type of the
22 | message headers list to be changed from the future built-in list.
23 | """
24 | multipart_message = email.mime.multipart.MIMEMultipart()
25 | headers_type = type(multipart_message._headers)
26 | self.assertEqual(headers_type, type(list()))
27 |
28 | boundary = '===============6387699881409002085=='
29 | multipart_message.set_boundary(boundary)
30 | headers_type = type(multipart_message._headers)
31 | self.assertEqual(headers_type, type(list()))
32 |
--------------------------------------------------------------------------------
/tests/test_future/test_explicit_imports.py:
--------------------------------------------------------------------------------
1 | """
2 | This tests whether explicit imports like
3 |
4 | from future.builtins import str, range
5 |
6 | etc. all work as expected on both Python 2 and Python 3.
7 |
8 | """
9 |
10 | from __future__ import absolute_import, print_function, unicode_literals
11 |
12 | import copy
13 |
14 | from future import utils
15 | from future.tests.base import unittest
16 |
17 |
18 | class TestExplicitImports(unittest.TestCase):
19 | def test_py3_builtin_imports(self):
20 | from future.builtins import (input,
21 | filter,
22 | map,
23 | range,
24 | round,
25 | super,
26 | str,
27 | zip)
28 |
29 | def test_py2k_disabled_builtins(self):
30 | """
31 | On Py2 these should import.
32 | """
33 | if not utils.PY3:
34 | from future.builtins.disabled import (apply,
35 | cmp,
36 | coerce,
37 | execfile,
38 | file,
39 | long,
40 | raw_input,
41 | reduce,
42 | reload,
43 | unicode,
44 | xrange,
45 | StandardError)
46 |
47 |
48 | if __name__ == '__main__':
49 | unittest.main()
50 |
--------------------------------------------------------------------------------
/tests/test_future/test_html.py:
--------------------------------------------------------------------------------
1 | """
2 | Tests for the html module functions.
3 |
4 | Adapted for the python-future module from the Python 3.3 standard library tests.
5 | """
6 |
7 | from __future__ import unicode_literals
8 | from future import standard_library
9 |
10 | with standard_library.hooks():
11 | import html
12 |
13 | from future.tests.base import unittest
14 |
15 |
16 | class HtmlTests(unittest.TestCase):
17 | def test_escape(self):
18 | self.assertEqual(
19 | html.escape('\'\''),
20 | ''<script>"&foo;"</script>'')
21 | self.assertEqual(
22 | html.escape('\'\'', False),
23 | '\'<script>"&foo;"</script>\'')
24 |
25 |
26 | if __name__ == '__main__':
27 | unittest.main()
28 |
--------------------------------------------------------------------------------
/tests/test_future/test_import_star.py:
--------------------------------------------------------------------------------
1 | """
2 | This tests whether
3 |
4 | from future.builtins import *
5 |
6 | works as expected:
7 | - This should NOT introduce namespace pollution on Py3.
8 | - On Python 2, this should not introduce any symbols that aren't in
9 | __builtin__.
10 |
11 | """
12 |
13 | from __future__ import absolute_import, print_function, unicode_literals
14 |
15 | import copy
16 |
17 | from future import utils
18 | from future.tests.base import unittest, skip26
19 |
20 |
21 | original_locals = set(copy.copy(locals()))
22 | original_globals = set(copy.copy(globals()))
23 | new_names = set(['original_locals', 'original_globals', 'new_names'])
24 | from future.builtins import *
25 | new_locals = set(copy.copy(locals())) - new_names - original_locals
26 | new_globals = set(copy.copy(globals())) - new_names - original_globals - \
27 | set(['new_locals'])
28 |
29 |
30 | class TestImportStar(unittest.TestCase):
31 | def test_namespace_pollution_locals(self):
32 | if utils.PY3:
33 | self.assertEqual(len(new_locals), 0,
34 | 'namespace pollution: {0}'.format(new_locals))
35 | else:
36 | pass # maybe check that no new symbols are introduced
37 |
38 | def test_namespace_pollution_globals(self):
39 | if utils.PY3:
40 | self.assertEqual(len(new_globals), 0,
41 | 'namespace pollution: {0}'.format(new_globals))
42 | else:
43 | pass # maybe check that no new symbols are introduced
44 |
45 | def test_iterators(self):
46 | self.assertNotEqual(type(range(10)), list)
47 |
48 | def test_super(self):
49 | pass
50 |
51 | def test_str(self):
52 | self.assertIsNot(str, bytes) # Py2: assertIsNot only in 2.7
53 | self.assertEqual(str('blah'), u'blah') # Py3.3 and Py2 only
54 |
55 | def test_python_2_unicode_compatible_decorator(self):
56 | # This should not be in the namespace
57 | assert 'python_2_unicode_compatible' not in locals()
58 |
59 |
60 | if __name__ == '__main__':
61 | unittest.main()
62 |
--------------------------------------------------------------------------------
/tests/test_future/test_imports_httplib.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, print_function
2 | import sys
3 |
4 | from future.utils import PY2
5 | from future.tests.base import unittest
6 |
7 |
8 | class ImportHttplibTest(unittest.TestCase):
9 | def test_issue_159(self):
10 | """
11 | The latest version of urllib3 (as of 2015-07-25)
12 | uses http.client.HTTPMessage, which isn't normally
13 | exported on Py2 through __all__ in httplib.py.
14 | """
15 | from http.client import HTTPMessage
16 | if PY2:
17 | import mimetools
18 | assert issubclass(HTTPMessage, mimetools.Message)
19 | else:
20 | import email.message
21 | assert issubclass(HTTPMessage, email.message.Message)
22 |
23 |
24 | if __name__ == '__main__':
25 | unittest.main()
26 |
--------------------------------------------------------------------------------
/tests/test_future/test_imports_urllib.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, print_function
2 |
3 | import sys
4 | from future.tests.base import unittest
5 | from future.standard_library import install_aliases
6 |
7 |
8 | class ImportUrllibTest(unittest.TestCase):
9 | def test_urllib(self):
10 | """
11 | Tests that urllib isn't changed from under our feet. (This might not
12 | even be a problem?)
13 | """
14 | from future import standard_library
15 | import urllib
16 | orig_file = urllib.__file__
17 | with standard_library.hooks():
18 | import urllib.response
19 | self.assertEqual(orig_file, urllib.__file__)
20 |
21 | def test_issue_158(self):
22 | """
23 | CherryPy conditional import in _cpcompat.py: issue 158
24 | """
25 | install_aliases()
26 | try:
27 | from urllib.parse import unquote as parse_unquote
28 |
29 | def unquote_qs(atom, encoding, errors='strict'):
30 | return parse_unquote(
31 | atom.replace('+', ' '),
32 | encoding=encoding,
33 | errors=errors)
34 | except ImportError:
35 | from urllib import unquote as parse_unquote
36 |
37 | def unquote_qs(atom, encoding, errors='strict'):
38 | return parse_unquote(atom.replace('+', ' ')).decode(encoding, errors)
39 | self.assertEqual(unquote_qs('/%7Econnolly/', 'utf-8'),
40 | '/~connolly/')
41 |
42 |
43 | if __name__ == '__main__':
44 | unittest.main()
45 |
--------------------------------------------------------------------------------
/tests/test_future/test_py2_str_literals_to_bytes.py:
--------------------------------------------------------------------------------
1 | a = '123'
2 |
--------------------------------------------------------------------------------
/tests/test_future/test_urllib_response.py:
--------------------------------------------------------------------------------
1 | """Unit tests for code in urllib.response."""
2 |
3 | from __future__ import absolute_import, division, unicode_literals
4 |
5 | from future.backports import urllib
6 | import future.backports.urllib.response as urllib_response
7 | from future.backports.test import support as test_support
8 | from future.tests.base import unittest
9 |
10 |
11 | class File(object):
12 |
13 | def __init__(self):
14 | self.closed = False
15 |
16 | def read(self, bytes):
17 | pass
18 |
19 | def readline(self):
20 | pass
21 |
22 | def close(self):
23 | self.closed = True
24 |
25 |
26 | class Testaddbase(unittest.TestCase):
27 |
28 | # TODO(jhylton): Write tests for other functionality of addbase()
29 |
30 | def setUp(self):
31 | self.fp = File()
32 | self.addbase = urllib_response.addbase(self.fp)
33 |
34 | def test_with(self):
35 | def f():
36 | with self.addbase as spam:
37 | pass
38 | self.assertFalse(self.fp.closed)
39 | f()
40 | self.assertTrue(self.fp.closed)
41 | self.assertRaises(ValueError, f)
42 |
43 |
44 | if __name__ == '__main__':
45 | unittest.main()
46 |
--------------------------------------------------------------------------------
/tests/test_past/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PythonCharmers/python-future/2d56f83adab5a0957cfc5abbe62db1e2d1912b61/tests/test_past/__init__.py
--------------------------------------------------------------------------------
/tests/test_past/test_basestring.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Tests for the Py2-like class:`basestring` type.
4 | """
5 |
6 | from __future__ import absolute_import, unicode_literals, print_function
7 | import os
8 |
9 | from past import utils
10 | from future.tests.base import unittest
11 | from past.builtins import basestring, str as oldstr
12 |
13 |
14 | class TestBaseString(unittest.TestCase):
15 |
16 | def test_isinstance(self):
17 | s = b'abc'
18 | self.assertTrue(isinstance(s, basestring))
19 | s2 = oldstr(b'abc')
20 | self.assertTrue(isinstance(s2, basestring))
21 |
22 | def test_issubclass(self):
23 | self.assertTrue(issubclass(str, basestring))
24 | self.assertTrue(issubclass(bytes, basestring))
25 | self.assertTrue(issubclass(basestring, basestring))
26 | self.assertFalse(issubclass(int, basestring))
27 | self.assertFalse(issubclass(list, basestring))
28 | self.assertTrue(issubclass(basestring, object))
29 |
30 | class CustomString(basestring):
31 | pass
32 | class NotString(object):
33 | pass
34 | class OldStyleClass:
35 | pass
36 | self.assertTrue(issubclass(CustomString, basestring))
37 | self.assertFalse(issubclass(NotString, basestring))
38 | self.assertFalse(issubclass(OldStyleClass, basestring))
39 |
40 |
41 |
42 | if __name__ == '__main__':
43 | unittest.main()
44 |
--------------------------------------------------------------------------------
/tests/test_past/test_misc.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Tests for the resurrected Py2-like cmp function
4 | """
5 |
6 | from __future__ import absolute_import, unicode_literals, print_function
7 |
8 | import os.path
9 | import sys
10 | import traceback
11 | from contextlib import contextmanager
12 |
13 | from future.tests.base import unittest
14 | from future.utils import PY3, PY26
15 |
16 | if PY3:
17 | from past.builtins import cmp
18 |
19 | _dir = os.path.dirname(os.path.abspath(__file__))
20 | sys.path.append(_dir)
21 | import test_values
22 |
23 |
24 | @contextmanager
25 | def empty_context_manager(*args, **kwargs):
26 | yield dict(args=args, kwargs=kwargs)
27 |
28 |
29 | class TestCmp(unittest.TestCase):
30 | def test_cmp(self):
31 | for x, y, cmp_python2_value in test_values.cmp_python2_value:
32 | if PY26:
33 | # set cmp works a bit differently in 2.6, we try to emulate 2.7 behavior, so skip set cmp tests
34 | if isinstance(x, set) or isinstance(y, set):
35 | continue
36 | # to get this to run on python <3.4 which lacks subTest
37 | with getattr(self, 'subTest', empty_context_manager)(x=x, y=y):
38 | try:
39 | past_cmp_value = cmp(x, y)
40 | except Exception:
41 | past_cmp_value = traceback.format_exc().strip().split('\n')[-1]
42 |
43 | self.assertEqual(cmp_python2_value, past_cmp_value,
44 | "expected result matching python2 __builtins__.cmp({x!r},{y!r}) "
45 | "== {cmp_python2_value} "
46 | "got past.builtins.cmp({x!r},{y!r}) "
47 | "== {past_cmp_value} "
48 | "".format(x=x, y=y, past_cmp_value=past_cmp_value,
49 | cmp_python2_value=cmp_python2_value))
50 |
51 |
52 | if __name__ == '__main__':
53 | unittest.main()
54 |
--------------------------------------------------------------------------------
/tests/test_past/test_noniterators.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Tests for the Py2-like list-producing functions
4 | """
5 |
6 | from __future__ import absolute_import, unicode_literals, print_function
7 | import os
8 |
9 | from past import utils
10 | from future.tests.base import unittest
11 | from past.builtins import filter, map, range, zip
12 |
13 |
14 | class TestNonIterators(unittest.TestCase):
15 |
16 | def test_noniterators_produce_lists(self):
17 | l = range(10)
18 | self.assertTrue(isinstance(l, list))
19 |
20 | l2 = zip(l, list('ABCDE')*2)
21 | self.assertTrue(isinstance(l2, list))
22 |
23 | double = lambda x: x*2
24 | l3 = map(double, l)
25 | self.assertTrue(isinstance(l3, list))
26 |
27 | is_odd = lambda x: x % 2 == 1
28 | l4 = filter(is_odd, range(10))
29 | self.assertEqual(l4, [1, 3, 5, 7, 9])
30 | self.assertTrue(isinstance(l4, list))
31 |
32 |
33 | if __name__ == '__main__':
34 | unittest.main()
35 |
--------------------------------------------------------------------------------
/tests/test_past/test_oldstr.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Tests for the resurrected Py2-like 8-bit string type.
4 | """
5 |
6 | from __future__ import absolute_import, unicode_literals, print_function
7 |
8 | from numbers import Integral
9 | from future.tests.base import unittest
10 | from past.builtins import str as oldstr
11 | from past.types.oldstr import unescape
12 |
13 |
14 | class TestOldStr(unittest.TestCase):
15 | def test_repr(self):
16 | s1 = oldstr(b'abc')
17 | self.assertEqual(repr(s1), "'abc'")
18 | s2 = oldstr(b'abc\ndef')
19 | self.assertEqual(repr(s2), "'abc\\ndef'")
20 |
21 | def test_str(self):
22 | s1 = oldstr(b'abc')
23 | self.assertEqual(str(s1), 'abc')
24 | s2 = oldstr(b'abc\ndef')
25 | self.assertEqual(str(s2), 'abc\ndef')
26 |
27 | def test_unescape(self):
28 | self.assertEqual(unescape('abc\\ndef'), 'abc\ndef')
29 | s = unescape(r'a\\b\c\\d') # i.e. 'a\\\\b\\c\\\\d'
30 | self.assertEqual(str(s), r'a\b\c\d')
31 | s2 = unescape(r'abc\\ndef') # i.e. 'abc\\\\ndef'
32 | self.assertEqual(str(s2), r'abc\ndef')
33 |
34 | def test_getitem(self):
35 | s = oldstr(b'abc')
36 |
37 | self.assertNotEqual(s[0], 97)
38 | self.assertEqual(s[0], b'a')
39 | self.assertEqual(s[0], oldstr(b'a'))
40 |
41 | self.assertEqual(s[1:], b'bc')
42 | self.assertEqual(s[1:], oldstr(b'bc'))
43 |
44 |
45 | if __name__ == '__main__':
46 | unittest.main()
47 |
--------------------------------------------------------------------------------