7 Suggestions for Naming python Variables
- 2021-07-09 08:48:05
- OfStack
Preface
According to the voting statistics of one developer in Quora Q&A community, the biggest problem for programmers is how to name (for example, give variables, classes, functions, etc.). The votes for one item alone are almost the sum of the voting results of the other eight items. How to name a variable and how to make it meaningful has become an insurmountable problem for programmers. This article refers to Clean Code and provides 7 naming suggestions, hoping to bring you some help in the process of naming.
The following are based on Python 3.7 syntax
1. Use meaningful and readable variable names
Difference
ymdstr = datetime.date.today().strftime("%y-%m-%d")
Who knows what ymd is?
Good
current_date: str = datetime.date.today().strftime("%y-%m-%d")
When you see current_date, you can understand it with one eye.
2. Use the same vocabulary for variables of the same type
These three functions are all user-related information, but they use three names
get_user_info()
get_client_data()
get_customer_record()
Ok, if the entities are the same, you should unify 1 name
get_user_info()
get_user_data()
get_user_record()
Excellent because Python is an object-oriented language, it is more reasonable to use a class to realize it, which is represented by instance attributes, property methods and instance methods respectively.
class User:
info : str
@property
def data(self) -> dict:
# ...
def get_record(self) -> Union[Record, None]:
# ...
3. Use searchable names
Most of the time you are reading code instead of writing code, so it is especially important that the code we write is readable and searchable. A variable without a name can't help us understand the program, and it also hurts readers. Remember: Make sure it is searchable.
Difference
time.sleep(86400);
What the fuck, God doesn't know what 86400 is
Good
# Declare variables in the global namespace, 1 How many seconds are there in the day
SECONDS_IN_A_DAY = 60 * 60 * 24
time.sleep(SECONDS_IN_A_DAY)
It's much clearer.
4. Use self-descriptive variables
Difference
address = 'One Infinite Loop, Cupertino 95014'
city_zip_code_regex = r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'
matches = re.match(city_zip_code_regex, address)
save_city_zip_code(matches[1], matches[2])
matches [1] has no role in self-explaining who you are
1-like
address = 'One Infinite Loop, Cupertino 95014'
city_zip_code_regex = r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'
matches = re.match(city_zip_code_regex, address)
city, zip_code = matches.groups()
save_city_zip_code(city, zip_code )
You should understand that matches. groups () is automatically unpacked into two variables, city, zip_code
Good
address = 'One Infinite Loop, Cupertino 95014'
city_zip_code_regex = r'^[^,\\]+[,\\\s]+(?P<city>.+?)\s*(?P<zip_code>\d{5})?$'
matches = re.match(city_zip_code_regex, address)
save_city_zip_code(matches['city'], matches['zip_code'])
5. Don't force readers to guess the meaning of variables, clear is better than obscure
Difference
current_date: str = datetime.date.today().strftime("%y-%m-%d")
0
What is seq? Sequence? What sequence? No one knows, only by looking down.
Good
current_date: str = datetime.date.today().strftime("%y-%m-%d")
1
Expressed in locations, 1 you can see that this is a tuple composed of several regions
6. Don't add unnecessary context
If your class name already tells you something, don't repeat the description of variable names
Difference
current_date: str = datetime.date.today().strftime("%y-%m-%d")
2
Feel gilding the lily. If it is unnecessary, don't add entities.
Good
class Car:
make: str
model: str
color: str
7. Use default parameters instead of short circuit operation and conditional operation
Difference
current_date: str = datetime.date.today().strftime("%y-%m-%d")
4
Good
current_date: str = datetime.date.today().strftime("%y-%m-%d")
5
This should be understandable, since the function needs to deal with variables without parameters, why not specify it at the time of definition?