【问题标题】:Rename a python class with rope using a python script使用 Python 脚本重命名带有绳索的 Python 类
【发布时间】:2022-07-04 19:25:30
【问题描述】:

给定一个文件夹 myproj 和一个文件 myclass.py

myproj
-- __init__.py
-- myclass.py

其中myclass.py 包含以下类定义

class MyClass:
    pass

我想用rope 将课程从MyClass 重命名为MyClass2。

如果我知道类名的偏移量是6,那么我可以重命名类如下

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())

问题:如何只知道类名称MyClass(但不知道MyClass 的偏移量)用rope 重命名一个类?

编辑:

这是一种方法

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

【问题讨论】:

    标签: python refactoring rename offset rope


    【解决方案1】:

    Rope 主要用于 IDE,其中用户通过文本编辑器光标以交互方式进行重构,文本编辑器光标指向用户想要重构的对象,而不是用于编程重构。

    话虽如此,如果你想做这样的事情,你可以使用get_definition_location() 方法来获取最近的行号:

    mod = proj.get_module('myclass')
    name = mod.get_attribute('MyClass')
    pymod, lineno = name.get_definition_location()
    lineno_start, lineno_end = pymod.logical_lines.logical_line_in(lineno)
     
    offset = pymod.resource.read().index(name.pyobject.get_name(), pymod.lines.get_line_start(lineno))
    
    change = rope.refactor.rename.Rename(proj, pymod.get_resource(), offset).get_changes('MyClass2')
    

    这将比尝试使用index() 获取全局偏移量稍微可靠一些,后者很容易被匹配 docstrings/cmets 中的文本所欺骗。

    披露:我是 Rope 的主要维护者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2013-06-05
      • 2012-05-26
      相关资源
      最近更新 更多