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

Asked

Viewed 254 times

3

I am working on the adaptation of a Jango project already created. During the analysis of the code 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

Taking past concepts as a reference here I was left with a doubt of the need of the pass in this method. If there is the need of the use does not modify its meaning for the language?

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 is still regarded as a valid expression.

It is usually used when you want to have the definition of a structure, but do not want to implement the respective logic. For example, defining a function:

def foo():
    pass

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

function foo() {

}

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

It is important to note that even if queryset is an empty set and no loop iteration is executed, the for remains a valid expression and is analyzed by the interpreter. Even in this case the 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 if no iteration occurs, since it is an empty list, the expression remains valid and no syntax error is triggered.

  • I understand. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.