Silly Techy

Search
Close this search box.

Python Functions

What are functions in python?

Functions in python or, in general, functions are a group of code bundled together which perform particular tasks or operations. We can reuse this group of codes elsewhere in the program. Functions bring modularity to your code.
A general python function structure is given here:

Python functions structure

A function in python is written by the keyword def first followed by the function name then with an open and close parenthesis, where we mention our positional and keyword parameters then followed by the full colon. We have a return keyword that returns the final output of the function. This is a function definition.

To call a python function we simply use the function name and pass the required number of parameters defined by the function.

Let’s look at an actual code snippet

				
					def addition(a:int=20,b:int=30)->int:
""" Function to add two integers"""
    return a + b
				
			

The function name is addition (always name functions that make sense or speak its purpose). We have two parameters here a and b which has some default values. The full colon and the type mentioned, also the arrow key is python annotations. If you do not understand python annotations you can click here. I have a tutorial for that. Then we have the docstring of the function and finally, we are returning the python expression.

To call this function:

				
					# since we have default parameters we are not passing any arguments
addition()
				
			

output:

				
					50
				
			

What is dir in python?

Now we want to see what are the attributes and other methods of a class or functions. We can use a built-in function called dirand pass in the class or function.

So let’s take our example function and see what it gives us as output.

				
					dir(addition)
				
			

output:

				
					['__annotations__',
 '__call__',
 '__class__',
 '__closure__',
 '__code__',
 '__defaults__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__get__',
 '__getattribute__',
 '__globals__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__kwdefaults__',
 '__le__',
 '__lt__',
 '__module__',
 '__name__',
 '__ne__',
 '__new__',
 '__qualname__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']
				
			

Let’s discuss some of the magic methods for functions (the special methods that start and end with the double underscores).

__name__ : Gives the name of the function

				
					>>> addition.__name__
'addition'
				
			

__defaults__ : Gives the default values of the parameters in a tuple format.

				
					>>> addition.__defaults__
(20, 30)
				
			

__annotations__ : Gives the type hints values of the parameters also the return type in a dictionary format.

				
					>>> addition.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
				
			

__doc__ : Gives the doc string of the function in a string format.

				
					>>> addition.__doc__
' Function to add two integers'
				
			

__sizeof__ : Gives the internal size for a particular object (in bytes) occupying the memory.

				
					>>> addition.__sizeof__()
120

				
			

What is the difference between a function and a method?

Classes and objects have attributes that are bound to the class. An attribute that is callable is called method.

Unlike a method, the function is not bound to a class object.

We will use the inspect library to help us understand which is a function and which is a method. Let’s take an example to understand it better.

We have defined a arithmtic class, with a method addition. Using  self we are bounding this to the class object. We also have addition function defined separately.

Using the isfunction which returns TRUE if the passed object is actually a function and FALSE otherwise.

We can clearly see the difference.

				
					from inspect import isfunction, ismethod, isroutine

def addition():
    pass

class arithmtic:
    def addition(self):
        pass
object = arithmtic()

print(isfunction(addition))
True
# instance of the class
print(isfunction(object.addition))
False
				
			

Similarly, we test whether an object is a method or not using the ismethod

				
					print(ismethod(addition))
False
print(ismethod(object.addition))
True
				
			

Quick Guide

I hope you learned something new today. Check out other posts and learn new things. Also, do tell me how did you like the posts and how can I make them better. Your friendly neighbour developer

Share

Facebook
Twitter
Pinterest
LinkedIn

Follow us on

Related Posts

You may also like

On Key

Related Posts