Conditionalizing imports Python2 - Python3

Gregory Szorc gregory.szorc at gmail.com
Sun Feb 28 02:16:33 EST 2016


On Sat, Feb 27, 2016 at 11:09 PM, Wasim Thabraze <waseem.tabraze at gmail.com>
wrote:

> Hello everyone,
>
> I'm currently working on conditionalizing imports (Moving towards Python3
> - GSoC).
>

Cool!


>
> In '/contrib' folder I found some issues with the imports.
>
> 1. In 'casemash.py'  we are importing 'builtins' as 'import __builtin__'.
> This works in Python 2 but Python 3 gives an ImportError. To resolve this
> we need to change it to  'import builtins'. This works in both Python 2 and
> Python 3.
>

No it doesn't.


>
> 2. In 'hgclient.py' we import 'cStringIO' but this raises an ImportError
> in Python 3. Python 3 version of 'cStringIO' is 'from io import StringIO'.
> So changing 'import cStringIO' to 'from io import StringIO'  would work in
> both Python 2 and Python 3.
>

We (sadly) probably want to avoid io.StringIO in Python 2 because the io
module is a bit slower than StringIO or cStringIO. Also, io.StringIO and
io.BytesIO and io.StringIO enforce encoding. So e.g. you can only pass a
unicode Python 2 type to io.StringIO. Most string values in Mercurial are
the str Python 2 type (Mercurial prefers to work with bytes not encoded
strings).


>
> 3. In 'import-checker.py' we import http server module as
> 'BaseHTTPServer'. This doesn't work in Python 3. Raises an Import Error.
> Changing 'import BaseHTTPServer' to 'from http import server' would work
> fine in both Python 2 and 3.
>
> We can also resolve them by making conditional imports as follows for all
> such imports.
>
> >>> try:...     import BaseHTTPServer... except ImportError:...     from http import server
>
>
Alternatively, you can perform the imports in py3kcompat.py and export them
under a unified symbol. Of course, this only works if the module was simply
renamed. If APIs changed, we'll need an additional compatibility layer.


> I'm currently working on this task of conditionalizing imports and other
> tasks mentioned.
>
> I feel glad if I can receive feedback about it.
>
> Thank You.
>
> Regards,
> Wasim
> www.thabraze.me
>
> _______________________________________________
> Mercurial-devel mailing list
> Mercurial-devel at mercurial-scm.org
> https://www.mercurial-scm.org/mailman/listinfo/mercurial-devel
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.mercurial-scm.org/pipermail/mercurial-devel/attachments/20160227/932a9034/attachment.html>


More information about the Mercurial-devel mailing list