DEV Community

Cover image for Functions are first class objects
icncsx
icncsx

Posted on

2 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay