dcu
dcu

Reputation: 347

TypeError - Missing required positional arguments using getattr

I am receiving a string which has multiple arguments. When I pass the strings individually to the function I am able to get this to work. I am trying to see if there is a way to get the commented line below to work.

testc.py
class TestClass(object):

    def test(k1, k2, k3, d1):
        print(k1,k2,k3)
        return 'done'
from testc import TestClass

args = 'earth,moon,mars'
d = {'key':'value'}    
#v = getattr(TestClass, 'test')(args, d) #how do I get this to work?
v = getattr(TestClass, 'test')("earth", "moon", "mars", d)
print(v)

Upvotes: 1

Views: 586

Answers (2)

Mike Scotty
Mike Scotty

Reputation: 10782

First, you have to turn your string into a list: args_list = args.split(",").

Then you have to unpack that list using * to pass the list content as separate parameters( w/o the * the list would be passed as a single parameter).

class TestClass(object):
    def test(k1, k2, k3, d1):
        print(k1,k2,k3)
        return 'done'

args = 'earth,moon,mars'
d = {'key':'value'}
args_list = args.split(",")
print("args_list:", args_list)
v = getattr(TestClass, 'test')(*args_list, d)
print("v:", v)

Output:

args_list: ['earth', 'moon', 'mars']
earth moon mars
v: done

Upvotes: 2

Barmar
Barmar

Reputation: 780655

Use split() to split the string into a list, and then use * to spread them into separate arguments.

arglist = args.split(',');
v = getattr(TestClass, 'test')(*arglist, d)

Upvotes: 0

Related Questions