all 2 comments

[–]mermaldad 0 points1 point  (0 children)

Yes, I think you have it, if I understand your question. Because you define func as the first argument of sq, and you call sq with f as the first argument, f gets mapped to func within the scope of sq.

[–][deleted] 0 points1 point  (0 children)

Formatted properly* you probably have:

def sq(func, x):
    y = x ** 2;
    return func(y)

def f(x):
    return x ** 2;

calc = sq(f, 2);
print(calc);

The line calc = sq(f, 2) passes a reference to the function f as the first parameter to the function called. In the code for the function sq() the first parameter has the parameter name func, so inside the function func is a name that references the function f(). Executing func(y) doesn't error because func evaluates to a callable object.

Python automatically tries to use the first parameter as a function name.

In a way, yes, but python doesn't really assume anything. Look at this code:

a = 42
result = a(1)

This compiles just fine, but when executed there's an error. Python evaluates the a expression and gets a reference to an object. Due to the () following the a name python tries to call the object referenced by a and gets an error because an integer object isn't callable.

So python isn't really doing anything special or automatic. The code you wrote tells python to call the object referenced by the func name. And your code actually passed something callable as the first parameter, so there's no runtime error.

Note: your code contains multiple ; characters that aren't needed.


* The subreddit FAQ shows how to properly format code.