What is the real use of the pass in this case?

3

I'm working on the adaptation of a django project already created. During the code analysis I came across the following excerpt:

def objects_delete_action(modeladmin, request, queryset):
    for obj in queryset:
        try:
            obj.delete()
        except (NOT_ALLOWED_ON_NONLEAF, ValueError):
            messages.error(request, AdminErrorMessages.MUST_BE_EMPTY)
    pass

Referring to past concepts here I had a question about the need to pass in this method. If there is a need to use does not modify the meaning of it to the language?

    
asked by anonymous 27.09.2017 / 15:29

1 answer

8

There is no use for this case. The only function of pass is to function as a placeholder in structures that require an expression, but that no logic should be executed. When a pass is executed, nothing happens, literally, but it is still considered as a valid expression.

It is typically used when you want to have a structure definition, but you do not want to implement its logic. For example, define a function:

def foo():
    pass

The function is defined, it can be called, but nothing happens. Without pass , a syntax error would be triggered. It would be the equivalent of leaving the keys empty in some other languages:

function foo() {

}

In this case, since pass is at the same indentation level as for , it belongs directly to the scope of the objects_delete_action function. However, since for itself already provides the expression that the function declaration demands, pass is unnecessary - and probably remains in the code because someone forgot to delete it.

It is important to note that even though queryset is an empty set and no loop iteration is performed, for remains a valid expression and is parsed by the interpreter. Even then pass is unnecessary. Proof of this, just try to create a loop that iterates an empty list:

def foo():
    for value in []:
        print(value)

Even though no iteration occurs, since it is an empty list, the expression remains valid and no syntax error is triggered.

    
27.09.2017 / 15:44