在 Python 中使用之前显式声明变量,如 C++

Explicitly declare variable before using in Python like c++

请在评论建议之前阅读底部的注意事项。问题不在于强类型、动态类型、静态类型语言等。它是关于在程序中的任何地方开始使用变量并且改变一个而不是另一个将导致巨大的行为变化。

如果 PyLintflake8 可以提供帮助,请通过示例建议配置,以便我实施它。 如果我能做一些像类型提示之类的事情,看起来比 pylint 或 flake 8 更像语法错误,这将是很棒的,后者由 运行ning 稍后完成以检查类似测试。

在Python中使用如下变量:

def func():
    is_name_appropriate = False
    while not is_name_appropriate:
        print("Hello World")
        is_name_appropriate = True

func()


**Output :**
Hello World

在 C++ 中,变量的用法如下:

void func() 
{
    bool is_name_appropriate = false;
    while (is_name_appropriate != True)
    {
        cout<<"Hello World";
        is_name_appropriate = true;
    }
}

func();



**Output :**
Hello World

(C++)重构代码改变量名怎么办?

存在编译时错误,更正错误后程序的行为显然没有改变。

void func() 
{
    bool is_name_refactored_appropriate = false;  // changed variable name
    while (is_name_refactored_appropriate != True)  // changed variable name
    {
        cout<<"Hello World";
        is_name_appropriate = true;  // Forgot to change this. It will give me compile time error.
    }
}

func();


**Output :**
Hello World|
Hello World
Hello World
Hello World
.
.
.
and infinite

(Python) 如果我重构代码并更改变量名怎么办?

is_name_appropriate 现在是一个新变量,程序 运行 和行为已更改。这是我的问题。如何告诉 python 编译器 is_name_appropriate 变量不存在,这是一个错误。类似于 C++ 代码。

def func():
    is_name_refactored_appropriate = False  # changed variable name
    while not is_name_refactored_appropriate:  # change variable name initialized above
        print("Hello World")
        is_name_appropriate = True  # forgot to change this. I don't use IDE. terminal is great!!! 

func()


**Output :**
Hello World|
Hello World
Hello World
Hello World
.
.
.
and infinite

我的程序有30,000行代码,很难记住在哪里使用了变量。重构是非常必要的,所以不要拒绝重构。

我使用 PyCharm Propressional Edition 作为 IDE,但重构一个使用次数超过 50 次的名称仍然很困难。

注意:上面的代码只是一个示例,实际代码非常复杂,无法在此处发布。 请不要建议删除上面的 while 循环。理解问题。 我也不能更改语言,因为 python 是程序中特别需要的,所以请不要太建议。 单元测试在这里没有帮助。抱歉,伙计们。这里用的是BDD

我建议添加 type hints to your code and using MyPy to do static type checking. I've found this to be a game changer when maintaining and refactoring big Python code bases. See this article 以详细说明其工作原理。

诚然,类型提示无法解决您询问的有关重命名局部变量的位置的具体问题

    is_name_refactored_appropriate = False  # changed variable name
    while not is_name_refactored_appropriate:  # change variable name initialized above
        print("Hello World")
        is_name_appropriate = True  # forgot to change this. I don't use IDE. terminal is great!!! 

类型提示是可选的,这是设计使然。它允许您在 MyPy 可以推断类型的地方省略它们,并且还允许您逐渐将类型提示引入现有代码库。然而,这确实意味着即使您在 is_name_refactored_appropriate 上放置类型提示,MyPy 也不会在您分配给 is_name_appropriate 的行上给您一个错误,因为它认为您想要创建一个新变量.

然而,重命名局部变量通常不是一个很大的重构障碍,因为它们只能从使用它们的函数中引用。如果重命名局部变量,唯一可以破坏的是它正在使用的函数。这意味着即使是简单的文本搜索和替换也是更改局部变量名称的有效方法。

例如,重命名属性或方法的问题要多得多,因为它们可能会在程序的任何位置被引用。 MyPy 给你错误,例如,如果你试图访问一个 属性 或调用一个不存在的方法。 这些是非常重要的要捕获的错误,因为它们本质上是全局的:如果重命名 属性 或方法,程序的任何部分都可能会中断。

要向现有项目添加类型提示,我会采用将它们引入您将要重构并因此需要防止破坏的区域的方法。这确保您通过引入类型提示所做的工作有立竿见影的效果。