I have to port a legacy code ( ~60K LOC) from Python 2 to 3 which has a couple of thousand of structures like below:
class Sample(object):
__slots__ = ('both', 'advertise')
class __metaclass__(type):
__instancecheck__ = classmethod(
lambda cls, inst: inst in ('both', 'advertise'))
both = 'both'
advertise = 'advertise'
This code works fine with Python 2 but doesn't compile with Python 3 and to resolve it I need to change it to
class Sample(object):
__slots__ = ('both', 'advertise')
class __metaclass__(type):
__instancecheck__ = classmethod(
lambda cls, inst: inst in ('both', 'advertise'))
def __init__(self):
both = 'both'
advertise = 'advertise'
What would be an efficient way to handle this change given that it has to be done over such a large file multiple times?
We have to consider that there may or may not be a __init__
function definition already for the class and there can be nested class definitions as well.
This is what I have tried so far.
2to3
doesn't recognize this as an issue and hence doesn't change it.- One possible way could be to use
ast
module to modify the parse tree in memory and then useunparse
to write back the modified code. But it is not straightforward. - If nothing else works, I will consider writing a simple Shell/Python script which will read the source file, make changes and write it back.
Can there be another quick and simple way to handle this change.