Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Refactor Module using python rope?

Tags:

python

rope

I have my project structure as following

├── app
│   ├── Country
│   │   └── views.py
│   ├── Customer
│   │   └── views.py

Where the module 'Country' folder is what I tried to rename it to 'Countries' and every occurrence it is used, and it is also imported in Customer/views.py as well.

from app.Country.views   import *
....

According to this tutorial Refactoring Python Applications for Simplicity, I tried it as below:

>>> from rope.base.project import Project
>>> 
>>> proj = Project('app')
>>> 
>>> Country = proj.get_folder('Country')
>>> 
>>> from rope.refactor.rename import Rename
>>> 
>>> change = Rename(proj, Country).get_changes('Countries')
>>> proj.do(change)

After executing the script, the module folder 'Country' was changed to 'Countries' but its instance where it is used in Customer/views.py does not change accordingly, the import statement in Customer/views.py is still

from app.Country.views   import *

I expected it should change to from app.Countries.views import * after refactoring, but it did not.

Is there anything else I should do to refactor this successfully? Thanks.

like image 250
Houy Narun Avatar asked Nov 30 '19 14:11

Houy Narun


People also ask

What is rope in Python?

Rope is the world's most advanced open source Python refactoring library (yes, I totally stole that tagline from Postgres). Most Python syntax from Python 2.7 up to Python 3.10 is supported. Please file bugs and contribute patches if you encounter gaps. From version 1.0.

What is refractor in Python?

Refactoring in Python. Refactoring is the technique of changing an application (either the code or the architecture) so that it behaves the same way on the outside, but internally has improved. These improvements can be stability, performance, or reduction in complexity.


1 Answers

You could use proj.get_module('app.Country').get_resource() to rename module.

from rope.base.project import Project
from rope.refactor.rename import Rename

proj = Project('app')
country = proj.get_module('app.Country').get_resource()
change = Rename(proj, country).get_changes('Countries')
print(change.get_description())
like image 191
AnnieFromTaiwan Avatar answered Oct 05 '22 20:10

AnnieFromTaiwan