python functions and callables

Python is a good, strong Object Oriented Programming language and it was never designed to be a functional programming language. You can read a bit about the history here.

Having said that, Python does have certain useful functional programming features which we discuss below.

Function as first class citizens

All functions in python are in fact objects and you can do whatever you do normally with objects. Like passing them around. Functions can be passed as parameters into other functions and they can also be returned as return values.

>>> def some_function():
...    print "do something"

>>> def some_other_function(f):
...    # do something else with f
...    f()

>>> print some_other_function(some_function)

If we inspect the type of some_function, it shows that its an object of class ‘function

>>> print type(some_function)
<class 'function'>

So, functions are just objects.

Then, can we make our other objects behave like function? i.e., can we call our objects like function?

# create an instance (object) of class Fruit
>>> apple = Fruit()
# can we then call apple like a function?
>>> apple()

Yes, we can. Python interprets an object as a function if the class implements the method “__call__

>>> class Fruit:
...    def __call__(self):
...        # do something
...        print 'doing something'
>>> apple = Fruit()
# we can now call apple like a function
>>> apple()

doing something

Objects of Classes that implement the __call__ method are called “Callables“.

Callables are very interesting and we use them in the metaprogramming concept of Decorators, which we’ll cover in a future post.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.