comparison mercurial/pycompat.py @ 30579:fbc3f73dc802

py3: utility functions to convert keys of kwargs to bytes/unicodes Keys of keyword arguments need to be str(unicodes) on Python 3. We have a lot of function where we pass keyword arguments. Having utility functions to help converting keys to unicodes before passing and convert back them to bytes once passed into the function will be helpful. We now have functions named pycompat.strkwargs(dic) and pycompat.byteskwargs(dic) to help us.
author Pulkit Goyal <7895pulkit@gmail.com>
date Wed, 07 Dec 2016 21:53:03 +0530
parents c6ce11f2ee50
children c6026c20a3ce
comparison
equal deleted inserted replaced
30578:c6ce11f2ee50 30579:fbc3f73dc802
99 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1')) 99 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
100 for a in opts] 100 for a in opts]
101 args = [a.encode('latin-1') for a in args] 101 args = [a.encode('latin-1') for a in args]
102 return opts, args 102 return opts, args
103 103
104 # keys of keyword arguments in Python need to be strings which are unicodes
105 # Python 3. This function takes keyword arguments, convert the keys to str.
106 def strkwargs(dic):
107 dic = dict((k.decode('latin-1'), v) for k, v in dic.iteritems())
108 return dic
109
110 # keys of keyword arguments need to be unicode while passing into
111 # a function. This function helps us to convert those keys back to bytes
112 # again as we need to deal with bytes.
113 def byteskwargs(dic):
114 dic = dict((k.encode('latin-1'), v) for k, v in dic.iteritems())
115 return dic
116
104 else: 117 else:
105 def sysstr(s): 118 def sysstr(s):
106 return s 119 return s
107 120
108 # Partial backport from os.py in Python 3, which only accepts bytes. 121 # Partial backport from os.py in Python 3, which only accepts bytes.
120 def fsdecode(filename): 133 def fsdecode(filename):
121 return filename 134 return filename
122 135
123 def getoptb(args, shortlist, namelist): 136 def getoptb(args, shortlist, namelist):
124 return getopt.getopt(args, shortlist, namelist) 137 return getopt.getopt(args, shortlist, namelist)
138
139 def strkwargs(dic):
140 return dic
141
142 def byteskwargs(dic):
143 return dic
125 144
126 osname = os.name 145 osname = os.name
127 ospathsep = os.pathsep 146 ospathsep = os.pathsep
128 ossep = os.sep 147 ossep = os.sep
129 stdin = sys.stdin 148 stdin = sys.stdin