What does the pass keyword do?

Question

What does the pass keyword do?

Answer

The pass keyword performs no function in Python other than being a legal keyword. The most common use of pass is as a placeholder for code that is not yet present in a program but where something is required to prevent an IndentationError from being reported such as after the definition of a class or function. It can also be used after for, while and if to act as a placeholder for missing code.

8 Likes

Eg.

>>> class Foo(object):
	pass

>>> foo = Foo()
>>> isinstance(foo, Foo)
True
>>> 

Were it not for that indented line of pseudo code, an instance would not be possible. Actually, since this is in the interactive console, we could keep hitting Enter and would never see the, >>>. The definition could not be escaped from without some code, indented per norm.

>>> class Bar(object):
	"""
Bar complements Foo
"""

	
>>> bar = Bar()
>>> isinstance(bar, Bar)
True
>>> print (bar.__doc__)

Bar complements Foo

>>> Bar.__doc__
'\nBar complements Foo\n'
>>> 

Clearly, pass is the cheapest, but we can still use this opportunity to document what we wish to accomplish with this class. No time like the starting point to document ideas and objectives. Let the code that results answer to that as it evolves.

11 Likes

3 posts were split to a new topic: What is a namespace in python?

3 posts were split to a new topic: What is the difference between a class and type?

Does pass keyword add any execution overhead - something similar to NOP instruction in assembly?

In Big O terms, it would be O(1).

2 Likes

Are there any Codecademy courses on Big O?

1 Like

would like to now that too.

1 Like

The pass key tells the compiler that you are coming back to complete the program and not to throw some errors.

1 Like

This is great tip that i just found out about but i always used to wonder about a placeholder for a function, for, if loop.