Home > Back-end >  Is underscore needed between the word and number in a variable name? (Python)
Is underscore needed between the word and number in a variable name? (Python)

Time:06-14

I have 2 variables, city1 and city2 as shown below:

city1 = "New York" 
city2 = "Los Angeles"

According to Function and Variable Names in PEP 8 – Style Guide for Python Code, an underscore _ is needed between the words in a variable name as shown below:

first_name = "John"
last_name = "Tom"

Now, is underscore also needed between the word and number in a variable name as shown below?

city_1 = "New York" 
city_2 = "Los Angeles"

CodePudding user response:

From PEP8:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

So underscores are there to improve readability, but you are free to do as you want.

longvariable = 0
long_variable = 1
city1 = 2
city_2 = 3

The main thing is to stay consistent within your code style and your organisation's style.

CodePudding user response:

Python naming conventions do not specify whether or not you need to separate numbers from letters by an underscore. This is a matter of opinion. Here is mine.

I use no separator between letters and numbers for brevity. Thus, I use:

city1 = "New York" 
city2 = "Los Angeles"

It seems that the highly scientific google search agrees:
file:py "test1": About 712,000 results
file:py "test_1": About 66,800 results

How can 712,000 users be wrong? But seriously, that's an order of magnitude difference!

A few related notes:

  • When numeric extensions are needed, use lists or dictionaries, which are more extensible, and which allow iterations, loops, comprehensions, etc - everything that can help keep the code non repetitive:
# Lists:
cities = ['New York', 'Los Angeles']
print(cities[0])
# New York

cities.append('Boston')
cities = [c.lower() for c in cities]
print(cities[2])
# boston

# Dictionaries:
city  = {'src': 'New York', 'dest': 'Los Angeles'}
print(city['src'])
# New York
  • Avoid relatively uninformative extensions such as 1 or 2, unless they are part of the knowledge domain of the users. For example, read1 and read2 have specific meaning for biologists, who are the users in the analysis of next-generation sequencing. But that's rare. And even then, lists are a better idea (because sooner than you think, there will also be read3 and read4). Perhaps src_city and dest_city can be better choices and city1 and city2.
  • Related