
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Partial Functions in Python?
Everybody loves to write reusable code, right? Then partial function is a cool thing to learn. Partial functions allows us to derive a function with x parameters to a function with fewer parameters and constant values set for the more limited function.
We can write partial functional application in python through functools library. Below is a simple example of partial function from the functools library with the add function from the operator library.
>>> from functools import * >>> from operator import * >>> add(1,2) 3 >>> add1 = partial(add, 4) >>> add1(6) 10 >>> add1(10) 14
Partial is a higher order function which takes a function as input (like map and filter) but it also returns a function that can be used in the same way as any other function in your program.
>>> list(map (add1, [1, 2, 3, 4, 5])) [5, 6, 7, 8, 9] >>> seven = partial(add1, 3) >>> seven() 7
We can also use partial on object methods, for e.g. to generate a list of default strings −
>>> str1 = "Hello, Python" >>> helloStr = partial(str1.replace, "Python") >>> helloStr("Tutorialspoint") 'Hello, Tutorialspoint' >>> helloStr("Java") 'Hello, Java'
Partial function application is a very useful tools especially where you need to apply a range of different input to a single object or need to bind one of the arguments to a function to be constant.
Python function helps you to write your code easily and easier to maintain.
- Related Articles
- What are Partial functions in JavaScript?
- How to take partial screenshot with Selenium WebDriver in python?
- Mathematical Functions in Python - Special Functions and Constants
- Decimal Functions in Python
- Operator Functions in Python
- Time Functions in Python?
- Mathematical Functions in Python?
- Log functions in Python
- Iterator Functions in Python
- Trigonometric Functions in Python
- Statistical Functions in Python
- Partial Dependency in DBMS
- Terminal Control Functions in Python
- First Class functions in Python
- Mathematical statistics functions in Python
