DEV Community

Mahendra Patel
Mahendra Patel

Posted on

Simplifying function with keyword only arguments

Picture this: you’re working with some legacy code; it has juggling multiple positional arguments passed to a function. Now you are mapping arguments to its value 🗺️ It’s like trying to catch falling knives blindfolded! 🤹‍♂️

The Original Function

def validate_document(name, size, path, doc_type, owner, category, date, issue_by):
    print(f'name: {name}, size: {size}, path: {path}, doc_type: {doc_type}, owner: {owner}, category: {category}, date: {date}, issue_by: {issue_by}')

# Function call with positional argument
validate_document('test.pdf', 1024, 'home/user/', 'pdf', 'Bob', 'medical', '2023-01-02', 'Martin')

Enter fullscreen mode Exit fullscreen mode

It's difficult to work with 🥲, right?

Worry not 😉, you can refactor it to make it better, using keyword only arguments.

Using "*" in function declaration, make sure that all the following arguments will be passed as keyword argument only.

Now your Improved code look like this

def validate_document(name, *, size, path, doc_type, owner, category, date, issue_by):
    print(f'name: {name}, size: {size}, path: {path}, doc_type: {doc_type}, owner: {owner}, category: {category}, date: {date}, issue_by: {issue_by}')

# function called with keyword only arguments
validate_document(name='test.pdf', size=1024, path='home/user/', doc_type='pdf', owner='Bob', category='medical', date='2023-01-02', issue_by='Martin')
Enter fullscreen mode Exit fullscreen mode

Now, only the “name” can venture forth as a positional argument, because it is before "*". The rest arguments must be called by their true names: size, path, doc_type, and so on. 🗝️

If you still try to call function with positional argument you will encounter TypeErorr like following.

TypeError: validate_document() takes 1 positional argument but x were given

Now you have better code to work with which 😇

And Happy Coding!

Top comments (0)

AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️