DIGIT-ARC read-only archive · snapshot: July 23, 2026

Python: why it worked later, function keywords:

2 posts · originally from https://geek.digit.in/community/threads/python-why-it-worked-later-function-keywords.109208/

R
ravi.xolve Original post #1
Feb 23, 2009 at 1:35 AM
The following code didn't work:

class X(object):
def f(self, **kwds):
print kwds
try:
print kwds['i'] * 2
except KeyError:
print "unknown keyword argument"
self.g("string", kwds)

def g(self, s, **kwds):
print s
print kwds

if __name__ == "__main__":
x = X()
x.f(k = 2, j = 10)

However the following did:

class X(object):
def f(self, **kwds):
print kwds
try:
print kwds['i'] * 2
except KeyError:
print "unknown keyword argument"
self.g("string", **kwds)

def g(self, s, **kwds):
print s
print kwds

if __name__ == "__main__":
x = X()
x.f(k = 2, j = 10)

Please explain
QwertyManiac
Feb 23, 2009 at 8:48 AM
Its because your g function is set to accept one formal parameter and optional keyword arguments after it. So its set to accept only 2 arguments inside the class, the class itself and s.

In Python, the * is usually used to "unpack" a tuple or a list for passing them as arguments to a function, while the ** is used over dictionaries to make them deliver keyword arguments over to other functions that accept it as the last parameter.

For more, there's Python documentation reference.