DEV Community

Cover image for Functions are first class objects
icncsx
icncsx

Posted on

Functions are first class objects

By functions being first-class objects, we mean that we can:

  • assign functions to variables
  • store functions in data structures
  • pass functions as arguments to other functions
  • return functions as values from other functions.

Assignment

def yell(text):
    return text.upper() + '!'

bark = yell
bark('woof')
Enter fullscreen mode Exit fullscreen mode

Functions can be stored in data structures

funcs = [str.lower, str.capitalize]

for f in funcs:
    print(f('hey there'))
Enter fullscreen mode Exit fullscreen mode

Functions can be passed to other functions

def yell(text):
    return text.upper() + '!'

map(yell, ['hello', 'hey', 'hi'])
Enter fullscreen mode Exit fullscreen mode

Functions can be returned from other functions

def talk(volume):
    def whisper(text):
        return text.lower() + '...'
    def yell(text):
        return text.upper() + '!'

    if volume > 0.5:
        return yell
    else:
        return whisper

talk(0.8)("hello")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)