[PATCH 1 of 3 V2] py3: make a bytes version of getopt.getopt()

Yuya Nishihara yuya at tcha.org
Thu Dec 8 09:58:10 EST 2016


On Thu, 08 Dec 2016 00:06:39 +0530, Pulkit Goyal wrote:
> # HG changeset patch
> # User Pulkit Goyal <7895pulkit at gmail.com>
> # Date 1480986396 -19800
> #      Tue Dec 06 06:36:36 2016 +0530
> # Node ID ced854b9dfaa7298b241ac085627b12ecb796dcd
> # Parent  a2b053b8d31aa01b1dcae2d3001b060ff59e8a68
> py3: make a bytes version of getopt.getopt()

> --- a/mercurial/pycompat.py	Tue Dec 06 11:44:49 2016 +0000
> +++ b/mercurial/pycompat.py	Tue Dec 06 06:36:36 2016 +0530
> @@ -10,6 +10,7 @@
>  
>  from __future__ import absolute_import
>  
> +import getopt
>  import os
>  import sys
>  
> @@ -87,6 +88,21 @@
>      setattr = _wrapattrfunc(builtins.setattr)
>      xrange = builtins.range
>  
> +    # getopt.getopt() on Python 3 deals with unicodes internally so we cannot
> +    # pass bytes there. Passing unicodes will result in unicodes as return
> +    # values which we need to convert again to bytes.
> +    def getoptb(args, shortlist, namelist):
> +        args = [a.decode('latin-1') for a in args]
> +        shortlist = shortlist.decode('latin-1')
> +        namelist = [a.decode('latin-1') if isinstance(a, bytes) else a
> +                                    for a in namelist]
> +        opts, args = getopt.getopt(args, shortlist, namelist)
> +        opts = [((a[0].enocde('latin-1') if isinstance(a[0], str) else a[0]),
> +                (a[1].enocde('latin-1') if isinstance(a[1], str) else a[1]))
> +                            for a in opts]

Are these isinstance() tests necessary?


More information about the Mercurial-devel mailing list