Nabeel Ahmed
Nabeel Ahmed

Reputation: 140

What is the difference between keyword pass and ... in python?

Is there any significant difference between the two Python keywords (...) and (pass) like in the examples

def tempFunction():
    pass 

and

def tempFunction():
    ...

I should be aware of?

Upvotes: 7

Views: 1252

Answers (3)

S.B
S.B

Reputation: 16496

pass is a keyword. It's basically a null operator and when it is executed, "nothing happens".

... is an object of type <class 'ellipsis'>. When it appears, it's an expression like any other objects it may also be evaluated.

But whether this Ellipsis object is evaluated (in your example) or not varies between different versions of the interpreter.

In my local machine(3.10.6):

from dis import dis

def fn_ellipsis():
    ...

def fn_pass():
    pass

dis(fn_ellipsis)
print("-----------------------------------")
dis(fn_pass)

output:

  4           0 LOAD_CONST               0 (None)
              2 RETURN_VALUE
-----------------------------------
  7           0 LOAD_CONST               0 (None)
              2 RETURN_VALUE

but in 3.5.1:

  4           0 LOAD_CONST               1 (Ellipsis)
              3 POP_TOP
              4 LOAD_CONST               0 (None)
              7 RETURN_VALUE
-----------------------------------
  7           0 LOAD_CONST               0 (None)
              3 RETURN_VALUE

So it's better to say, it's guaranteed that pass won't evaluated at all but evaluation of any other object is implementation details. New parser can easily say that it's unnecessary to evaluate a bare ... in your example. Same thing happens if you place an int. But that's not the case for list objects.

Upvotes: 0

vaizki
vaizki

Reputation: 1932

The ... is an ellipsis, aka internal object Ellipsis.

def tempFunction():
    ...

is the same as:

def tempFunction():
    Ellipsis

so it's similar to doing something like:

def tempFunction():
    0

All of these are functions which have a simple expression in that doesn't get returned so almost the same as using pass. Not exactly the same as the expression still gets evaluated even though the value is never used.

I just use pass. It's the most efficient and understood by every Python programmer.

Upvotes: 3

mousetail
mousetail

Reputation: 8010

The ... is the shorthand for the Ellipsis global object in python. Similar to None and NotImplemented it can be used as a marker value to indicate the absence of something.

For example:

print(...)
# Prints "Ellipsis"

In this case, it has no effect. You could put any constant there and it would do the same. This is valid:

def function():
    1

Or

def function():
    'this function does nothing'

Note both do nothing and return None. Since there is no return keyword the value won't be returned.

pass explicitly does nothing, so it will have the same effect in this case too.

Upvotes: 5

Related Questions