comparison contrib/byteify-strings.py @ 42705:f95b59ffc307

byteify-strings: add --treat-as-kwargs argument to handle kwargs-like objects This argument will help extensions move to Python 3 as keyword arguments should not be byte-prefixed. Most of the time, code bases will call this object `kwargs`, but other conventions exist like `opts`, so it should make sense to allow for custom names. This is a best effort solution that does minimal static checking; cases like `options = [o for o in ('a', 'b', 'c') if kwargs.get(o)]` and other just as complicated will not be detected.
author Rapha?l Gom?s <rgomes@octobus.net>
date Fri, 02 Aug 2019 10:18:22 +0200
parents c9fd8163131f
children 5e296f618920
comparison
equal deleted inserted replaced
42704:c9fd8163131f 42705:f95b59ffc307
226 # present in Python 3 world. 226 # present in Python 3 world.
227 elif opts['dictiter'] and fn in ('iteritems', 'itervalues'): 227 elif opts['dictiter'] and fn in ('iteritems', 'itervalues'):
228 yield adjusttokenpos(t._replace(string=fn[4:]), coloffset) 228 yield adjusttokenpos(t._replace(string=fn[4:]), coloffset)
229 continue 229 continue
230 230
231 if t.type == token.NAME and t.string in opts['treat-as-kwargs']:
232 if _isitemaccess(i):
233 _ensuresysstr(i + 2)
234 if _ismethodcall(i, 'get', 'pop', 'setdefault', 'popitem'):
235 _ensuresysstr(i + 4)
236
231 # Looks like "if __name__ == '__main__'". 237 # Looks like "if __name__ == '__main__'".
232 if (t.type == token.NAME and t.string == '__name__' 238 if (t.type == token.NAME and t.string == '__name__'
233 and _isop(i + 1, '==')): 239 and _isop(i + 1, '==')):
234 _ensuresysstr(i + 2) 240 _ensuresysstr(i + 2)
235 241
268 ap = argparse.ArgumentParser() 274 ap = argparse.ArgumentParser()
269 ap.add_argument('-i', '--inplace', action='store_true', default=False, 275 ap.add_argument('-i', '--inplace', action='store_true', default=False,
270 help='edit files in place') 276 help='edit files in place')
271 ap.add_argument('--dictiter', action='store_true', default=False, 277 ap.add_argument('--dictiter', action='store_true', default=False,
272 help='rewrite iteritems() and itervalues()'), 278 help='rewrite iteritems() and itervalues()'),
279 ap.add_argument('--treat-as-kwargs', nargs="+",
280 help="ignore kwargs-like objects"),
273 ap.add_argument('files', metavar='FILE', nargs='+', help='source file') 281 ap.add_argument('files', metavar='FILE', nargs='+', help='source file')
274 args = ap.parse_args() 282 args = ap.parse_args()
275 opts = { 283 opts = {
276 'dictiter': args.dictiter, 284 'dictiter': args.dictiter,
285 'treat-as-kwargs': set(
286 args.treat_as_kwargs
287 ) if args.treat_as_kwargs else set()
277 } 288 }
278 for fname in args.files: 289 for fname in args.files:
279 if args.inplace: 290 if args.inplace:
280 with editinplace(fname) as fout: 291 with editinplace(fname) as fout:
281 with open(fname, 'rb') as fin: 292 with open(fname, 'rb') as fin: