Reputation: 391
Why do upper
in df.apply(df.str.upper)
doesn't require a parenthesis, but upper()
method requires them as in df.str.upper()
?
Is there some concept I've miss?
Upvotes: 3
Views: 1148
Reputation: 41625
The ()
means "call this function now".
print(str.upper())
Referring to a function without the ()
does not call the function immediately.
map(str.upper)
The str.upper
function is passed to the map
function. The map
function can now decide what it does with the str.upper
function. It might call it once, or multiple times, or store it somewhere for later use.
Upvotes: 4
Reputation: 546
In Python everything is an object. A function without parentheses is not evaluated and is treated as an object. A function with parentheses is immediately evaluated.
For example:
>>> def return_one():
... return 1
...
>>> return_one # return the object reference, do not evaluate
<function return_one at 0x7fb76d3f4bf8>
>>> return_one() # evaluate the function
1
With this in mind, the .apply
method takes a function object and then calls it at a later point in time. If you were to write .apply(str.upper())
, str.upper()
would evaluate to a str
instead of a func
object.
Upvotes: 0
Reputation: 2546
When you use .apply(function_name)
, the internals treats function_name as a reference to the function that has been applied. Hence, only the function name is passed and that too without parentheses.
When it is applied to the entity, it will be accessed from the function_name
.
Its just like passing a function as an argument to another function.
Example:
def fun(x):
return x*x
def fun_b(function):
return function(3)
print(fun_b(fun))
Upvotes: 1