Passing a function as a parameter - BeautifulSoup
The BeautifulSoup documentation defines the following function:
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
And then passed as a parameter to the function find_all()
::
soup.find_all(has_class_but_no_id)
What surprises me is that it worked. I don't really know how this mechanism works, how does this function ( has_class_but_no_id
) return a value for a function find_all()
without using a parameter?
source to share
has_class_but_no_id
is not executed when you pass it to find_all()
.
find_all
makes the call has_class_but_no_id
, multiple times, passing it to tags as the "tag" value at that time. This is a pattern that takes advantage of the fact that in Python, functions are what are known as first-order objects - they exist as objects, and you can pass them in variables.
This allows functions to accept other functions and run them later, just like BeautifulSoup does.
Try the experiment:
def say_something(something_to_say):
print something_to_say
def call_another_function(func, argument):
func(argument)
call_another_function(say_something, "hi there")
The above answer is taken from this Reddit post .
Also, see the source code for find_all and call .
source to share