python - How to use "pass" statement? - Stack Overflow
How do I pass a method as a parameter in Python - Stack Overflow
Pass a function into another function as an argument, with some but not all of the arguments?
Python - Passing a function into another function - Stack Overflow
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 fromxml):try: self.version = "Expat %d.%d.%d" % expat.version_info except AttributeError: pass # unknownNote: 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.KeyboardInterruptorSystemExit(or evenHardwareIsOnFireError– 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: passInstead using at least
except Error:or in this case preferablyexcept OSError:is considered much better practice. A quick analysis of all Python modules I have installed gave me that more than 10% of allexcept ...: passstatements 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): passSimilarly, 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): passTesting 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)): passIn 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
passin addition to the docstring in order to say “This is indeed intended to do nothing.”, for example inpebl:class ParsingError(Exception): """Error encountered while parsing an ill-formed datafile.""" passIn some cases,
passis 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 theEllipsisliteral...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): passbefore
def time_step(agents): for agent in agents: update_agent(agent)as a reminder to fill in the
update_agentfunction 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 israise 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”)
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self parameter).
To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
obj.method2(obj.method1)
Note: I believe a __call__() method does exist, i.e. you could technically do methodToRun.__call__(), but you probably should never do so explicitly. __call__() is meant to be implemented, not to be invoked from your own code.
If you wanted method1 to be called with arguments, then things get a little bit more complicated. method2 has to be written with a bit of information about how to pass arguments to method1, and it needs to get values for those arguments from somewhere. For instance, if method1 is supposed to take one argument:
def method1(self, spam):
return 'hello ' + str(spam)
then you could write method2 to call it with one argument that gets passed in:
def method2(self, methodToRun, spam_value):
return methodToRun(spam_value)
or with an argument that it computes itself:
def method2(self, methodToRun):
spam_value = compute_some_value()
return methodToRun(spam_value)
You can expand this to other combinations of values passed in and values computed, like
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham_value)
or even with keyword arguments
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham=ham_value)
If you don't know, when writing method2, what arguments methodToRun is going to take, you can also use argument unpacking to call it in a generic way:
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, positional_arguments, keyword_arguments):
return methodToRun(*positional_arguments, **keyword_arguments)
obj.method2(obj.method1, ['spam'], {'ham': 'ham'})
In this case positional_arguments needs to be a list or tuple or similar, and keyword_arguments is a dict or similar. In method2 you can modify positional_arguments and keyword_arguments (e.g. to add or remove certain arguments or change the values) before you call method1.
Yes it is possible. Just call it:
class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
Hello, I am new to python, and am trying to learn as I go for my machine learning class. In order to make some of my assignment work, I need to be able to pass a function in as an argument to another function, but have some of the arguments already filled out.
So for example, let’s say I wanted to pass the function “foo” to use in a function “bar”. Lets assume that foo takes the arguments a, b, and c. I could write
bar(foo)
but in order to call foo, I would need a, b and c in bar.
alternatively, I could write
bar(foo(a, b, c))
but this is going to pass in as a value, and I need all 3 values.
Let’s say I have a and b to pass in, but c is calculated within bar. Is there a way to do this so I can give bar a and b, but not c?
edit: I figured it out! He just wanted me to create a lambda function that passes the arguments into the function, and then pass that lambda as the argument.
Just pass it in like any other parameter:
def a(x):
return "a(%s)" % (x,)
def b(f,x):
return f(x)
print b(a,10)
Treat function as variable in your program so you can just pass them to other functions easily:
def test ():
print "test was invoked"
def invoker(func):
func()
invoker(test) # prints test was invoked