LoginSignup
4
1

More than 5 years have passed since last update.

How to design better Python functions

Posted at

How to design better Python functions

In Python, creating a function is the most common approach to enable abstraction. As a programmer, you would have defined a no. of functions in your programming assignments.

We can't equate every function as a good one. Sometimes, you may end up writing a bad function which could hamper the readability and usability of your code. It means that the particular procedure requires refactoring.

In this post, I like to share some of the guidelines to write good functions.

Don't bring complexity

It is possible to write an utter cryptic code in Python, but you should only prefer to keep your code simple and straightforward.

You shouldn't be doing this way

def wrong(*args):
    m, n = args
    return dict(**locals())

You should be doing this way

def right(m, n):
    return {'m': m, 'n': n}

Don't mix instructions

Although, you can write compound statements in Python. But it is not a good way to write code. It makes your code less expressive.

You shouldn't be doing this way

print('first'); print('second')

if m == n: print('first')

if <first complex match> and <second complex match>:
    # execute code

You should be doing this way

print('first')
print('second')

if m == n:
    print('first')

test1 = <first complex match>
test2 = <second complex match>
if test1 and test2 :
    # execute code

Don't blindly use function params

Positional params

These are compulsory and don't have any default values. They are the easiest form of params and you should use if there are few arguments. They are fully part of the function and have a natural order.

Keyword params

These are not compulsory and do have default inputs. You can use then when there is a need to send optional parameters to the function. If your function has more than two positional params, then it is tough to remember the sequence of the arguments. In such a case, using the keyword-based arguments is beneficial.

Quick Reference

  1. Python function
  2. Style your code
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1