Firefox/Python 3 Migration: Difference between revisions

→‎How to Port the Code: added porting examples with six
(→‎How to Port the Code: added porting examples with six)
Line 81: Line 81:
* The `six` module is available in-tree, feel free to use it as a dependency.
* The `six` module is available in-tree, feel free to use it as a dependency.
* [https://black.readthedocs.io/en/stable/index.html Black] can format Python 2 code and Python 3 code (but [https://black.readthedocs.io/en/stable/installation_and_usage.html it requires Py3.6+ to run]).
* [https://black.readthedocs.io/en/stable/index.html Black] can format Python 2 code and Python 3 code (but [https://black.readthedocs.io/en/stable/installation_and_usage.html it requires Py3.6+ to run]).
=== Porting examples ===
Prefer <code>[https://six.readthedocs.io/ six]</code> when possible.  Make use of <code>six.PY2</code>, <code>six.PY3</code>, <code>six.moves</code>, <code>six.string_types</code>, <code>six.integer_types</code>, etc.  This make it easy to find the py2 code again so we can remove it.
==== <code>import</code> statements ====
Use the <code>[https://six.readthedocs.io/#module-six.moves six.moves]</code> module:
Before:
<pre>
import __builtin__
__builtin__.__import__ = myimporthook()
</pre>
After:
<pre>
from six.moves import builtins
builtins.__import__ = myimporthook()
</pre>
==== <code>if</code> statements ====
Use <code>six.PY2</code> and <code>six.PY3</code>:
<pre>
import six
if six.PY2:
    # py2 stuff
else:
    # py3 stuff
</pre>
If six isn't available or you are in the imports section of the module then this is fine too:
<pre>
if sys.version_info < (3,):
  # py2 stuff
else:
  # py3 stuff
</pre>
==== String data ====
Use <code>six.string_types</code>, <code>six.text_type</code>, <code>six.binary_type</code>, etc. Also see the <code>six</code> docs for "[https://six.readthedocs.io/#binary-and-text-data Binary and text data]":
Before:
<pre>
# using unicode
def write(self, buf):
    if isinstance(buf, unicode):
        buf = buf.encode('utf-8')
    BytesIO.write(self, buf)
# using types.StringTypes
if isinstance(value, types.StringTypes):
    ...
</pre>
After:
<pre>
import six
# fixed unicode
def write(self, buf):
    if isinstance(buf, six.text_type):
        buf = buf.encode('utf-8')
    BytesIO.write(self, buf)
# fixed types.StringTypes
if isinstance(value, six.string_types):
    ...
</pre>


=== Porting Resources ===
=== Porting Resources ===
75

edits