Partial Functions in Python

Level 5217 keystrokes

This uses partial to create specialized functions with preset arguments. Partial application fixes some arguments, creating a new function.

Python code

# Import partial from functools module
1from functools import partial
2
# Define a general power function with two parameters
3def power(base, exponent):
# Calculate base raised to exponent
4 return base ** exponent
5
# Create a square function by fixing exponent=2
# square(x) is equivalent to power(x, exponent=2)
6square = partial(power, exponent=2)
# Create a cube function by fixing exponent=3
7cube = partial(power, exponent=3)
8
# Use the specialized functions - only need to provide base
9print(f"square(5) = {square(5)}")
10print(f"cube(5) = {cube(5)}")

Output

square(5) = 25
cube(5) = 125
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 9
  • )× 9
  • =× 6
  • "× 4
  • ,× 3
  • {× 2
  • }× 2
  • *× 2
  • :× 1

More Python examples at level 5

← Python typing practice