I am in the process of learning Python and I have reached the section about the pass statement. The guide I'm using defines it as being a null statement that is commonly used as a placeholder.
I still don't fully understand what that means though. What would be a simple/basic situation where the pass statement would be used and why would it be needed?
Suppose you are designing a new class with some methods that you don't want to implement, yet.
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
print "I'm meth_b"
If you were to leave out the pass, the code wouldn't run.
You would then get an:
IndentationError: expected an indented block
To summarize, the pass statement does nothing particular, but it can act as a placeholder, as demonstrated here.
Python has the syntactical requirement that code blocks (after if, except, def, class etc.) cannot be empty. Empty code blocks are however useful in a variety of different contexts, such as in examples below, which are the most frequent use cases I have seen.
Therefore, if nothing is supposed to happen in a code block, a pass is needed for such a block to not produce an IndentationError. Alternatively, any statement (including just a term to be evaluated, like the Ellipsis literal ... or a string, most often a docstring) can be used, but the pass makes clear that indeed nothing is supposed to happen, and does not need to be actually evaluated and (at least temporarily) stored in memory.
Ignoring (all or) a certain type of Exception (example from xml):
try:
self.version = "Expat %d.%d.%d" % expat.version_info
except AttributeError:
pass # unknown
Note: Ignoring all types of raises, as in the following example from pandas, is generally considered bad practice, because it also catches exceptions that should probably be passed on to the caller, e.g. KeyboardInterrupt or SystemExit (or even HardwareIsOnFireError – How do you know you aren't running on a custom box with specific errors defined, which some calling application would want to know about?).
try:
os.unlink(filename_larry)
except:
pass
Instead using at least except Error: or in this case preferably except OSError: is considered much better practice. A quick analysis of all Python modules I have installed gave me that more than 10% of all except ...: pass statements catch all exceptions, so it's still a frequent pattern in Python programming.
Deriving an exception class that does not add new behaviour (e.g., in SciPy):
class CompileError(Exception):
pass
Similarly, classes intended as abstract base class often have an explicit empty __init__ or other methods that subclasses are supposed to derive (e.g., pebl):
class _BaseSubmittingController(_BaseController):
def submit(self, tasks): pass
def retrieve(self, deferred_results): pass
Testing that code runs properly for a few test values, without caring about the results (from mpmath):
for x, error in MDNewton(mp, f, (1,-2), verbose=0,
norm=lambda x: norm(x, inf)):
pass
In class or function definitions, often a docstring is already in place as the obligatory statement to be executed as the only thing in the block. In such cases, the block may contain pass in addition to the docstring in order to say “This is indeed intended to do nothing.”, for example in pebl:
class ParsingError(Exception):
"""Error encountered while parsing an ill-formed datafile."""
pass
In some cases, pass is used as a placeholder to say “This method/class/if-block/... has not been implemented yet, but this will be the place to do it”, although I personally prefer the Ellipsis literal ... in order to strictly differentiate between this and the intentional “no-op” in the previous example. (Note that the Ellipsis literal is a valid expression only in Python 3)
For example, if I write a model in broad strokes, I might write
def update_agent(agent):
...
where others might have
def update_agent(agent):
pass
before
def time_step(agents):
for agent in agents:
update_agent(agent)
as a reminder to fill in the update_agent function at a later point, but run some tests already to see if the rest of the code behaves as intended. (A third option for this case is raise NotImplementedError. This is useful in particular for two cases: Either “This abstract method should be implemented by every subclass, and there isn't a generic way to define it in this base class”, or “This function, with this name, is not yet implemented in this release, but this is what its signature will look like”)
Besides its use as a placeholder for unimplemented functions, pass can be useful in filling out an if-else statement ("Explicit is better than implicit.")
def some_silly_transform(n):
# Even numbers should be divided by 2
if n % 2 == 0:
n /= 2
flag = True
# Negative odd numbers should return their absolute value
elif n < 0:
n = -n
flag = True
# Otherwise, number should remain unchanged
else:
pass
Of course, in this case, one would probably use return instead of assignment, but in cases where mutation is desired, this works best.
The use of pass here is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flag is set in the two specifically mentioned cases, but not in the else-case. Without using pass, a future programmer might move flag = True to outside the condition—thus setting flag in all cases.
Another case is with the boilerplate function often seen at the bottom of a file:
if __name__ == "__main__":
pass
In some files, it might be nice to leave that there with pass to allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.
Finally, as mentioned in other answers, it can be useful to do nothing when an exception is caught:
try:
n[i] = 0
except IndexError:
pass
The best and most accurate way to think of pass is as a way to explicitly tell the interpreter to do nothing. In the same way the following code:
def foo(x,y):
return x+y
means "if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result",
def bar():
pass
means "If I call the function bar(), do absolutely nothing."
The other answers are quite correct, but it's also useful for a few things that don't involve place-holding.
For example, in a bit of code I worked on just recently, it was necessary to divide two variables, and it was possible for the divisor to be zero.
c = a / b
will, obviously, produce a ZeroDivisionError if b is zero. In this particular situation, leaving c as zero was the desired behavior in the case that b was zero, so I used the following code:
try:
c = a / b
except ZeroDivisionError:
pass
Another, less standard usage is as a handy place to put a breakpoint for your debugger. For example, I wanted a bit of code to break into the debugger on the 20th iteration of a for... in statement. So:
for t in range(25):
do_a_thing(t)
if t == 20:
pass
with the breakpoint on pass.
A common use case where it can be used 'as is' is to override a class just to create a type (which is otherwise the same as the superclass), e.g.
class Error(Exception):
pass
So you can raise and catch Error exceptions. What matters here is the type of exception, rather than the content.
pass in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:
1: Can be used in class
class TestClass:
pass
2: Can be use in loop and conditional statements:
if (something == true): # used in conditional statement
pass
while (some condition is true): # user is not sure about the body of the loop
pass
3: Can be used in function:
def testFunction(args): # The programmer wants to implement the body of the function later
pass
pass is mostly used when the programmer does not want to give implementation at the moment, but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for a blank or unimplemented class, function, or conditional statement it gives an error:
IndentationError: expected an indented block
pass can be used in such scenarios.
You can say that pass means a NOP (no operation) operation. You will get a clear picture after this example:
C Program
#include<stdio.h>
void main()
{
int age = 12;
if( age < 18 )
{
printf("You are not adult, so you can't do that task ");
}
else if( age >= 18 && age < 60)
{
// I will add more code later inside it
}
else
{
printf("You are too old to do anything , sorry ");
}
}
Now how you will write that in Python:
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
else:
print "You are too old to do anything , sorry "
But your code will give an error because it required an indented block after elif. Here is the role of the pass keyword.
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
pass
else:
print "You are too old to do anything , sorry "
Now I think it's clear to you.
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
Honestly, I think the official Python docs describe it quite well and provide some examples:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
... pass
...
Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:
>>> def initlog(*args):
... pass # Remember to implement this!
...
If you want to import a module, if it exists, and ignore importing it, if that module does not exists, you can use the below code:
try:
import a_module
except ImportError:
pass
# The rest of your code
If you avoid writing the pass statement and continue writing the rest of your code, a IndentationError would be raised, since the lines after opening the except block are not indented.
As the book said, I only ever use it as a temporary placeholder, i.e.,
# code that does something to to a variable, var
if var == 2000:
pass
else:
var += 1
And then later fill in the scenario where var == 2000.
In addition to the "main" use of "I don't want anything to go here," here's one I just found, assuming gen is an Iterator:
i = 0
obj = None
for i, obj in enumerate(gen):
pass
This gets the last object yielded from gen and the length of gen, all in one pass. (Sorta similar to a while loop that ends with a semicolon in C, come to think of it.)
Pass is usually helpful when you are writing code to design a game or something of that type , now as you proceed with the code , you would realize that , there are some functions you don't want to move ahead and want to leave it untouched and move further on with the code and then revisit the function later , but as you do so , the compiler would obviously thrown an error saying it isn't either recognized and all sorts of other things!! In this condition you use pass so that the compiler would simply neglect the function and move further on with the code !!
For example -
if __name__ = "__main__":
pass
print("Hello World!")
Here the compiler would neglect the if name part and would print Hello World as directed !!
Thanks !
First, if you want to write a block, like this:
if statement:
pass
for i in range(abc):
pass
def func():
pass
And pass can to be a placeholder.
Second, it can let you 'communicate' with IDE:
When you want to let your IDE decrement indentations like this:
If your program written here:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
# cursor in there
Now your indentations count is 2, but you want it is 1 in next line.
You can type a pass, and your program to be this:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
pass# cursor in there
And return. It will let you happy:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
pass
# cursor in there
Now the indentation count is 1.
pass is just the indication code of emptiness.
For example, pass is used to create a empty class or function as shown below:
class Test:
pass
def test():
pass
But, if a class or function really doesn't have anything even pass as shown below:
class Test:
# pass
def test():
# psss
There is an error as shown below:
SyntaxError: unexpected EOF while parsing
And as I said before, pass is just the indication code of emptiness so if there is some code after pass, the code works as shown below:
class Test:
pass
x = "Hello World"
def test():
pass
return "Hello World"
print(Test.x) # Hello World
print(test()) # Hello World
The pass statement in Python is used when a statement is required syntactically, but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):
Example:
#!/usr/bin/python
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
This will produce the following result:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block, but it is no longer required.
You can then remove the statements inside the block, but let the block remain with a pass statement so that it doesn't interfere with other parts of the code.
Pass refers to ignore...as simple as it is. If the given condition is true and the next statement is pass, it ignores that value or iteration and proceed to the next line.
Example:
for i in range (1, 100):
if i%2 == 0:
pass
else:
print(i)
Output: Prints all the odd numbers from 1-100
This is because the modulus of an even number is equal to zero, hence it ignores the number and proceeds to next number. Since odd numbers' modulus are not equal to zero, the else part of the loop is executed and it's printed.
pass is used to avoid indentation errors in Python.
If we take languages like C, C++, and Java, they have braces like:
if(i==0)
{}
else
{//some code}
But in Python we use indentation instead of braces, so to avoid such errors we use pass.
Remembered as you were playing a quiz and
if(dont_know_the_answer)
pass
Example program,
for letter in 'geeksforgeeks':
pass
print 'Last letter: ', letter
Related
Let's say,
def sample():
if a==1:
print(a)
else:
continue
for i in language:
a=i
sample()
I want to use this function in a loop, but the continue command gives me an error because there is no loop. What can I do?
Return a boolean from the function and based on the return value make continue or not because continue must be within a loop
continue keyword in python is only available in for or while loops. Also block defined variables like a are not available on the global scope.
I don't know what you want to achieve but assuming your code, you want to extract a condition into a function, something like this:
def condition(a):
return a == 1
def sample(a):
print(a)
for i in language:
a=i
if condition(a):
sample(a)
else:
continue
There are several best-practice patterns of exactly how to do this, depending on your needs.
0. Factor your code better
Before doing any of the below, stop and ask yourself if you can just do this instead:
def sample(a):
print(a)
for i in language:
if i != 1:
continue
sample(i)
This is so much better:
it's clearer to the reader (everything you need to understand the loop's control flow is entirely local to the loop - it's right there in the loop, we don't have to look anywhere else farther away like a function definition to know when or why or how the loop will do the next thing),
it's cleaner (less boilerplate code than any of the solutions below),
it's more efficient, technically (not that this should matter until you measure a performance problem, but this might appeal to you; going into a function and coming back out of it, plus somehow telling the loop outside the function to continue - that's more work to achieve the same thing), and
it's simpler (objectively: there is less code complected together - the loop behavior is no longer tied to the body of the sample function, for example).
But, if you must:
1. Add boolean return
The simplest change that works with your example is to return a boolean:
def sample(a):
if a==1:
print(a)
else:
return True
return False
for i in language:
if sample(i):
continue
However, don't just mindlessly always use True for continue - for each function, use the one that fits with the function. In fact, in well-factored code, the boolean return value will make sense without even knowing that you are using it in some loop to continue or not.
For example, if you have a function called check_if_valid, then the boolean return value just makes sense without any loops - it tells you if the input is valid - and at the same time, either of these loops is sensible depending on context:
for thing in thing_list:
if check_if_valid(thing):
continue
... # do something to fix the invalid things
for thing in thing_list:
if not check_if_valid(thing):
continue
... # do something only with valid things
2. Reuse existing return
If your function already returns something, or you can rethink your code so that returns make sense, then you can ask yourself: is there a good way to decide to continue based on that return value?
For example, let's say inside your sample function you were actually trying to do something like this:
def sample(a):
record = select_from_database(a)
if record.status == 1:
print(record)
else:
continue
Well then you can rewrite it like this:
def sample(a):
record = select_from_database(a)
if record.status == 1:
print(record)
return record
for i in language:
record = sample(a)
if record.status != 1:
continue
Of course in this simple example, it's cleaner to just not have the sample function, but I am trusting that your sample function is justifiably more complex.
3. Special "continue" return
If no existing return value makes sense, or you don't want to couple the loop to the return value of your function, the next simplest pattern is to create and return a special unique "sentinel" object instance:
_continue = object()
def sample(a):
if a==1:
print(a)
else:
return _continue
for i in language:
result = sample(i):
if result = _continue:
continue
(If this is part of a module's API, which is something that you are saying if you name it like sample instead of like _sample, then I would name the sentinel value continue_ rather than _continue... But I also would not make something like this part of an API unless I absolutely had to.)
(If you're using a type checker and it complains about returning an object instance conflicting with your normal return value, you can make a Continue class and return an instance of that instead of an instance of object(). Then the type hinting for the function return value can be a type union between your normal return type and the Continue type. If you have multiple control flow constructs in your code that you want to smuggle across function call lines like this.)
4. Wrap return value (and "monads")
Sometimes, if the type union thing isn't good enough for some reason, you may want to create a wrapper object, and have it store either your original return value, or indicate control flow. I only mention this option for completeness, without examples, because I think the previous options are better most of the time in Python. But if you take the time to learn about "Option types" and "maybe monads", it's kinda like that.
(Also, notice that in all of my examples, I fixed your backdoor argument passing through a global variable to be an explicit clearly passed argument. This makes the code easier to understand, predict, and verify for correctness - you might not see that yet but keep an eye out for implicit state passing making code harder to follow and keep correct as you grow as a developer, read more code by others, and deal with bugs.)
It is because the scope of the function doesn't know we are in a loop. You have to put the continue keyword inside the loop
continue keyword cannot be used inside a function. It must be inside the loop. There is a similar question here. Maybe you can do something like the following.
language = [1,1,1,2,3]
a = 1
def sample():
if a == 1:
print(a)
return False
else:
return True
for i in language:
if sample():
continue
else:
a = i
OR something like this:
language = [1,1,1,2,3]
a = 1
def gen(base):
for item in base:
if a == 1:
yield a
else:
continue
for i in gen(language):
a = i
print(a)
Lets say I have a function myFunc defined as
def myFunc(value):
return value if isinstance(value, int) else None
Now wherever in my project I use myFunc the enclosing funciton should return automatically if the value returned from myFunc is None and should continue if some integer value is returned
For example:
def dumbFunc():
# some code
# goes here..
result = myFunc('foo')
# some code
# goes here..
This funciton should automatically behave like..
def dumbFunc():
# some code
# goes here..
result = myFunc('foo')
if not result:
return
# some code
# goes here..
PS - I don't know whether this thing even possible or not.
This is simply not possible.
Apart from exceptions, you cannot give a called function the ability to impact the control flow of the calling scope. So a function call foo() can never interrupt the control flow without throwing an exception. As a consumer of the function, you (the calling function) always have the responsibility yourself to handle such cases and decide about your own control flow.
And it is a very good idea to do it like that. Just the possibility that a function call might interrupt my control flow without having a possibility to react on it first sounds like a pure nightmare. Just alone for the ability to release and cleanup resources, it is very important that the control flow is not taken from me.
Exceptions are the notable exception from this, but of course this is a deeply rooted language feature which also still gives me the ability to act upon it (by catching exceptions, and even by having finally blocks to perform clean up tasks). Exceptions are deliberately not silent but very loud, so that interruptions from the deterministic control flow are clearly visible and have a minimum impact when properly handled.
But having a silent feature that does neither give any control nor feedback would be just a terrible idea.
If myFunc is used at 100 places in my project, everywhere I need to put an if condition after it.
If your code is like that that you could just return nothing from any function that calls myFunc without having to do anything, then either you are building an unrealistic fantasy project, or you simply are not aware of the implications this can have to the calling code of the functions that would be returned that way.
ok, I'll bite.
on the one hand, this isn't really possible. if you want to check something you have to have a line in your code that checks it.
there are a few ways you could achieve something like this, but i think you may have already found the best one.
you already have this function:
def myFunc(value):
return value if isinstance(value, int) else None
I would probably have done:
def myFunc(value):
return isinstance(value, int)
but either way you could use it:
def dumb_func():
value = do_something()
if myFunc(value):
return
do_more()
return value
alternately you could use try and except
I would raise a TypeError, seeing as that seems to be what you are checking:
def myFunc(value):
if not isinstance(value, int):
raise TypeError('myFunc found that {} is not an int'.format(value))
then you can use this as such
def dumb_func():
value = do_something()
try:
myFunc(value):
Except TypeError as e:
print e # some feedback that this has happened, but no error raised
return
do_more()
return value
for bonus points you could define a custom exception (which is safer because then when you catch that specific error you know it wasn't raised by anything else in your code, also if you did that you could be lazier eg:)
Class CustomTypeError(TypeError):
pass
def dumb_func():
try:
value = do_something()
myFunc(value):
do_more()
return value
Except CustomTypeError as e:
print e # some feedback that this has happened, but no error raised
return
but none of this gets around the fact that if you want to act based on the result of a test, you have to check that result.
Python has a ternary conditional operator, and the syntax you used is right, so this will work:
def myFunc(value):
return value if isinstance(value, int) else None
def dumbFunc():
print("Works?")
result = myFunc(5)
print(result)
dumbFunc()
Result:
Works?
5
I want the function to return automatically in that case
This is not possible. To do that, you have to check the return value of myFunc() and act upon it.
PS: You could do that with a goto statement, but Python, fortunately, doesn't support this functionality.
I am in the process of learning Python and I have reached the section about the pass statement. The guide I'm using defines it as being a null statement that is commonly used as a placeholder.
I still don't fully understand what that means though. What would be a simple/basic situation where the pass statement would be used and why would it be needed?
Suppose you are designing a new class with some methods that you don't want to implement, yet.
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
print "I'm meth_b"
If you were to leave out the pass, the code wouldn't run.
You would then get an:
IndentationError: expected an indented block
To summarize, the pass statement does nothing particular, but it can act as a placeholder, as demonstrated here.
Python has the syntactical requirement that code blocks (after if, except, def, class etc.) cannot be empty. Empty code blocks are however useful in a variety of different contexts, such as in examples below, which are the most frequent use cases I have seen.
Therefore, if nothing is supposed to happen in a code block, a pass is needed for such a block to not produce an IndentationError. Alternatively, any statement (including just a term to be evaluated, like the Ellipsis literal ... or a string, most often a docstring) can be used, but the pass makes clear that indeed nothing is supposed to happen, and does not need to be actually evaluated and (at least temporarily) stored in memory.
Ignoring (all or) a certain type of Exception (example from xml):
try:
self.version = "Expat %d.%d.%d" % expat.version_info
except AttributeError:
pass # unknown
Note: Ignoring all types of raises, as in the following example from pandas, is generally considered bad practice, because it also catches exceptions that should probably be passed on to the caller, e.g. KeyboardInterrupt or SystemExit (or even HardwareIsOnFireError – How do you know you aren't running on a custom box with specific errors defined, which some calling application would want to know about?).
try:
os.unlink(filename_larry)
except:
pass
Instead using at least except Error: or in this case preferably except OSError: is considered much better practice. A quick analysis of all Python modules I have installed gave me that more than 10% of all except ...: pass statements catch all exceptions, so it's still a frequent pattern in Python programming.
Deriving an exception class that does not add new behaviour (e.g., in SciPy):
class CompileError(Exception):
pass
Similarly, classes intended as abstract base class often have an explicit empty __init__ or other methods that subclasses are supposed to derive (e.g., pebl):
class _BaseSubmittingController(_BaseController):
def submit(self, tasks): pass
def retrieve(self, deferred_results): pass
Testing that code runs properly for a few test values, without caring about the results (from mpmath):
for x, error in MDNewton(mp, f, (1,-2), verbose=0,
norm=lambda x: norm(x, inf)):
pass
In class or function definitions, often a docstring is already in place as the obligatory statement to be executed as the only thing in the block. In such cases, the block may contain pass in addition to the docstring in order to say “This is indeed intended to do nothing.”, for example in pebl:
class ParsingError(Exception):
"""Error encountered while parsing an ill-formed datafile."""
pass
In some cases, pass is used as a placeholder to say “This method/class/if-block/... has not been implemented yet, but this will be the place to do it”, although I personally prefer the Ellipsis literal ... in order to strictly differentiate between this and the intentional “no-op” in the previous example. (Note that the Ellipsis literal is a valid expression only in Python 3)
For example, if I write a model in broad strokes, I might write
def update_agent(agent):
...
where others might have
def update_agent(agent):
pass
before
def time_step(agents):
for agent in agents:
update_agent(agent)
as a reminder to fill in the update_agent function at a later point, but run some tests already to see if the rest of the code behaves as intended. (A third option for this case is raise NotImplementedError. This is useful in particular for two cases: Either “This abstract method should be implemented by every subclass, and there isn't a generic way to define it in this base class”, or “This function, with this name, is not yet implemented in this release, but this is what its signature will look like”)
Besides its use as a placeholder for unimplemented functions, pass can be useful in filling out an if-else statement ("Explicit is better than implicit.")
def some_silly_transform(n):
# Even numbers should be divided by 2
if n % 2 == 0:
n /= 2
flag = True
# Negative odd numbers should return their absolute value
elif n < 0:
n = -n
flag = True
# Otherwise, number should remain unchanged
else:
pass
Of course, in this case, one would probably use return instead of assignment, but in cases where mutation is desired, this works best.
The use of pass here is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flag is set in the two specifically mentioned cases, but not in the else-case. Without using pass, a future programmer might move flag = True to outside the condition—thus setting flag in all cases.
Another case is with the boilerplate function often seen at the bottom of a file:
if __name__ == "__main__":
pass
In some files, it might be nice to leave that there with pass to allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.
Finally, as mentioned in other answers, it can be useful to do nothing when an exception is caught:
try:
n[i] = 0
except IndexError:
pass
The best and most accurate way to think of pass is as a way to explicitly tell the interpreter to do nothing. In the same way the following code:
def foo(x,y):
return x+y
means "if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result",
def bar():
pass
means "If I call the function bar(), do absolutely nothing."
The other answers are quite correct, but it's also useful for a few things that don't involve place-holding.
For example, in a bit of code I worked on just recently, it was necessary to divide two variables, and it was possible for the divisor to be zero.
c = a / b
will, obviously, produce a ZeroDivisionError if b is zero. In this particular situation, leaving c as zero was the desired behavior in the case that b was zero, so I used the following code:
try:
c = a / b
except ZeroDivisionError:
pass
Another, less standard usage is as a handy place to put a breakpoint for your debugger. For example, I wanted a bit of code to break into the debugger on the 20th iteration of a for... in statement. So:
for t in range(25):
do_a_thing(t)
if t == 20:
pass
with the breakpoint on pass.
A common use case where it can be used 'as is' is to override a class just to create a type (which is otherwise the same as the superclass), e.g.
class Error(Exception):
pass
So you can raise and catch Error exceptions. What matters here is the type of exception, rather than the content.
pass in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:
1: Can be used in class
class TestClass:
pass
2: Can be use in loop and conditional statements:
if (something == true): # used in conditional statement
pass
while (some condition is true): # user is not sure about the body of the loop
pass
3: Can be used in function:
def testFunction(args): # The programmer wants to implement the body of the function later
pass
pass is mostly used when the programmer does not want to give implementation at the moment, but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for a blank or unimplemented class, function, or conditional statement it gives an error:
IndentationError: expected an indented block
pass can be used in such scenarios.
You can say that pass means a NOP (no operation) operation. You will get a clear picture after this example:
C Program
#include<stdio.h>
void main()
{
int age = 12;
if( age < 18 )
{
printf("You are not adult, so you can't do that task ");
}
else if( age >= 18 && age < 60)
{
// I will add more code later inside it
}
else
{
printf("You are too old to do anything , sorry ");
}
}
Now how you will write that in Python:
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
else:
print "You are too old to do anything , sorry "
But your code will give an error because it required an indented block after elif. Here is the role of the pass keyword.
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
pass
else:
print "You are too old to do anything , sorry "
Now I think it's clear to you.
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
Honestly, I think the official Python docs describe it quite well and provide some examples:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
... pass
...
Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:
>>> def initlog(*args):
... pass # Remember to implement this!
...
If you want to import a module, if it exists, and ignore importing it, if that module does not exists, you can use the below code:
try:
import a_module
except ImportError:
pass
# The rest of your code
If you avoid writing the pass statement and continue writing the rest of your code, a IndentationError would be raised, since the lines after opening the except block are not indented.
As the book said, I only ever use it as a temporary placeholder, i.e.,
# code that does something to to a variable, var
if var == 2000:
pass
else:
var += 1
And then later fill in the scenario where var == 2000.
In addition to the "main" use of "I don't want anything to go here," here's one I just found, assuming gen is an Iterator:
i = 0
obj = None
for i, obj in enumerate(gen):
pass
This gets the last object yielded from gen and the length of gen, all in one pass. (Sorta similar to a while loop that ends with a semicolon in C, come to think of it.)
Pass is usually helpful when you are writing code to design a game or something of that type , now as you proceed with the code , you would realize that , there are some functions you don't want to move ahead and want to leave it untouched and move further on with the code and then revisit the function later , but as you do so , the compiler would obviously thrown an error saying it isn't either recognized and all sorts of other things!! In this condition you use pass so that the compiler would simply neglect the function and move further on with the code !!
For example -
if __name__ = "__main__":
pass
print("Hello World!")
Here the compiler would neglect the if name part and would print Hello World as directed !!
Thanks !
First, if you want to write a block, like this:
if statement:
pass
for i in range(abc):
pass
def func():
pass
And pass can to be a placeholder.
Second, it can let you 'communicate' with IDE:
When you want to let your IDE decrement indentations like this:
If your program written here:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
# cursor in there
Now your indentations count is 2, but you want it is 1 in next line.
You can type a pass, and your program to be this:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
pass# cursor in there
And return. It will let you happy:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
pass
# cursor in there
Now the indentation count is 1.
pass is just the indication code of emptiness.
For example, pass is used to create a empty class or function as shown below:
class Test:
pass
def test():
pass
But, if a class or function really doesn't have anything even pass as shown below:
class Test:
# pass
def test():
# psss
There is an error as shown below:
SyntaxError: unexpected EOF while parsing
And as I said before, pass is just the indication code of emptiness so if there is some code after pass, the code works as shown below:
class Test:
pass
x = "Hello World"
def test():
pass
return "Hello World"
print(Test.x) # Hello World
print(test()) # Hello World
The pass statement in Python is used when a statement is required syntactically, but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):
Example:
#!/usr/bin/python
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
This will produce the following result:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block, but it is no longer required.
You can then remove the statements inside the block, but let the block remain with a pass statement so that it doesn't interfere with other parts of the code.
Pass refers to ignore...as simple as it is. If the given condition is true and the next statement is pass, it ignores that value or iteration and proceed to the next line.
Example:
for i in range (1, 100):
if i%2 == 0:
pass
else:
print(i)
Output: Prints all the odd numbers from 1-100
This is because the modulus of an even number is equal to zero, hence it ignores the number and proceeds to next number. Since odd numbers' modulus are not equal to zero, the else part of the loop is executed and it's printed.
pass is used to avoid indentation errors in Python.
If we take languages like C, C++, and Java, they have braces like:
if(i==0)
{}
else
{//some code}
But in Python we use indentation instead of braces, so to avoid such errors we use pass.
Remembered as you were playing a quiz and
if(dont_know_the_answer)
pass
Example program,
for letter in 'geeksforgeeks':
pass
print 'Last letter: ', letter
In Ruby, I can pass a block of code to a method.
For example, I can pass different code blocks to get_schedules_with_retries method.
And invoke the block by calling black.call
I'd like to know how could I implement that logic in Python,
Because I have lots of code blocks, need retry pattern.
I don't like copy paste the retry logic in many code blocks
Example:
def get_schedules_with_retries(&block)
max_retry_count = 3
retry_count = 0
while (retry_count < max_retry_count)
begin
schedules = get_more_raw_schedules
block.call(schedules)
rescue Exception => e
print_error(e)
end
if schedules.count > 0
break
else
retry_count+=1
end
end
return schedules
end
get_schedules_with_retries do |schedules|
# do something here
end
get_schedules_with_retries do |schedules|
# do another thing here
end
In Python, a block is a syntactic feature (an indentation under block opening statements like if or def) and not an object. The feature you expect may be a closure (which can access variables outside of the block), which you can achieve using inner functions, but any callable could be used. Because of how lambda works in Python, the inline function definition you've shown with do |arg| is limited to a single expression.
Here's a rough rewrite of your sample code in Python.
def get_schedules_with_retries(callable, max_retry_count = 3):
retry_count = 0
while retry_count < max_retry_count:
schedules = get_more_raw_schedules()
try:
callable(schedules)
except: # Note: could filter types, bind name etc.
traceback.print_exc()
if schedules.count > 0:
break
else:
retry_count+=1
return schedules
get_schedules_with_retries(lambda schedules: single_expression)
def more_complex_function(schedules):
pass # do another thing here
get_schedules_with_retries(more_complex_function)
One variant uses a for loop to make it clear the loop is finite:
def call_with_retries(callable, args=(), tries=3):
for attempt in range(tries):
try:
result=callable(*args)
break
except:
traceback.print_exc()
continue
else: # break never reached, so function always failed
raise # Reraises the exception we printed above
return result
Frequently when passing callables like this, you'll already have the function you want available somewhere and won't need to redefine it. For instance, methods on objects (bound methods) are perfectly valid callables.
You could do it like this:
def codeBlock(paramter1, parameter2):
print("I'm a code block")
def passMeABlock(block, *args):
block(*args)
#pass the block like this
passMeABlock(codeBlock, 1, 2)
You do so by defining a function, either by using the def statement or a lambda expression.
There are other techniques however, that may apply here. If you need to apply common logic to the input or output of a function, write a decorator. If you need to handle exceptions in a block of code, perhaps creating a context manager is applicable.
I am in the process of learning Python and I have reached the section about the pass statement. The guide I'm using defines it as being a null statement that is commonly used as a placeholder.
I still don't fully understand what that means though. What would be a simple/basic situation where the pass statement would be used and why would it be needed?
Suppose you are designing a new class with some methods that you don't want to implement, yet.
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
print "I'm meth_b"
If you were to leave out the pass, the code wouldn't run.
You would then get an:
IndentationError: expected an indented block
To summarize, the pass statement does nothing particular, but it can act as a placeholder, as demonstrated here.
Python has the syntactical requirement that code blocks (after if, except, def, class etc.) cannot be empty. Empty code blocks are however useful in a variety of different contexts, such as in examples below, which are the most frequent use cases I have seen.
Therefore, if nothing is supposed to happen in a code block, a pass is needed for such a block to not produce an IndentationError. Alternatively, any statement (including just a term to be evaluated, like the Ellipsis literal ... or a string, most often a docstring) can be used, but the pass makes clear that indeed nothing is supposed to happen, and does not need to be actually evaluated and (at least temporarily) stored in memory.
Ignoring (all or) a certain type of Exception (example from xml):
try:
self.version = "Expat %d.%d.%d" % expat.version_info
except AttributeError:
pass # unknown
Note: Ignoring all types of raises, as in the following example from pandas, is generally considered bad practice, because it also catches exceptions that should probably be passed on to the caller, e.g. KeyboardInterrupt or SystemExit (or even HardwareIsOnFireError – How do you know you aren't running on a custom box with specific errors defined, which some calling application would want to know about?).
try:
os.unlink(filename_larry)
except:
pass
Instead using at least except Error: or in this case preferably except OSError: is considered much better practice. A quick analysis of all Python modules I have installed gave me that more than 10% of all except ...: pass statements catch all exceptions, so it's still a frequent pattern in Python programming.
Deriving an exception class that does not add new behaviour (e.g., in SciPy):
class CompileError(Exception):
pass
Similarly, classes intended as abstract base class often have an explicit empty __init__ or other methods that subclasses are supposed to derive (e.g., pebl):
class _BaseSubmittingController(_BaseController):
def submit(self, tasks): pass
def retrieve(self, deferred_results): pass
Testing that code runs properly for a few test values, without caring about the results (from mpmath):
for x, error in MDNewton(mp, f, (1,-2), verbose=0,
norm=lambda x: norm(x, inf)):
pass
In class or function definitions, often a docstring is already in place as the obligatory statement to be executed as the only thing in the block. In such cases, the block may contain pass in addition to the docstring in order to say “This is indeed intended to do nothing.”, for example in pebl:
class ParsingError(Exception):
"""Error encountered while parsing an ill-formed datafile."""
pass
In some cases, pass is used as a placeholder to say “This method/class/if-block/... has not been implemented yet, but this will be the place to do it”, although I personally prefer the Ellipsis literal ... in order to strictly differentiate between this and the intentional “no-op” in the previous example. (Note that the Ellipsis literal is a valid expression only in Python 3)
For example, if I write a model in broad strokes, I might write
def update_agent(agent):
...
where others might have
def update_agent(agent):
pass
before
def time_step(agents):
for agent in agents:
update_agent(agent)
as a reminder to fill in the update_agent function at a later point, but run some tests already to see if the rest of the code behaves as intended. (A third option for this case is raise NotImplementedError. This is useful in particular for two cases: Either “This abstract method should be implemented by every subclass, and there isn't a generic way to define it in this base class”, or “This function, with this name, is not yet implemented in this release, but this is what its signature will look like”)
Besides its use as a placeholder for unimplemented functions, pass can be useful in filling out an if-else statement ("Explicit is better than implicit.")
def some_silly_transform(n):
# Even numbers should be divided by 2
if n % 2 == 0:
n /= 2
flag = True
# Negative odd numbers should return their absolute value
elif n < 0:
n = -n
flag = True
# Otherwise, number should remain unchanged
else:
pass
Of course, in this case, one would probably use return instead of assignment, but in cases where mutation is desired, this works best.
The use of pass here is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flag is set in the two specifically mentioned cases, but not in the else-case. Without using pass, a future programmer might move flag = True to outside the condition—thus setting flag in all cases.
Another case is with the boilerplate function often seen at the bottom of a file:
if __name__ == "__main__":
pass
In some files, it might be nice to leave that there with pass to allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.
Finally, as mentioned in other answers, it can be useful to do nothing when an exception is caught:
try:
n[i] = 0
except IndexError:
pass
The best and most accurate way to think of pass is as a way to explicitly tell the interpreter to do nothing. In the same way the following code:
def foo(x,y):
return x+y
means "if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result",
def bar():
pass
means "If I call the function bar(), do absolutely nothing."
The other answers are quite correct, but it's also useful for a few things that don't involve place-holding.
For example, in a bit of code I worked on just recently, it was necessary to divide two variables, and it was possible for the divisor to be zero.
c = a / b
will, obviously, produce a ZeroDivisionError if b is zero. In this particular situation, leaving c as zero was the desired behavior in the case that b was zero, so I used the following code:
try:
c = a / b
except ZeroDivisionError:
pass
Another, less standard usage is as a handy place to put a breakpoint for your debugger. For example, I wanted a bit of code to break into the debugger on the 20th iteration of a for... in statement. So:
for t in range(25):
do_a_thing(t)
if t == 20:
pass
with the breakpoint on pass.
A common use case where it can be used 'as is' is to override a class just to create a type (which is otherwise the same as the superclass), e.g.
class Error(Exception):
pass
So you can raise and catch Error exceptions. What matters here is the type of exception, rather than the content.
pass in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:
1: Can be used in class
class TestClass:
pass
2: Can be use in loop and conditional statements:
if (something == true): # used in conditional statement
pass
while (some condition is true): # user is not sure about the body of the loop
pass
3: Can be used in function:
def testFunction(args): # The programmer wants to implement the body of the function later
pass
pass is mostly used when the programmer does not want to give implementation at the moment, but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for a blank or unimplemented class, function, or conditional statement it gives an error:
IndentationError: expected an indented block
pass can be used in such scenarios.
You can say that pass means a NOP (no operation) operation. You will get a clear picture after this example:
C Program
#include<stdio.h>
void main()
{
int age = 12;
if( age < 18 )
{
printf("You are not adult, so you can't do that task ");
}
else if( age >= 18 && age < 60)
{
// I will add more code later inside it
}
else
{
printf("You are too old to do anything , sorry ");
}
}
Now how you will write that in Python:
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
else:
print "You are too old to do anything , sorry "
But your code will give an error because it required an indented block after elif. Here is the role of the pass keyword.
age = 12
if age < 18:
print "You are not adult, so you can't do that task"
elif age >= 18 and age < 60:
pass
else:
print "You are too old to do anything , sorry "
Now I think it's clear to you.
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
Honestly, I think the official Python docs describe it quite well and provide some examples:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
... pass
...
Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:
>>> def initlog(*args):
... pass # Remember to implement this!
...
If you want to import a module, if it exists, and ignore importing it, if that module does not exists, you can use the below code:
try:
import a_module
except ImportError:
pass
# The rest of your code
If you avoid writing the pass statement and continue writing the rest of your code, a IndentationError would be raised, since the lines after opening the except block are not indented.
As the book said, I only ever use it as a temporary placeholder, i.e.,
# code that does something to to a variable, var
if var == 2000:
pass
else:
var += 1
And then later fill in the scenario where var == 2000.
In addition to the "main" use of "I don't want anything to go here," here's one I just found, assuming gen is an Iterator:
i = 0
obj = None
for i, obj in enumerate(gen):
pass
This gets the last object yielded from gen and the length of gen, all in one pass. (Sorta similar to a while loop that ends with a semicolon in C, come to think of it.)
Pass is usually helpful when you are writing code to design a game or something of that type , now as you proceed with the code , you would realize that , there are some functions you don't want to move ahead and want to leave it untouched and move further on with the code and then revisit the function later , but as you do so , the compiler would obviously thrown an error saying it isn't either recognized and all sorts of other things!! In this condition you use pass so that the compiler would simply neglect the function and move further on with the code !!
For example -
if __name__ = "__main__":
pass
print("Hello World!")
Here the compiler would neglect the if name part and would print Hello World as directed !!
Thanks !
First, if you want to write a block, like this:
if statement:
pass
for i in range(abc):
pass
def func():
pass
And pass can to be a placeholder.
Second, it can let you 'communicate' with IDE:
When you want to let your IDE decrement indentations like this:
If your program written here:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
# cursor in there
Now your indentations count is 2, but you want it is 1 in next line.
You can type a pass, and your program to be this:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
pass# cursor in there
And return. It will let you happy:
class abc(parent):
def __init__(self, params):
self.params=params
if d:
return
else:
return
pass
# cursor in there
Now the indentation count is 1.
pass is just the indication code of emptiness.
For example, pass is used to create a empty class or function as shown below:
class Test:
pass
def test():
pass
But, if a class or function really doesn't have anything even pass as shown below:
class Test:
# pass
def test():
# psss
There is an error as shown below:
SyntaxError: unexpected EOF while parsing
And as I said before, pass is just the indication code of emptiness so if there is some code after pass, the code works as shown below:
class Test:
pass
x = "Hello World"
def test():
pass
return "Hello World"
print(Test.x) # Hello World
print(test()) # Hello World
The pass statement in Python is used when a statement is required syntactically, but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):
Example:
#!/usr/bin/python
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
This will produce the following result:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block, but it is no longer required.
You can then remove the statements inside the block, but let the block remain with a pass statement so that it doesn't interfere with other parts of the code.
Pass refers to ignore...as simple as it is. If the given condition is true and the next statement is pass, it ignores that value or iteration and proceed to the next line.
Example:
for i in range (1, 100):
if i%2 == 0:
pass
else:
print(i)
Output: Prints all the odd numbers from 1-100
This is because the modulus of an even number is equal to zero, hence it ignores the number and proceeds to next number. Since odd numbers' modulus are not equal to zero, the else part of the loop is executed and it's printed.
pass is used to avoid indentation errors in Python.
If we take languages like C, C++, and Java, they have braces like:
if(i==0)
{}
else
{//some code}
But in Python we use indentation instead of braces, so to avoid such errors we use pass.
Remembered as you were playing a quiz and
if(dont_know_the_answer)
pass
Example program,
for letter in 'geeksforgeeks':
pass
print 'Last letter: ', letter