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

Question:

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?
Asked By: Lou

||

Answers:

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?

Answered By: Jason Cook

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

Answered By: user12860315

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 globals or built-ins, rendering them un-usable, unless you introduce namespace which is not always possible.

Answered By: anurag