Terrence Brannon
Terrence Brannon

Reputation: 4968

What does the Python function keyword do?

I was looking at this line of code -

    result = function(self, *args, **kwargs)

And I was not able to find a definition of the function keyword for Python. Could someone link me to the docs and/or explain that this line of code does? I intuitively think I know, but I don't understand why I can't find any docs on it.

In searching through http://docs.python.org both the new module and its successor types seem to have something to do with it.

Upvotes: 3

Views: 6148

Answers (4)

Darrick Herwehe
Darrick Herwehe

Reputation: 3722

That's because function is not a python keyword.

If you expand your view just a little, you can see that function is a variable (passed in as a parameter).

def autoAddScript(function):
    """
        Returns a decorator function that will automatically add it's result to the element's script container.
    """
    def autoAdd(self, *args, **kwargs):
        result = function(self, *args, **kwargs)
        if isinstance(result, ClientSide.Script):
            self(result)
            return result
        else:
            return ClientSide.Script(ClientSide.var(result))
    return autoAdd

Upvotes: 9

James Sapam
James Sapam

Reputation: 16940

First of all function is first class object in python, which means you can bind to another name like fun = func() or you can pass a function to another function as an argument.

So, lets start with a small snippet :

# I ve a function to upper case argument : arg
def foo(arg):
    return arg.upper()

# another function which received argument as function, 
# and return another function.
# func is same as function in your case, which is just a argument name.

def outer_function(func):
    def inside_function(some_argument):
        return func(some_argument)
    return inside_function

test_string = 'Tim_cook'

# calling the outer_function with argument `foo` i.e function to upper case string,
# which will return the inner_function.

var = outer_function(foo)
print var  # output is : <function inside_function at 0x102320a28>

# lets see where the return function stores inside var. It is store inside 
# a function attribute called func_closure.

print var.func_closure[0].cell_contents # output: <function foo at 0x1047cecf8>

# call var with string test_string
print var(test_string) # output is : TIM_COOK

Upvotes: 2

Xavier Combelle
Xavier Combelle

Reputation: 11195

function is just a variable which happen to be a function maybe with a short example it would be clearer:

def add(a,b):
    return a+b

def run(function):
    print(function(3,4))

>>> run(add)
7

Upvotes: 3

Gabe
Gabe

Reputation: 86718

In this case function is just a formal parameter to the autoAddScript function. It is a local variable expected to have a type that allows you to call it like a function.

Upvotes: 4

Related Questions