Pete Cacioppi
Pete Cacioppi

Reputation: 920

What the purpose of the `pass` statement?

Seems like pass is just a reserved word that isn't really needed. Python could use the convention of having a single line None statement to accomplish the same thing.

For example, I see very little difference between

while doing_a_thing():
   pass

and

while doing_a_thing():
   None

I suppose having pass is slightly more readable, but to my mind, it is a poor trade off against removing such a common word from the choices of functions/variables.

Just wondering if anyone knows more history and/or Python usage that I'm not aware of.

Upvotes: 1

Views: 456

Answers (2)

Rory Daulton
Rory Daulton

Reputation: 22544

None already has meaning in Python. It is not a statement, but a value. It can be used to flag a variable that does not yet have a standard value, or as the "return value" of a function that does not return anything.

So using it as a statement would be more confusing than using the new keyword pass.

Upvotes: 8

Chrispresso
Chrispresso

Reputation: 4071

I'm going to piggy-back off Rory a bit here.

None is a value, whereas pass is a statement.

For instance if you want a default value for a function you would do

def my_func(val1, val2=None):
    # Some stuff here

Where None is used to denote that the default value of val2 is None.

If you have a class, however, you may see pass in this way:

class MyClass(object):
    def __init__(self):
        pass

Where pass may be there because you want to define the __init__ method later, or to denote that it does nothing for the class.

Either way, pass is to say, "I could do something here, but I prefer not to". And None is an actual value that you are explicitly meaning to say "Yes, I am giving this value None

EDIT:
I understand more of the confusion now.

Because you see that:

class MyClass(object):
    def __init__(self):
        pass

could be written as

class MyClass(object):
    def __init__(self):
        None

This is not Pythons way of saying that None is equivalent to pass here. It is simply saying that providing only a value as a no-op, will have the same effect. So that means I could also do:

class MyClass(object):
    def __init__(self):
        12

And this of course doesn't make sense, why would you ever put 12 there? The point here is that the effects are the same, but the meanings are different in this case. And in a lot of cases None and pass are not interchangeable such as default arguments

Upvotes: 5

Related Questions