1

I need to call the class methods based on the command line argument

params = sys.argv[1].split('.')

print params

['Abc', 'test']

suite.addTest(params[0](params[1]))

Traceback (most recent call last):
    File "policy.py", line 407, in <module>
    suite.addTest(params[0](params[1]))
TypeError: 'str' object is not callable

Is their any way to call a class method.

3
  • Where is Abc class defined? Commented May 8, 2014 at 14:06
  • I tried the globals() by using like this suite.addTest(globals()[params[0]](globals()[params[1]])) i got below error " KeyError: 'test' " Commented May 8, 2014 at 14:22
  • See my answer below, don't use globals() twice. Either params is a parameter to calling the class or it's an attribute in which case you would do TestClass = globals()[params[0]] and then getattr(TestClass, params[1]). Commented May 8, 2014 at 14:26

2 Answers 2

3

In your code, params[0] is still the string 'Abc'. You need to transform it into a class that you can call.

Suppose class Abc is in module foo. Then you can do this--

import foo

MyTestClass = getattr(foo, params[0])

suite.addTest(MyTestClass(params[1])
Sign up to request clarification or add additional context in comments.

Comments

0

The quick way to do it is using eval which will take the string and evaluate it in the current namespace. But eval is evil since your program input could look something like:

eval("os.remove('/')")

just as an example. Python also has a dictionary of the globals you can use this:

TestClass = globals()[params[0]]
suite.addTest(TestClass(params[1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.