python not accept keyword arguments

GodMan picture GodMan · Sep 8, 2012 · Viewed 10.1k times · Source

I am trying to make my code NOT to accept keyword arguments just like some bulitins also do not accept keyword arguments, but, I am unable to do so. Here, is my thinking according to my limited understanding:-

def somefunc(a,b):
    print a,b

somefunc(10,20)

Output:

10 20

Now, When I run the following (I know this is not expected to be keyword argument in the function definition, but, looking at the function call, it seems to be the same syntax as that of when calling a function which accepts keyword arguments):

somefunc(b=10,a=20)

Output:

20 10

I have 2 questions:-

  1. Looking at the function call somefunc(b=10,a=20) and not the function definition, this can seem to be either of a call to a function which accepts just normal arguments or a function which accepts keyword arguments. How does the interpreter differentiate between the two?
  2. Is it possible to convert any of our function in a form so that it does not accept keyword arguments just like many of the builtins do?

Why I want to do this at all? I am just checking if I can do this, so that I do not miss anything in understanding python in depth. I do knot know whether python allows that or not.

Answer

mkayala picture mkayala · Sep 8, 2012

You can use arbitrary argument lists to do this. See http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists

For example:

def somefunc(*args):
    print args[0], args[1]

Calling without keywords:

somefunc(10,20)

Gives:

10 20

Calling with keywords:

somefunc(a=10,b=20)

Gives an error:

TypeError: someFunc() got an unexpected keyword argument 'a'

It's unclear why you would want to do this though.