Related
I have multiple class instances that call each other's functions. I also have a system that detects if these functions call each other for too long (to avoid stack overflow). However, when it detects that, there's nothing it can do to actually stop them, so they just keep running until they reach recursion limit. Here's a simpler example:
class test:
def activateOther(self, other):
sleep(2)
print('Activated Other Function', id(self))
other.activateOther(self)
t = test()
t_ = test()
t.activateOther(t_)
del t, t_ # Even after deleting the variables/references, they continue running
Is there a way to actually stop these functions from running endlessly and hitting the recursion limit? If not, I suppose I'll try to add a variable to each class indicating whether they should continue running or not.
Indeed, this is a typical recursion issue. There must be a condition in the code for when the recursion is stopped. The easiest is to introduce a depth parameter:
class test:
def activateOther(self, other, depth=0):
if depth > 88:
return
sleep(2)
print('Activated Other Function', id(self))
other.activateOther(self, depth + 1)
t = test()
t_ = test()
t.activateOther(t_)
The actual condition, and whether the depth counter will do, depends of course on your application.
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
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
I have an automation test, which uses function that creates screenshots to a folder. This function is called by multiple screenshot instances. On every test run, a new folder is created, so I don't care about counter reset. In order to reflect the order at which these screenshots are taken, I had to come up with names that could be sorted by order. This is my solution:
def make_screenshot_file(file_name):
order = Counter().count
test_suites_path = _make_job_directory()
return make_writable_file(os.path.join(test_suites_path,'screenshot',file_name % order))
class Counter():
__counter_instance = None
def __init__(self):
if Counter.__counter_instance is None:
self.count = 1
Counter.__counter_instance = self
else:
Counter.__counter_instance.count += 1
self.count = Counter.__counter_instance.count
It works fine for me. But I keep thinking that there should be an easier way to solve this problem. Is there? And if singleton is the only way, could my code be optimized in any way?
What you're trying to do here is simulate a global variable.
There is no good reason to do that. If you really want a global variable, make it explicitly a global variable.
You could create a simple Counter class that increments count by 1 each time you access it, and then create a global instance of it. But the standard library already gives you something like that for free, in itertools.count, as DSM explains in a comment.
So:
import itertools
_counter = itertools.count()
def make_screenshot_file(file_name):
order = next(_counter)
test_suites_path = _make_job_directory()
return make_writable_file(os.path.join(test_suites_path,'screenshot',file_name % order))
I'm not sure why you're so worried about how much storage or time this takes up, because I can't conceive of any program where it could possibly matter whether you were using 8 bytes or 800 for a single object you could never have more than one or, or whether it took 3ns or 3us to access it when you only do so a handful of times.
But if you are worried, as you can see from the source, count is implemented in C, it's pretty memory-efficient, and if you don't do anything fancy with it, it comes down to basically a single PyNumber_Add to generate each number, which is a lot less than interpreting a few lines of code.
Since you asked, here's how you could radically simplify your existing code by using a _count class attribute instead of a __counter_instance class attribute:
class Counter():
_count = 0
def count(self):
Counter._count += 1
return Counter.count
Of course now you have to to Counter().count() instead of just Counter().count—but you can fix that trivially with #property if it matters.
It's worth pointing out that it's a really bad idea to use a classic class instead of a new-style class (by passing nothing inside the parens), and if you do want a classic class you should leave the parens off, and most Python programmers will associate the name Counter with the class collections.Counter, and there's no reason count couldn't be a #classmethod or #staticmethod… at which point this is exactly Andrew T.'s answer. Which, as he points out, is much simpler than what you're doing, and no more or less Pythonic.
But really, all of this is no better than just making _count a module-level global and adding a module-level count() function that increments and returns it.
why not just do
order = time.time()
or do something like
import glob #glob is used for unix like path expansion
order = len(glob.glob(os.path.join(test_suites_path,"screenshot","%s*"%filename))
Using static methods and variables. Not very pythonic, but simpler.
def make_screenshot_file(file_name):
order = Counter.count() #Note the move of the parens
test_suites_path = _make_job_directory()
return make_writable_file(os.path.join(test_suites_path,'screenshot',file_name % order))
class Counter():
count_n = 0
#staticmethod
def count():
Counter.count_n += 1
return Counter.count_n
print Counter.count()
print Counter.count()
print Counter.count()
print Counter.count()
print Counter.count()
atarzwell#freeman:~/src$ python so.py
1
2
3
4
5
Well , you can use this solution, just make sure you never initialize the order kwarg!
Mutable Kwargs in function's work like classes global variables. And the value isn't reset to default between calls, as you might think at first!
def make_screenshot_file(file_name , order=[0]):
order[0] = order[0] + 1
test_suites_path = _make_job_directory()
return make_writable_file(os.path.join(test_suites_path,'screenshot',file_name % order[0]))
At the moment, I'm doing stuff like the following, which is getting tedious:
run_once = 0
while 1:
if run_once == 0:
myFunction()
run_once = 1:
I'm guessing there is some more accepted way of handling this stuff?
What I'm looking for is having a function execute once, on demand. For example, at the press of a certain button. It is an interactive app which has a lot of user controlled switches. Having a junk variable for every switch, just for keeping track of whether it has been run or not, seemed kind of inefficient.
I would use a decorator on the function to handle keeping track of how many times it runs.
def run_once(f):
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return f(*args, **kwargs)
wrapper.has_run = False
return wrapper
#run_once
def my_function(foo, bar):
return foo+bar
Now my_function will only run once. Other calls to it will return None. Just add an else clause to the if if you want it to return something else. From your example, it doesn't need to return anything ever.
If you don't control the creation of the function, or the function needs to be used normally in other contexts, you can just apply the decorator manually as well.
action = run_once(my_function)
while 1:
if predicate:
action()
This will leave my_function available for other uses.
Finally, if you need to only run it once twice, then you can just do
action = run_once(my_function)
action() # run once the first time
action.has_run = False
action() # run once the second time
Another option is to set the func_code code object for your function to be a code object for a function that does nothing. This should be done at the end of your function body.
For example:
def run_once():
# Code for something you only want to execute once
run_once.func_code = (lambda:None).func_code
Here run_once.func_code = (lambda:None).func_code replaces your function's executable code with the code for lambda:None, so all subsequent calls to run_once() will do nothing.
This technique is less flexible than the decorator approach suggested in the accepted answer, but may be more concise if you only have one function you want to run once.
Run the function before the loop. Example:
myFunction()
while True:
# all the other code being executed in your loop
This is the obvious solution. If there's more than meets the eye, the solution may be a bit more complicated.
I'm assuming this is an action that you want to be performed at most one time, if some conditions are met. Since you won't always perform the action, you can't do it unconditionally outside the loop. Something like lazily retrieving some data (and caching it) if you get a request, but not retrieving it otherwise.
def do_something():
[x() for x in expensive_operations]
global action
action = lambda : None
action = do_something
while True:
# some sort of complex logic...
if foo:
action()
There are many ways to do what you want; however, do note that it is quite possible that —as described in the question— you don't have to call the function inside the loop.
If you insist in having the function call inside the loop, you can also do:
needs_to_run= expensive_function
while 1:
…
if needs_to_run: needs_to_run(); needs_to_run= None
…
I've thought of another—slightly unusual, but very effective—way to do this that doesn't require decorator functions or classes. Instead it just uses a mutable keyword argument, which ought to work in most versions of Python. Most of the time these are something to be avoided since normally you wouldn't want a default argument value to change from call-to-call—but that ability can be leveraged in this case and used as a cheap storage mechanism. Here's how that would work:
def my_function1(_has_run=[]):
if _has_run: return
print("my_function1 doing stuff")
_has_run.append(1)
def my_function2(_has_run=[]):
if _has_run: return
print("my_function2 doing some other stuff")
_has_run.append(1)
for i in range(10):
my_function1()
my_function2()
print('----')
my_function1(_has_run=[]) # Force it to run.
Output:
my_function1 doing stuff
my_function2 doing some other stuff
----
my_function1 doing stuff
This could be simplified a little further by doing what #gnibbler suggested in his answer and using an iterator (which were introduced in Python 2.2):
from itertools import count
def my_function3(_count=count()):
if next(_count): return
print("my_function3 doing something")
for i in range(10):
my_function3()
print('----')
my_function3(_count=count()) # Force it to run.
Output:
my_function3 doing something
----
my_function3 doing something
Here's an answer that doesn't involve reassignment of functions, yet still prevents the need for that ugly "is first" check.
__missing__ is supported by Python 2.5 and above.
def do_once_varname1():
print 'performing varname1'
return 'only done once for varname1'
def do_once_varname2():
print 'performing varname2'
return 'only done once for varname2'
class cdict(dict):
def __missing__(self,key):
val=self['do_once_'+key]()
self[key]=val
return val
cache_dict=cdict(do_once_varname1=do_once_varname1,do_once_varname2=do_once_varname2)
if __name__=='__main__':
print cache_dict['varname1'] # causes 2 prints
print cache_dict['varname2'] # causes 2 prints
print cache_dict['varname1'] # just 1 print
print cache_dict['varname2'] # just 1 print
Output:
performing varname1
only done once for varname1
performing varname2
only done once for varname2
only done once for varname1
only done once for varname2
One object-oriented approach and make your function a class, aka as a "functor", whose instances automatically keep track of whether they've been run or not when each instance is created.
Since your updated question indicates you may need many of them, I've updated my answer to deal with that by using a class factory pattern. This is a bit unusual, and it may have been down-voted for that reason (although we'll never know for sure because they never left a comment). It could also be done with a metaclass, but it's not much simpler.
def RunOnceFactory():
class RunOnceBase(object): # abstract base class
_shared_state = {} # shared state of all instances (borg pattern)
has_run = False
def __init__(self, *args, **kwargs):
self.__dict__ = self._shared_state
if not self.has_run:
self.stuff_done_once(*args, **kwargs)
self.has_run = True
return RunOnceBase
if __name__ == '__main__':
class MyFunction1(RunOnceFactory()):
def stuff_done_once(self, *args, **kwargs):
print("MyFunction1.stuff_done_once() called")
class MyFunction2(RunOnceFactory()):
def stuff_done_once(self, *args, **kwargs):
print("MyFunction2.stuff_done_once() called")
for _ in range(10):
MyFunction1() # will only call its stuff_done_once() method once
MyFunction2() # ditto
Output:
MyFunction1.stuff_done_once() called
MyFunction2.stuff_done_once() called
Note: You could make a function/class able to do stuff again by adding a reset() method to its subclass that reset the shared has_run attribute. It's also possible to pass regular and keyword arguments to the stuff_done_once() method when the functor is created and the method is called, if desired.
And, yes, it would be applicable given the information you added to your question.
Assuming there is some reason why myFunction() can't be called before the loop
from itertools import count
for i in count():
if i==0:
myFunction()
Here's an explicit way to code this up, where the state of which functions have been called is kept locally (so global state is avoided). I don't much like the non-explicit forms suggested in other answers: it's too surprising to see f() and for this not to mean that f() gets called.
This works by using dict.pop which looks up a key in a dict, removes the key from the dict, and takes a default value to use in case the key isn't found.
def do_nothing(*args, *kwargs):
pass
# A list of all the functions you want to run just once.
actions = [
my_function,
other_function
]
actions = dict((action, action) for action in actions)
while True:
if some_condition:
actions.pop(my_function, do_nothing)()
if some_other_condition:
actions.pop(other_function, do_nothing)()
I use cached_property decorator from functools to run just once and save the value. Example from the official documentation https://docs.python.org/3/library/functools.html
class DataSet:
def __init__(self, sequence_of_numbers):
self._data = tuple(sequence_of_numbers)
#cached_property
def stdev(self):
return statistics.stdev(self._data)
You can also use one of the standard library functools.lru_cache or functools.cache decorators in front of the function:
from functools import lru_cache
#lru_cache
def expensive_function():
return None
https://docs.python.org/3/library/functools.html
If I understand the updated question correctly, something like this should work
def function1():
print "function1 called"
def function2():
print "function2 called"
def function3():
print "function3 called"
called_functions = set()
while True:
n = raw_input("choose a function: 1,2 or 3 ")
func = {"1": function1,
"2": function2,
"3": function3}.get(n)
if func in called_functions:
print "That function has already been called"
else:
called_functions.add(func)
func()
You have all those 'junk variables' outside of your mainline while True loop. To make the code easier to read those variables can be brought inside the loop, right next to where they are used. You can also set up a variable naming convention for these program control switches. So for example:
# # _already_done checkpoint logic
try:
ran_this_user_request_already_done
except:
this_user_request()
ran_this_user_request_already_done = 1
Note that on the first execution of this code the variable ran_this_user_request_already_done is not defined until after this_user_request() is called.
A simple function you can reuse in many places in your code (based on the other answers here):
def firstrun(keyword, _keys=[]):
"""Returns True only the first time it's called with each keyword."""
if keyword in _keys:
return False
else:
_keys.append(keyword)
return True
or equivalently (if you like to rely on other libraries):
from collections import defaultdict
from itertools import count
def firstrun(keyword, _keys=defaultdict(count)):
"""Returns True only the first time it's called with each keyword."""
return not _keys[keyword].next()
Sample usage:
for i in range(20):
if firstrun('house'):
build_house() # runs only once
if firstrun(42): # True
print 'This will print.'
if firstrun(42): # False
print 'This will never print.'
I've taken a more flexible approach inspired by functools.partial function:
DO_ONCE_MEMORY = []
def do_once(id, func, *args, **kwargs):
if id not in DO_ONCE_MEMORY:
DO_ONCE_MEMORY.append(id)
return func(*args, **kwargs)
else:
return None
With this approach you are able to have more complex and explicit interactions:
do_once('foobar', print, "first try")
do_once('foo', print, "first try")
do_once('bar', print, "second try")
# first try
# second try
The exciting part about this approach it can be used anywhere and does not require factories - it's just a small memory tracker.
Depending on the situation, an alternative to the decorator could be the following:
from itertools import chain, repeat
func_iter = chain((myFunction,), repeat(lambda *args, **kwds: None))
while True:
next(func_iter)()
The idea is based on iterators, which yield the function once (or using repeat(muFunction, n) n-times), and then endlessly the lambda doing nothing.
The main advantage is that you don't need a decorator which sometimes complicates things, here everything happens in a single (to my mind) readable line. The disadvantage is that you have an ugly next in your code.
Performance wise there seems to be not much of a difference, on my machine both approaches have an overhead of around 130 ns.
If the condition check needs to happen only once you are in the loop, having a flag signaling that you have already run the function helps. In this case you used a counter, a boolean variable would work just as fine.
signal = False
count = 0
def callme():
print "I am being called"
while count < 2:
if signal == False :
callme()
signal = True
count +=1
I'm not sure that I understood your problem, but I think you can divide loop. On the part of the function and the part without it and save the two loops.