When Should you use a Keyword Argument Rather Than a Positional Argument?

Hi! I was wondering, if you can just put in positional arguments, why do you need to go to the extra typing of keyword arguments? Are there any occasions where it is wrong or confusing to use positional arguments or is the kind of arguments used purely a matter of taste?

Hello @varianthealchemist. There are a few reasons to use keyword arguments, and this article explains it nicely. Basically, you use them if you want to miss out having to put certain arguments in (especially for built-in methods), or if you use *. E.g:

def a_function(*a, b):
  for i in a:
    print(i + b)

Using keyword arguments allows you to pass it:

a_function(3, 2, b=2)
#which will print
>>5
>>4

Essentially, using keyword arguments allows you to pass in multiple values for one keyword (also aided by *).
I hope this helps!

1 Like

a kwarg is independent from other args, consider this function:

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)

you might not want to specify all of those.

res = subprocess.run(
    ["black"], capture_output=True, text=True, input=sys.stdin.read()
)
1 Like