Reputation: 2519
I've noticed that certain variable names in Python get flagged up by Vim in blue highlight, whereas others do not. I'm familiar with the concept of reserved words, per this question, but from looking it up, "str" does not appear to be one of these words.
Despite the highlighting however, it doesn't (seem) to cause any problems. A simple example:
str = "Hello"
sfgfgf = "World"
print(str)
print(sfgfgf)
And here's a screen snip of Vim's highlighting:
In both the variable definition and the print statement, str
is highlighted blue but sfgfgf
is not. Yet this code happily prints "Hello" and "World".
The same is true for "int", and I'm sure that there are other examples (the below code also runs without complaint):
int = 1
intentional_or_no = 5
print(int)
print(intentional_or_no)
So, my question:
Upvotes: 0
Views: 1308
Reputation: 1942
See, to understand why this is bad, look at the following example:
num = 10
real = 5.4
print(real, int(real))
Will produce:
5.4 5
Now, if you were to write:
int = 10
real = 5.4
print(real, int(real))
You will get this error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-39e8d577bf55> in <module>
2 int = 10
3 real = 5.4
----> 4 print(real, int(real))
TypeError: 'int' object is not callable
Local names overshadow global
s or built-in
s, rendering them un-usable, unless you introduce namespace which is not always possible.
Upvotes: 2
Reputation:
Yes, you should avoid using str as a variable, because
A) naming a variable after what its use is makes it easier to read the code for both you and other people.
and B) str() is a function that converts something (an integer, a float, etc.) in a string. this is why it gets highlighted.
it will still work, but its better to use another name for the variable
Upvotes: 2
Reputation: 1511
The highlighting is part of linting and is suggesting what you are doing is bad practice. As your scripts grow, overriding reserved words with your own will lead to confusion.
For example, if you develop your own "str" function in Python, and you reference "str" somehwere else in your code, would you expect the Python function or yours to be used?
Upvotes: 1