DEV Community

Lody G Mtui
Lody G Mtui

Posted on • Edited on

2 1

First-Class Function in Python

Everything in Python is an Object (You heard it here first). Just kidding! Of course, at it's core everything in Python is an object.

Not all languages have this feature, but Python is one of them, together with JavaScript, Ruby etc.
This means, string, int, float, datatypes such as dictionary, list, tuple etc. are all objects.

Object is an entity with attributes and behavior. So, function in Python is treated as object. That's why you can call them as First-class function.

First-Class Function means that functions are treated as values - that you can assign a function into a variable, pass it around etc.

Properties of First-Class Function

  • you can assign them as variable.
  • you can pass them to other functions as arguments.
  • you can return them from other functions as values.
  • you can store them in data structures.

Lets dive into code examples for each property

1.Assigning function as variable.

def square(num):
    return num*num

# store the function in a variable
result = square
print(result2(3))
Enter fullscreen mode Exit fullscreen mode

2.Pass the function as a parameter to another function.

def morning():
    return "good morning"

def noon():
    return "good afternoon"

def greetings(function):
    greet = function()
    print(greet)

greetings(morning)
greetings(noon)
Enter fullscreen mode Exit fullscreen mode

3.Return function from other functions as values.

def outer_power(num1):
    def inner_power(num2):
        return num1 ** num2
    return inner_power

power = outer_power(4)
print(power(3))

Enter fullscreen mode Exit fullscreen mode

4.Store function in data structures

def plusOne(num):
    return num + 1

def plusTwo(num):
    return num + 2

def plusThree(num):
    return num + 3

list_function = [plusOne,plusTwo,plusThree]

for i in list_function:
    print(i)

print(plusOne)
print(plusTwo)
print(plusThree)
Enter fullscreen mode Exit fullscreen mode

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay