Mindmajix

Python partial functions using functools

Despite being a fully object oriented language and not an inherently functional language, Python has its unique set of functional programming tools. Partial functions in Python can be created in style with the help of functools library. Partial functions allow one to derive a function with x parameters to a function with fewer parameters and fixed values set for the more limited function.

The functools module is for higher-order functions: functions that act on or return other functions. This module provides tools for working with functions and other callable objects, to adapt or extend them for new purposes without completely rewriting them.In general, any callable object can be treated as a function for the purposes of this module.

Though Python is not a functional language, but this particular field helps coders to write their own code in a functional style and one such feature of functools library is to create partial functions. In other words functools module is for higher order functions where functions can either act or return on other functions. In order to use partial functions the following import is required:

>>> from functools import partial

Partial function helps you to derive a function with x parameters to a function with fewer parameters. In a partial function, one constant value argument can be bound to a definite function to create a new function that will take only the rest of the operations. Amongst all calls, the bound input will remain the same. To understand its application in detail, have a glimpse at the following example:

Screenshot_49

Partial Functions:

The primary tool supplied by the functools module is the class partial, which can be used to “wrap” a callable object with default arguments. Partial objects are similar to function objects with slight differences. Partial function application makes it easier to write and maintain the code.

What functools.partial does is:

  • Makes a new version of a function with one or more arguments already filled in.
  • New version of a function documents itself.

Now, have a look at another example of how to find a cube of a number with the help of partial functions:

Screenshot_50

https://docs.python.org/2/library/functools.html

 

            Enroll for Instructor Led Live Python Training


0 Responses on Python partial functions using functools"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.