Python Method - Quick Reference

Python Method - Quick Reference

You're not alone with us, python function syntax I hope all the images on this page are self explainatory. But let me cover in brief.
Syntax

1
2
3
4
5
def function_name(parameters):
	"""docstring"""
	statement(s)

print(function_name.__doc__);

In Python, you can create a method/ function/ procedure (or whatever you call it) with required and optional parameters. Optional parameters can have either default value or they can accept any number of arguments (from 0 to *any). You can pass these optional arguments as single value or with key-value pair. But their sequence should match with what is defined in method definition. Required parameters are also called positional. So you can’t interchange them while calling the function.

python function declaration syntax with default and optional paramters type

Packing and unpacking of arguments and parameters:

python function args kwargs pack unpack

Nested Functions

python decorator

Arguments passed to the original function will be passed to inner function of decorator function automatically.

But what if you need to pass arguments to a decorator function

python decorator with arguments

Now what if you have to support a decorator with arguments and without arguments

1
2
3
4
5
6
7
8
9
10
11
def repeat(arg):
    # @repeat without arguments
    if callable(arg):
        # If the argument is a function, it means 
        num_times = 1
        fn = arg
    # @repeat with arguments
    else:
        num_times = arg
        def decorator(fn):
          :

Yeah I know!! This is not cool. One more thing, you can also chain decorators

A function can be written in a single line as an expression using lambda keyword.

1
(lambda x, y: x + y)(5, 3) #8

Quiz

Let’s check if you really understand it. Remember that a question may have multiple answers.


I hope now it is pretty clear to you. If you still have any doubt then let’s catch up on the discussion page.



Your feedback is really important. So I can improve my future articles and correct what I have already published. You can also suggest if you want me to write an article on particular topic. If you really like this blog, or article, please share with others. That's the only way I can buy time to write more articles.

Amit
Amit Author & Maintainer of many opensourse projects like fast-xml-parser, imglab, stubmatic etc. Very much interested in research & innovations.

Related Articles

Visual Explanation of Python NumPy Library
Python List - Quick Reference
Visual Explanation of Python Panda Library