if else-if making code look ugly any cleaner solution? - python

I have around 20 functions (is_func1, is_fucn2, is_func3...) returning boolean
I assume there is only one function which returns true and I want that!
I am doing:
if is_func1(param1, param2):
# I pass 1 to following
abc(1) # I pass 1
some_list.append(1)
elif is_func2(param1, param2):
# I pass 2 to following
abc(2) # I pass 1
some_list.append(2)
...
.
.
elif is_func20(param1, param2):
...
Please note: param1 and param2 are different for each, abc and some_list take parameters depending on the function.
The code looks big and there is repetition in calling abc and some_list, I can pull this login in a function! but is there any other cleaner solution?
I can think of putting functions in a data structure and loop to call them.

What about
functionList = [is_func1, is_func2, ..., is_func20]
for index, func in enumerate(functionList):
if(func(param1, param2)):
abc(index+1)
some_list.append(index+1)
break

I can think of putting functions in a data structure and loop to call them.
Yes, probably you should do that since your code needs to be refactored,
and a data driven design is a good choice.
An example similar to BlueRaja's answer,
# arg1, arg2 and ret can have any values on each record
data = ((isfunc1, arg1, arg2, ret),
(isfunc2, arg1, arg2, ret),
(isfunc3, arg1, arg2, ret),
...)
for d in data:
if d[0](d[1], d[2]):
abc(d[3])
some_list.append(d[3])
break

If each branch of your event dispatcher is in fact different, then there just isn't any way to get around writing the individual branch handlers, and there isn't any way to get around polling the different cases and choosing a branch.

This looks a good case to apply Chain of responsibility pattern.
I know how to give the example with objects, not functions, so I'll do that:
class HandleWithFunc1
def __init__(self, otherHandler):
self.otherHandler = otherHandler
def Handle(param1, param2):
if ( should I handle with func1? ):
#Handle with func1
return
if otherHandler == None:
raise "Nobody handled the call!"
otherHandler.Handle(param1, param2)
class HandleWithFunc2:
def __init__(self, otherHandler):
self.otherHandler = otherHandler
def Handle(param1, param2):
if ( should I handle with func1? ):
#Handle with func1
return
if otherHandler == None:
raise "Nobody handled the call!"
otherHandler.Handle(param1, param2)
So you create all your classes like a chain:
handle = HandleWithFunc1(HandleWithFunc2())
then:
handle.Handle(param1, param2)
This code is prone to refactoring, here only to illustrate the usage

Try this:
value = 1 if is_func1(param1, param2) else \
2 if is_func2(param1x, param2x) else \
... else \
20 if is_func20(param1z, param2z) else 0
abc(value)
some_list.append(value)
Bear in mind that this statement was cobbled together using various websites as a reference for Python syntax, so please don't shoot me if it doesn't compile.
The basic gist is to produce a single value that corresponds to the function called (1 for is_func1, 2 for is_func2, etc.) then use that value in the abc and some_list.append functions. Going on what I was able to read about Python boolean expression evaluation, this should properly short-circuit the evaluation so that the functions stop being called as soon as one evaluates to true.

I modified BlueRaja answer for different parameters...
function_list = {is_func01: (pa1, pa2, ...),
is_func02: (pa1, pa2, pa3, ...),
....
is_func20: (pa1, ...)}
for func, pa_list in function_list.items:
if(func(*pa_list)):
abc(pa_list_dependent_parameters)
some_list.append(pa_list_dependent_parameters)
break
I don't see why it shouldn't work.

I've not used python before, but can you refer to functions by a variable?
If so, you can create an enum with entries representing each function, test all the functions in a loop, and set a variable to the 'true' function's enum.
Then you can do a switch statement on the enum.
Still, that won't 'clean up' the code much: when you have n options and need to drive down to the correct one, you'll need n blocks of code to handle it.

I'm not sure if it would be cleaner, but I think is's quite interesting solution.
First of all you should define new function, let it be semi_func, which will call abc and some_list.append do make code DRY.
Then set new variable to act as a binary result of all boolean functions, so the is_func1 is 20th bit of it, is_func2 is 19th and so on.
32 bits of integer type should be enough to handle all 20 results.
While setting value to this result variable you should use shift left to add new functions:
result = is_func1(param1, param2) << 1
result = (result | is_func2(param1, param2)) << 1
...
result = (result | is_func20(param1, param2))
For ease access define new constants like
IS_FUNC20_TRUE = 1
IS_FUNC19_TRUE = 2
IS_FUNC18_TRUE = 4
... values should be powers of 2
And in the end use switch/sase statement to call semi_func.

I know I will be modded down for being offtopic, but still. If you find anything that can be done with standard control constructs off-putting, then you need to use a different language, such as Common Lisp, which allows for macros, in effect makes it possible to create your own control constructs. (Having recently discovered anaphoric macros, I just have to recommend this.)
This specific case would be a perfect example where a macro would help, but only assuming you are doing it at multiple places in your code, otherwise it's probably not worth improving at all. And in fact, Common Lisp already has a macro like that, it's called cond.
Anyway, in Python, I think you should go along with a list of functions and a loop.

Related

What is the purpose of using pass statement in python code? [duplicate]

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

does pass statement in python makes any sence? [duplicate]

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

Python custom function

I have been working at learning Python over the last week and it has been going really well, however I have now been introduced to custom functions and I sort of hit a wall. While I understand the basics of it, such as:
def helloworld():
print("Hello World!")
helloworld()
I know this will print "Hello World!".
However, when it comes to getting information from one function to another, I find that confusing. ie: function1 and function2 have to work together to perform a task. Also, when to use the return command.
Lastly, when I have a list or a dictionary inside of a function. I'll make something up just as an example.
def my_function():
my_dict = {"Key1":Value1,
"Key2":Value2,
"Key3":Value3,
"Key4":Value4,}
How would I access the key/value and be able to change them from outside of the function? ie: If I had a program that let you input/output player stats or a character attributes in a video game.
I understand bits and pieces of this, it just confuses me when they have different functions calling on each other.
Also, since this was my first encounter with the custom functions. Is this really ambitious to pursue and this could be the reason for all of my confusion? Since this is the most complex program I have seen yet.
Functions in python can be both, a regular procedure and a function with a return value. Actually, every Python's function will return a value, which might be None.
If a return statement is not present, then your function will be executed completely and leave normally following the code flow, yielding None as a return value.
def foo():
pass
foo() == None
>>> True
If you have a return statement inside your function. The return value will be the return value of the expression following it. For example you may have return None and you'll be explicitly returning None. You can also have return without anything else and there you'll be implicitly returning None, or, you can have return 3 and you'll be returning value 3. This may grow in complexity.
def foo():
print('hello')
return
print('world')
foo()
>>>'hello'
def add(a,b):
return a + b
add(3,4)
>>>7
If you want a dictionary (or any object) you created inside a function, just return it:
def my_function():
my_dict = {"Key1":Value1,
"Key2":Value2,
"Key3":Value3,
"Key4":Value4,}
return my_dict
d = my_function()
d['Key1']
>>> Value1
Those are the basics of function calling. There's even more. There are functions that return functions (also treated as decorators. You can even return multiple values (not really, you'll be just returning a tuple) and a lot a fun stuff :)
def two_values():
return 3,4
a,b = two_values()
print(a)
>>>3
print(b)
>>>4
Hope this helps!
The primary way to pass information between functions is with arguments and return values. Functions can't see each other's variables. You might think that after
def my_function():
my_dict = {"Key1":Value1,
"Key2":Value2,
"Key3":Value3,
"Key4":Value4,}
my_function()
my_dict would have a value that other functions would be able to see, but it turns out that's a really brittle way to design a language. Every time you call my_function, my_dict would lose its old value, even if you were still using it. Also, you'd have to know all the names used by every function in the system when picking the names to use when writing a new function, and the whole thing would rapidly become unmanageable. Python doesn't work that way; I can't think of any languages that do.
Instead, if a function needs to make information available to its caller, return the thing its caller needs to see:
def my_function():
return {"Key1":"Value1",
"Key2":"Value2",
"Key3":"Value3",
"Key4":"Value4",}
print(my_function()['Key1']) # Prints Value1
Note that a function ends when its execution hits a return statement (even if it's in the middle of a loop); you can't execute one return now, one return later, keep going, and return two things when you hit the end of the function. If you want to do that, keep a list of things you want to return and return the list when you're done.
You send information into and out of functions with arguments and return values, respectively. This function, for example:
def square(number):
"""Return the square of a number."""
return number * number
... recieves information through the number argument, and sends information back with the return ... statement. You can use it like this:
>>> x = square(7)
>>> print(x)
49
As you can see, we passed the value 7 to the function, and it returned the value 49 (which we stored in the variable x).
Now, lets say we have another function:
def halve(number):
"""Return half of a number."""
return number / 2.0
We can send information between two functions in a couple of different ways.
Use a temporary variable:
>>> tmp = square(6)
>>> halve(tmp)
18.0
use the first function directly as an argument to the second:
>>> halve(square(8))
32.0
Which of those you use will depend partly on personal taste, and partly on how complicated the thing you're trying to do is.
Even though they have the same name, the number variables inside square() and halve() are completely separate from each other, and they're invisible outside those functions:
>>> number
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'number' is not defined
So, it's actually impossible to "see" the variable my_dict in your example function. What you would normally do is something like this:
def my_function(my_dict):
# do something with my_dict
return my_dict
... and define my_dict outside the function.
(It's actually a little bit more complicated than that - dict objects are mutable (which just means they can change), so often you don't actually need to return them. However, for the time being it's probably best to get used to returning everything, just to be safe).

How can I access variables from the caller, even if it isn't an enclosing scope (i.e., implement dynamic scoping)?

Consider this example:
def outer():
s_outer = "outer\n"
def inner():
s_inner = "inner\n"
do_something()
inner()
I want the code in do_something to be able to access the variables of the calling functions further up the call stack, in this case s_outer and s_inner. More generally, I want to call it from various other functions, but always execute it in their respective context and access their respective scopes (implement dynamic scoping).
I know that in Python 3.x, the nonlocal keyword allows access to s_outer from within inner. Unfortunately, that only helps with do_something if it's defined within inner. Otherwise, inner isn't a lexically enclosing scope (similarly, neither is outer, unless do_something is defined within outer).
I figured out how to inspect stack frames with the standard library inspect, and made a small accessor that I can call from within do_something() like this:
def reach(name):
for f in inspect.stack():
if name in f[0].f_locals:
return f[0].f_locals[name]
return None
and then
def do_something():
print( reach("s_outer"), reach("s_inner") )
works just fine.
Can reach be implemented more simply? How else can I solve the problem?
There is no and, in my opinion, should be no elegant way of implementing reach since that introduces a new non-standard indirection which is really hard to comprehend, debug, test and maintain. As the Python mantra (try import this) says:
Explicit is better than implicit.
So, just pass the arguments. You-from-the-future will be really grateful to you-from-today.
What I ended up doing was
scope = locals()
and make scope accessible from do_something. That way I don't have to reach, but I can still access the dictionary of local variables of the caller. This is quite similar to building a dictionary myself and passing it on.
We can get naughtier.
This is an answer to the "Is there a more elegant/shortened way to implement the reach() function?" half of the question.
We can give better syntax for the user: instead of reach("foo"), outer.foo.
This is nicer to type, and the language itself immediately tells you if you used a name that can't be a valid variable (attribute names and variable names have the same constraints).
We can raise an error, to properly distinguish "this doesn't exist" from "this was set to None".
If we actually want to smudge those cases together, we can getattr with the default parameter, or try-except AttributeError.
We can optimize: no need to pessimistically build a list big enough for all the frames at once.
In most cases we probably won't need to go all the way to the root of the call stack.
Just because we're inappropriately reaching up stack frames, violating one of the most important rules of programming to not have things far away invisibly effecting behavior, doesn't mean we can't be civilized.
If someone is trying to use this Serious API for Real Work on a Python without stack frame inspection support, we should helpfully let them know.
import inspect
class OuterScopeGetter(object):
def __getattribute__(self, name):
frame = inspect.currentframe()
if frame is None:
raise RuntimeError('cannot inspect stack frames')
sentinel = object()
frame = frame.f_back
while frame is not None:
value = frame.f_locals.get(name, sentinel)
if value is not sentinel:
return value
frame = frame.f_back
raise AttributeError(repr(name) + ' not found in any outer scope')
outer = OuterScopeGetter()
Excellent. Now we can just do:
>>> def f():
... return outer.x
...
>>> f()
Traceback (most recent call last):
...
AttributeError: 'x' not found in any outer scope
>>>
>>> x = 1
>>> f()
1
>>> x = 2
>>> f()
2
>>>
>>> def do_something():
... print(outer.y)
... print(outer.z)
...
>>> def g():
... y = 3
... def h():
... z = 4
... do_something()
... h()
...
>>> g()
3
4
Perversion elegantly achieved.
Is there a better way to solve this problem? (Other than wrapping the respective data into dicts and pass these dicts explicitly to do_something())
Passing the dicts explicitly is a better way.
What you're proposing sounds very unconventional. When code increases in size, you have to break down the code into a modular architecture, with clean APIs between modules. It also has to be something that is easy to comprehend, easy to explain, and easy to hand over to another programmer to modify/improve/debug it. What you're proposing sounds like it is not a clean API, unconventional, with a non-obvious data flow. I suspect it would probably make many programmers grumpy when they saw it. :)
Another option would be to make the functions members of a class, with the data being in the class instance. That could work well if your problem can be modelled as several functions operating on the data object.

How to use "pass" statement?

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

Categories

Resources