Jinghui Niu
Jinghui Niu

Reputation: 1140

How to rename packages using python-rope

I've found documentation and experimented with python-rope to rename a module in Python. However, when it comes to renaming the whole package, there doesn't seem to be documentation available. Do we grab the package's __init__ file as the resource?

I'd like to change the following structure:

some_package
  -- __init__.py
  -- some_module_a.py
  -- some_module_b.py

into:

renamed_package
  -- __init__.py
  -- some_module_a.py
  -- some_module_b.py

There are a lot of references to this package all across my codebase, so some automatic refactoring could be extremely valuable. It's not complex in theory right? So I assume rope can definitely do this?

p.s. I'm using Sublime Text's PyRefactor.

Upvotes: 2

Views: 605

Answers (1)

Lie Ryan
Lie Ryan

Reputation: 64827

Rope can do this using rename function. Yes, you can select either the package's folder or the __init__.py file as the resource.

If you need some example of how this is done, I recommend looking at rope's test suite:

def test_renaming_packages(self):
    pkg = testutils.create_package(self.project, "pkg")
    mod1 = testutils.create_module(self.project, "mod1", pkg)
    mod1.write(dedent("""\
        def a_func():
            pass
    """))
    mod2 = testutils.create_module(self.project, "mod2", pkg)
    mod2.write("from pkg.mod1 import a_func\n")
    self._rename(mod2, 6, "newpkg")
    self.assertTrue(self.project.find_module("newpkg.mod1") is not None)
    new_mod2 = self.project.find_module("newpkg.mod2")
    self.assertEqual("from newpkg.mod1 import a_func\n", new_mod2.read())

Upvotes: 0

Related Questions