'Rename a python class with rope using a python script

Given a folder myproj with a file myclass.py

myproj
-- __init__.py
-- myclass.py

where myclass.py contains the following class definition

class MyClass:
    pass

I want to rename the class from MyClass to MyClass2 with rope.

If I know that the offset of the class name is 6, then I could rename the class as follows

import rope.base.project
import rope.refactor.rename


proj = rope.base.project.Project('myproj')
res = proj.get_module('myclass').get_resource()
change = rope.refactor.rename.Rename(proj, res, 6).get_changes('MyClass2')
print(change.get_description())

Question: How do I rename a class with rope knowing only the name of the class MyClass (but not knowing the offset of MyClass)?

Edit:

Here is one way to do it

offset = res.read().index('MyClass')


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source