nine


Namenine JSON
Version 1.1.0 PyPI version JSON
download
home_pagehttps://github.com/nandoflorestan/nine
SummaryPython 2 / 3 compatibility, like six, but favouring Python 3
upload_time2020-01-21 20:10:27
maintainer
docs_urlNone
authorNando Florestan
requires_python
licensePublic domain
keywords python 2
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            Let's write Python 3 right now!
===============================

When the best Python 2/Python 3 compatibility modules -- especially the famous
`*six* library invented by Benjamin Peterson <https://pypi.python.org/pypi/six>`_
-- were created, they were written from the point of view of a Python 2
programmer starting to grok Python 3.  If you use *six*,
your code is compatible, but stuck in Python 2 idioms.

**nine** turns **six** upside down. You write your code using Python 3 idioms
-- as much as possible --, and it is the Python 2 "version" that is patched.
Needless to say, this approach is more future-proof.

When thou writeth Python, thou shalt write Python 3 and,
just for a little longer, ensure that the thing worketh on Python 2.7.

*nine* facilitates this point of view. You can write code
that is as 3ish as possible while still supporting 2.6.

For instance, you don't type ``unicode`` anymore, you type ``str``, and *nine*
makes ``str`` point to ``unicode`` on Python 2 (if you use our boilerplate).
Also, ``map``, ``zip`` and ``filter`` have Python 3 behaviour, on Python 2,
meaning they return iterators, not lists.

Honestly you should not spend one thought on Python 2.6 anymore, it is
`no longer supported <https://mail.python.org/pipermail/python-dev/2013-September/128287.html>`_
since its final release (2.6.9) in October 2013. Nobody uses 3.0 or 3.1 either.

Python 2.7 has finally met its demise on the first day of 2020.

*nine* is extremely stable and unlikely to change since it solves an old
problem that never changes.  Nobody should be surprised if *nine* isn't
updated for months or even years.

The author(s) of *nine* donate this module to the public domain.

To understand most of the intricacies involved in achieving 2&3 compatibility
in a single codebase, I recommend reading this:
http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/


Using nine
==========

In each of your modules, start by declaring a text encoding and
importing Python 3 behaviours from __future__.
Then import variables from *nine*, as per this boilerplate::

    # -*- coding: utf-8 -*-
    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    from nine import (IS_PYTHON2, str, basestring, native_str, chr, long,
        integer_types, class_types, range, range_list, reraise,
        iterkeys, itervalues, iteritems, map, zip, filter, input,
        implements_iterator, implements_to_string, implements_repr, nine,
        nimport)

I know that is ugly. What did you expect? *nine* is 3 squared.
OK, in many cases you can get away with less::

    # -*- coding: utf-8 -*-

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    from nine import IS_PYTHON2, nimport, nine, range, str, basestring

But in the second case you need to remember to import the missing stuff when
you use it, and it is not realistic to expect that you will remember, is it?


Unicode
=======

Because of the ``unicode_literals`` import, **all string literals in the module
become unicode objects**. No need to add a "u" prefix to each string literal.
This is the saner approach since in Python 3 strings are unicode objects
by default, and you can then indicate ``b"this is a byte string literal"``.
The literals that actually need to be byte strings are very rare.
But you wouldn't believe how many developers are irrationally afraid
of taking this simple step...

If you don't know much about Unicode, just read
`The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) <http://www.joelonsoftware.com/articles/Unicode.html>`_


Importing moved stuff
=====================

Many standard library modules were renamed in Python 3, but nine can
help. The ``nimport`` function gets the new Python 3 name, but knows to
import the old name if running in Python 2.
For instance, instead of writing this to import pickle::

    # Bad:
    try:
        import cPickle as pickle  # Python 2.x
    except ImportError:
        import pickle  # Python 3 automatically uses the C version.

...you can write this::

    # Good:
    pickle = nimport('pickle')

For variables that have been moved: In the argument, please separate the module
from the variable with a colon::

    name2codepoint = nimport('html.entities:name2codepoint')

Want StringIO? I recommend you build lists instead. But if you really need it::

    # Good:
    if IS_PYTHON2:
        from cStringIO import StringIO as BytesIO, StringIO
        NativeStringIO = BytesIO
    else:
        from io import BytesIO, StringIO
        NativeStringIO = StringIO

Our coverage of Python version differences probably isn't exhaustive,
but contributions are welcome.

When in doubt,
`use the source <https://github.com/nandoflorestan/nine/blob/master/nine/__init__.py>`_!

See the
`project page at GitHub <https://github.com/nandoflorestan/nine>`_!
We also have
`continuous integration at Travis-CI <https://travis-ci.org/nandoflorestan/nine>`_.


The *nine* class decorator
==========================

We provide a class decorator for Python 2 and 3 compatibility of magic methods.
Magic methods are those that start and end with two underlines.

You define the magic methods with their Python 3 names and,
on Python 2, they get their corresponding names. You may write:

* ``__next__()``. Use the ``next(iterator)`` function to iterate.
* ``__str__()``: must return a unicode string.  In Python 2, we implement
  ``__unicode__()`` and ``__bytes__()`` for you, based on your ``__str__()``.
* ``__repr__()``: must return a unicode string.
* ``__bytes__()``: must return a bytes object.

Example::

    @nine
    class MyClass(object):

        def __str__(self):
            return "MyClass"  # a unicode string


Porting steps
=============

When you are starting to apply *nine* on Python 2 code to achieve Python 3
compatibility, you can start by following this list of tasks. It isn't
exhaustive, just a good start. You can upgrade one ``.py`` module at a time:

* Add our header as mentioned above.
* Replace ocurrences of the print statement with the print function
  (this roughly means, add parentheses).
* Replace ``str()``, usually with nine's ``native_str()`` or with ``bytes()``.
* Replace ``unicode()`` with ``str()`` and ``from nine import str``
* Replace ``__unicode__()`` methods with ``__str__()`` methods;
  apply the ``@nine`` decorator on the class.
* Also apply the ``@nine`` decorator on classes that define ``__repr__()``.
* Search for ``range`` and replace with nine's ``range`` or ``range_list``
* Some dict methods return different things in Python 3. Only if you need
  exactly the same behavior in both versions, replace:

  * ``d.keys()`` or ``d.iterkeys()`` with nine's ``iterkeys(d)``;
  * ``d.values()`` or ``d.itervalues()`` with nine's ``itervalues(d)``; and
  * ``d.items()`` or ``d.iteritems()`` with nine's ``iteritems(d)``.

* Notice that ``map()``, ``zip()`` and ``filter()``, in nine's versions,
  always return iterators independently of Python version.

If you had been using *six* or another compatibility library before:

* Replace ``string_types`` with nine's ``basestring``

Then run your tests in all the Python versions you wish to support.

If I forgot to mention anything, could you
`make a pull request <https://github.com/nandoflorestan/nine>`_, for the
benefit of other developers?

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/nandoflorestan/nine",
    "name": "nine",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "python 2",
    "author": "Nando Florestan",
    "author_email": "nandoflorestan@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/ba/1f/0c7e2a1e28497df5d207199b5e70aa998e501659eeb84076a6cf78809540/nine-1.1.0.tar.gz",
    "platform": "",
    "description": "Let's write Python 3 right now!\n===============================\n\nWhen the best Python 2/Python 3 compatibility modules -- especially the famous\n`*six* library invented by Benjamin Peterson <https://pypi.python.org/pypi/six>`_\n-- were created, they were written from the point of view of a Python 2\nprogrammer starting to grok Python 3.  If you use *six*,\nyour code is compatible, but stuck in Python 2 idioms.\n\n**nine** turns **six** upside down. You write your code using Python 3 idioms\n-- as much as possible --, and it is the Python 2 \"version\" that is patched.\nNeedless to say, this approach is more future-proof.\n\nWhen thou writeth Python, thou shalt write Python 3 and,\njust for a little longer, ensure that the thing worketh on Python 2.7.\n\n*nine* facilitates this point of view. You can write code\nthat is as 3ish as possible while still supporting 2.6.\n\nFor instance, you don't type ``unicode`` anymore, you type ``str``, and *nine*\nmakes ``str`` point to ``unicode`` on Python 2 (if you use our boilerplate).\nAlso, ``map``, ``zip`` and ``filter`` have Python 3 behaviour, on Python 2,\nmeaning they return iterators, not lists.\n\nHonestly you should not spend one thought on Python 2.6 anymore, it is\n`no longer supported <https://mail.python.org/pipermail/python-dev/2013-September/128287.html>`_\nsince its final release (2.6.9) in October 2013. Nobody uses 3.0 or 3.1 either.\n\nPython 2.7 has finally met its demise on the first day of 2020.\n\n*nine* is extremely stable and unlikely to change since it solves an old\nproblem that never changes.  Nobody should be surprised if *nine* isn't\nupdated for months or even years.\n\nThe author(s) of *nine* donate this module to the public domain.\n\nTo understand most of the intricacies involved in achieving 2&3 compatibility\nin a single codebase, I recommend reading this:\nhttp://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/\n\n\nUsing nine\n==========\n\nIn each of your modules, start by declaring a text encoding and\nimporting Python 3 behaviours from __future__.\nThen import variables from *nine*, as per this boilerplate::\n\n    # -*- coding: utf-8 -*-\n    from __future__ import (absolute_import, division, print_function,\n                            unicode_literals)\n    from nine import (IS_PYTHON2, str, basestring, native_str, chr, long,\n        integer_types, class_types, range, range_list, reraise,\n        iterkeys, itervalues, iteritems, map, zip, filter, input,\n        implements_iterator, implements_to_string, implements_repr, nine,\n        nimport)\n\nI know that is ugly. What did you expect? *nine* is 3 squared.\nOK, in many cases you can get away with less::\n\n    # -*- coding: utf-8 -*-\n\n    from __future__ import (absolute_import, division, print_function,\n                            unicode_literals)\n    from nine import IS_PYTHON2, nimport, nine, range, str, basestring\n\nBut in the second case you need to remember to import the missing stuff when\nyou use it, and it is not realistic to expect that you will remember, is it?\n\n\nUnicode\n=======\n\nBecause of the ``unicode_literals`` import, **all string literals in the module\nbecome unicode objects**. No need to add a \"u\" prefix to each string literal.\nThis is the saner approach since in Python 3 strings are unicode objects\nby default, and you can then indicate ``b\"this is a byte string literal\"``.\nThe literals that actually need to be byte strings are very rare.\nBut you wouldn't believe how many developers are irrationally afraid\nof taking this simple step...\n\nIf you don't know much about Unicode, just read\n`The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) <http://www.joelonsoftware.com/articles/Unicode.html>`_\n\n\nImporting moved stuff\n=====================\n\nMany standard library modules were renamed in Python 3, but nine can\nhelp. The ``nimport`` function gets the new Python 3 name, but knows to\nimport the old name if running in Python 2.\nFor instance, instead of writing this to import pickle::\n\n    # Bad:\n    try:\n        import cPickle as pickle  # Python 2.x\n    except ImportError:\n        import pickle  # Python 3 automatically uses the C version.\n\n...you can write this::\n\n    # Good:\n    pickle = nimport('pickle')\n\nFor variables that have been moved: In the argument, please separate the module\nfrom the variable with a colon::\n\n    name2codepoint = nimport('html.entities:name2codepoint')\n\nWant StringIO? I recommend you build lists instead. But if you really need it::\n\n    # Good:\n    if IS_PYTHON2:\n        from cStringIO import StringIO as BytesIO, StringIO\n        NativeStringIO = BytesIO\n    else:\n        from io import BytesIO, StringIO\n        NativeStringIO = StringIO\n\nOur coverage of Python version differences probably isn't exhaustive,\nbut contributions are welcome.\n\nWhen in doubt,\n`use the source <https://github.com/nandoflorestan/nine/blob/master/nine/__init__.py>`_!\n\nSee the\n`project page at GitHub <https://github.com/nandoflorestan/nine>`_!\nWe also have\n`continuous integration at Travis-CI <https://travis-ci.org/nandoflorestan/nine>`_.\n\n\nThe *nine* class decorator\n==========================\n\nWe provide a class decorator for Python 2 and 3 compatibility of magic methods.\nMagic methods are those that start and end with two underlines.\n\nYou define the magic methods with their Python 3 names and,\non Python 2, they get their corresponding names. You may write:\n\n* ``__next__()``. Use the ``next(iterator)`` function to iterate.\n* ``__str__()``: must return a unicode string.  In Python 2, we implement\n  ``__unicode__()`` and ``__bytes__()`` for you, based on your ``__str__()``.\n* ``__repr__()``: must return a unicode string.\n* ``__bytes__()``: must return a bytes object.\n\nExample::\n\n    @nine\n    class MyClass(object):\n\n        def __str__(self):\n            return \"MyClass\"  # a unicode string\n\n\nPorting steps\n=============\n\nWhen you are starting to apply *nine* on Python 2 code to achieve Python 3\ncompatibility, you can start by following this list of tasks. It isn't\nexhaustive, just a good start. You can upgrade one ``.py`` module at a time:\n\n* Add our header as mentioned above.\n* Replace ocurrences of the print statement with the print function\n  (this roughly means, add parentheses).\n* Replace ``str()``, usually with nine's ``native_str()`` or with ``bytes()``.\n* Replace ``unicode()`` with ``str()`` and ``from nine import str``\n* Replace ``__unicode__()`` methods with ``__str__()`` methods;\n  apply the ``@nine`` decorator on the class.\n* Also apply the ``@nine`` decorator on classes that define ``__repr__()``.\n* Search for ``range`` and replace with nine's ``range`` or ``range_list``\n* Some dict methods return different things in Python 3. Only if you need\n  exactly the same behavior in both versions, replace:\n\n  * ``d.keys()`` or ``d.iterkeys()`` with nine's ``iterkeys(d)``;\n  * ``d.values()`` or ``d.itervalues()`` with nine's ``itervalues(d)``; and\n  * ``d.items()`` or ``d.iteritems()`` with nine's ``iteritems(d)``.\n\n* Notice that ``map()``, ``zip()`` and ``filter()``, in nine's versions,\n  always return iterators independently of Python version.\n\nIf you had been using *six* or another compatibility library before:\n\n* Replace ``string_types`` with nine's ``basestring``\n\nThen run your tests in all the Python versions you wish to support.\n\nIf I forgot to mention anything, could you\n`make a pull request <https://github.com/nandoflorestan/nine>`_, for the\nbenefit of other developers?\n",
    "bugtrack_url": null,
    "license": "Public domain",
    "summary": "Python 2 / 3 compatibility, like six, but favouring Python 3",
    "version": "1.1.0",
    "split_keywords": [
        "python",
        "2"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "3c0d5c2e0de2a24253072677be5fbad5",
                "sha256": "811b91c3117308ee86b11cbe6cc8caf3e7c576e1007520e5b357eeae47c9b5c9"
            },
            "downloads": -1,
            "filename": "nine-1.1.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3c0d5c2e0de2a24253072677be5fbad5",
            "packagetype": "bdist_wheel",
            "python_version": "3.7",
            "requires_python": null,
            "size": 9167,
            "upload_time": "2020-01-21T20:10:33",
            "upload_time_iso_8601": "2020-01-21T20:10:33.082913Z",
            "url": "https://files.pythonhosted.org/packages/11/5d/2db271e49bc3729230da1ea640eb749a21cdb3e1016b421a9e1e67dd1cae/nine-1.1.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "b7430863fbd8569cd43e323b01657a94",
                "sha256": "e8a96b6326341637d25ca9c257c1d2af4033c957946438d9d37bf6eb798d3bbe"
            },
            "downloads": -1,
            "filename": "nine-1.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "b7430863fbd8569cd43e323b01657a94",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 9772,
            "upload_time": "2020-01-21T20:10:27",
            "upload_time_iso_8601": "2020-01-21T20:10:27.156227Z",
            "url": "https://files.pythonhosted.org/packages/ba/1f/0c7e2a1e28497df5d207199b5e70aa998e501659eeb84076a6cf78809540/nine-1.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2020-01-21 20:10:27",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "nandoflorestan",
    "github_project": "nine",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "lcname": "nine"
}
        
Elapsed time: 0.01684s