Articles

Python Partial Functions Using Functools

by Azhar Uddin Technical Architect

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 the 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.

Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!

Though Python is not a functional language, 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.

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.

  • The new version of a function documents itself.

Sponsor Ads


About Azhar Uddin Advanced   Technical Architect

42 connections, 1 recommendations, 209 honor points.
Joined APSense since, May 12th, 2017, From Hyderabad, India.

Created on Jul 30th 2018 06:34. Viewed 164 times.

Comments

No comment, be the first to comment.
Please sign in before you comment.