Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Factory Function

Tags:

python

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 and i think it's really neat but I cant seem to envision when I could use this approach.

I could have easily implement the above by having maker() take both N and X as an argument instead.

Has anyone use this type of factory function and explain to me why you went this approach instead of just taking multiple arguments?

Is it just user preference?

like image 564
ealeon Avatar asked May 26 '26 19:05

ealeon


1 Answers

squarer = maker(2)

print(squarer(2)) # outputs 4
print(squarer(4)) # outputs 16
print(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.

like image 101
Tim Tisdall Avatar answered May 28 '26 09:05

Tim Tisdall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!