SoFunction
Updated on 2024-11-15

Explaining Advanced Python Variable and Comment Usage

Advanced Usage of Python Variables and Comments

1. Overview

Good variables and comments are not written for computers, but for everyone who reads the code. Variables and comments are the basis for expressing the author's thoughts, and their contribution to the quality of the code is unquestionable.

2. Variables

2.1. Variable unpacking

1. What is variable unpacking

The process of assigning all the members of an iterable object to multiple variables at once is variable unwrapping.

2. Variable unwrapping syntax

# Variable unpacking
username = ['zhangsan', '18']
name, age = username
print('name:{}, age:{} '.format(name, age))

# Nested type variable unwrapping
username = [1, ['zhangsan', 18]]
number, (name, age) = username
print('number:{}, name:{}, age:{}'.format(number, name, age))

# Match pattern unpacking
data = ['zhangsan', 'banana', 'apple', 'orange', 18]
name, *fruits, score = data
print('name:{}, fruits:{}, score:{}'.format(name, fruits, score))

# Slicing and dicing and unpacking
data = ['zhangsan', 'banana', 'apple', 'orange', 18]
name, fruits, score = data[0], data[1:-1], data[-1]
print('name:{}, fruits:{}, score:{}'.format(name, fruits, score))

# Variable unpacking using for loops
for name, age in [('zhangsan', 15), ('lisi', 18)]:
    print('name:{}, age:{}'.format(name, age))

# Single underlined variable names
username = ['zhangsan', 19]
name, _ = username
print(name, _)

2.2. Assigning types to variables

1. Introduction to the types of variables

python gives a type to a variable, unlike java variable types, python's variable types are just a hint and do not provide any checksums.
Therefore passing in a variable of a type that does not match the check type will not report an error.

The syntax for specifying the type of a variable is very simple: just separate the type of the table name with a colon after the variable name.

2. Examples of variables with types

# list means that the argument is of type list, int means that the members inside are shapes
def remove_invalid(item: list[int]):
    print(item)
# Pass in parameters that match the variable type
remove_invalid([1, 2, 3])
# Passing in parameters that do not match the variable type does not affect the result of the function execution.
remove_invalid(1)

# Type annotations using demos
class Duck:
    def __init__(self, color:str):
         = color
    # Specify for the quack method that the return value is of type None.
    def quack(self) -> None:
        print(f"Hi, I'm a {} duck")

# -> List[Duck]: use typing module's List object to label the function's return value with the specific type
def create_random_ducks(number:int) -> List[Duck]:
    # Add type declarations to variables
    ducks: List[Duck] = []

    for _ in number:
        color = (['yellow', 'white', 'gray'])
        (Duck(color=color))
    return ducks
ducks = create_random_ducks((1,2,3))
for duck in ducks:
    ()

2.3. Principles of variable naming

There are two main schools of thought for naming variables: one is hump naming that defines words by case, such as the Java language. The second is serpentine naming that connects words by underscores, such as the python language.

  • Follow the PEP8 principles
  • Be descriptive
  • Keep the length as short as possible
  • Variables indicate type
  • ultra-short nomenclature

1. Follow the PEP8 principles

PEP8, formerly known as Python Enhacement Proposal #8, translates to Python Enhancement Specification #8 provides guidelines for code writing style, with the following specifications for the variable naming section.

  • Common variables, using serpentine nomenclature, e.g. max_value
  • Constants, in all capital letters, are concatenated using underscores, e.g. MAX_VALUE
  • Use variables internally only by adding an underscore prefix to the variable, e.g. _local_var
  • When a variable name conflicts with a python keyword, append an underscore to the end of the variable, e.g. class_

2. Be descriptive

An important part of the writing process is choosing the right words for a sentence, and different words have different descriptive strengths. For example, "winter plum blossom" is more descriptive than "flower". Naming variables is just as descriptive as naming words.
Below are variables with different descriptive strengths, and the comparison gives a sense of how the more descriptive variable names make the code more readable.

# Weakly descriptive variable names: it is not clear what it is describing
vlaue = process(())

# Highly descriptive variable names: parses the user name from the user input parameters and eliminates spaces in the parameters.
username = extract_username(input_string.strip())

3. Keep the length as short as possible

If a particularly long repetition occurs, the reader will not find it precise, but rather verbose and difficult to read. Try to keep the name as short and readable as possible while maintaining descriptive clarity, usually within four words.

4. Variables indicate type

Although python variables do not need to declare their type, we can specify the type for variables to improve readability.
In addition to specifying the type for a variable, there are conventions for establishing a match between the variable name and the type, and here are some examples of matching variable names and types.

variable name hidden meaning clarification
is_superuser Whether or not you are a super user is means yes or no
has_errors Is there anything wrong? hans means yes or no
allow_empty Whether to allow null values allow indicates whether or not to allow

5. Ultra Short Order

In the naming of variables there is a special category of names, only one or two letters, usually they are divided into two categories, one is the short name that everyone agreed, the other is to create an alias.

Commonly used names of conventions

  • The Three Musketeers of Array Indexing i, j, k
  • Some integer n
  • A string s
  • An exception e
  • File object fp

create aliases from long names

is_not_normal as l

3. Notes

Comments don't affect the behavior of the code, it affects the readability of the code.

3.1. Types of annotations

There are two types of comments in python, in-code comments and function and class comments also known as interface comments.

in-line comment

# Benefits of using strip() to remove spaces:
# 1. Database takes up less space when saving data
# 2. There is no need to ask users to retype because they have over-typed a space.

username = extract_username(input_string.strip())

interface note

class Person:
	# Using three single quotes or three double quotes is an interface comment.
	'''Person
: param name: Name
: param age: age
: param favrite_color: favorite color
'''
	def __init__(self, name, age, favrite_color):
		 = name
		 = age
		self.favrite_color = color

3.2. Misuse of Annotation Cases

1. Shield code with comments

In programming, code is masked with comments, which can be deleted if they are no longer needed, or found in the Git repository if they need to be used. Temporarily commenting out large sections of code is a distraction for people reading the code and doesn't make any sense.

2. Repeat the code with comments

# Call strip() to remove the space
input_string = input_string.strip()

Comments like the one above are completely redundant because the reader can read the information in the comment from the code itself. A good comment would look like this

# If a parameter with spaces is passed to the backend for processing, it may cause the service to crash
# So use strip() to remove trailing spaces
input_string = input_string.strip()

Comments, as explanatory text outside of the code, should try to provide information that the reader can't read out of the code, describe theCode WhyTo do so, rather than simply restating the code itself.

apart fromfor what reason?In addition to the explanatory annotations, there is another type of annotation that is also common:introductory note
Instead of restating the code, such comments are concisesummarizeThe code function, which serves as a "code guide".
Guidance comments don't provide something that can't be read into the code - if there were no comments, patience would be enough to read all the code to know what it does. Guidance comments are about reducing the cost of code awareness and making it easier to understand the intent of the code.

Examples of guideline annotations

# Initialize the client object that accesses the service
token = token_service.get_token()
service_client = ServiceClient(token = token)
service_client.ready()

3. The wrong audience for interface annotations

to this article on the advanced use of Python variables and annotations to this article, more related to Python variables and annotations, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!