pythonvimsyntax-highlightingvim-syntax-highlightingvariable-names

Should I avoid using "str" as a variable name in Python?


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:

enter image description here

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)

enter image description here

So, my question:

  1. Is there any issue with using words such as "str" and "int" as variable names?
  2. If not, why does Vim highlight them in blue?

Solution

  • 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