Skip to content Skip to sidebar Skip to footer

Python Factory Function

Same example from the same book: Python deep nesting factory functions def maker(N): def action(X): return X ** N return action I understand the concept behind it

Solution 1:

squarer = maker(2)

print(squarer(2)) # outputs 4print(squarer(4)) # outputs 16print(squarer(8)) # outputs 64

Essentially, it means you only have to enter in the N value once and then you can't change it later.

I think it's mostly programming style as there are multiple ways of doing the same thing. However, this way you can only enter the N value once so you could add code to test that it's a valid value once instead of checking each time you called the function.

EDIT just thought of a possible example (though it's usually handled by using a class):

writer = connectmaker("127.0.0.1")
writer("send this text")
writer("send this other text")

The "maker" method would then connect to the address once and then maintain that value for each call to writer(). But as I said, something like this is usually a class where the __init__ would store the values.

Solution 2:

In a certain way, you can see some of the operator function as these as well.

For example, operator.itemgetter() works this way:

importoperator
get1 = operator.itemgetter(1) # creates a function which gets the item #1 of the given objectget1([5,4,3,2,1]) # gives 4

This is often used e. g. as a key= function of sorting functions and such.

Similiar, more dedicated use cases are easily imaginable if you have a concrete problem which you can solve with that.

In the same league you have these "decorator creators":

defindirect_deco(outer_param):
    defreal_deco(func):
        defwrapper(*a, **k):
            return func(outer_param, *a, **k)
        return wrapper
    return real_deco

@indirect_deco(1)deffunction(a, b, c):
    print (((a, b, c))

function(234, 432)

Here as well, the outer function is a factory function which creates the "real deco" function. This, in turn, even creates another oner which replaces the originally given one.

Post a Comment for "Python Factory Function"