What is the function of this naming method with "_" in front of it?

_ get_request_cookies ()

Jan.20,2022

doesn't want to be exposed, which means that although you can import this function from this file, the person who wrote it doesn't want you to use it and wants you to use it as a private function. Of course, it is also possible that it is simply because of the duplicate name, and if you don't know what name to change, you will directly underline it in front of it.


A single underlined name, called a "protected" name by the author of "fluent python", has two main uses:
1, which prevents other python scripts from importing the name through the [from module import *] statement, that is, the name will not be matched by asterisks;

"""foo.py"""
def add(a, b):
    """"""
    return a+b

def _add2(a, b):
    """"""
    return a+b

for example, for the above module foo, if I use the [from foo import *] statement in another python script, I can't actually access the _ add2 () function, but if I use the [from foo import add, _ add2] statement, both functions can be accessed.

2, as the property name or method name of a class, it means that you do not want downstream programmers to access the name directly, resulting in accidental overwriting of the property, but this is only a naming convention, and the python interpreter will not do any special treatment for this property name.

Menu