-
-
Notifications
You must be signed in to change notification settings - Fork 33.2k
Description
Feature or enhancement
Proposal:
Currently, Python does not distinguish between variable declaration and assignment, which allows variables to be redefined. This can lead to potential security issues. Here are some scenarios I can think of that always make me feel uneasy when writing Python code.
Scenario 1:
Functions have their own scope, and new variables used within a function will automatically be contained within that function while also having access to variables in the outer scope. However, when accessing variables from the outer scope, we might suddenly need to assign values to them, which can easily lead to accidentally creating a new variable contained within the function. Note that this is not saying the problem cannot be solved, but rather that it easily leads to errors. This requires programmers to be mindful of this issue, but the fact that programmers need to be mindful of this issue ultimately stems from Python's design flaw. Languages with variable declaration concepts would not have this problem.
Scenario 2:
In larger projects, functions with hundreds of lines of code frequently appear. While we might be aware of issues caused by variable redefinition when initially writing code, I often need to be extremely careful when creating new variables in certain scopes while modifying a huge application. I need to check whether corresponding variable names already exist above, and I'm always worried about accidentally overwriting function parameters or previously defined variables when modifying code. This feeling is terrible, especially since everyone has moments when they're not thinking clearly, which only increases the risk. Meanwhile, Python itself does not implement any effective measures to prevent programmers from making mistakes.
Therefore, I propose adding the concept of variable declaration to Python. Below is a temporary proposal. This proposal is essentially not about specific syntax, but rather about the concept of variable declaration. The syntax itself is something that can be discussed.
# The original way it was written
a = 123
# Suggested writing
var a = 123
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response