Is there any method to define a function name from string in python3?

无人久伴 提交于 2020-07-10 10:24:50

问题


I want to define some functions named 'test_[strings]' to use for pytest, like :

testfiles = ['first.py', 'second.py', 'third.py', ... ]

def test_first():
    test_code

def test_second():
    test_code

def test_third():
    test_code

...

The test code is all same, so I think it'll be much simpler if I can define pytest functions by using something like for loop :

for filename in testfiles :
    func_name = 'test_'+filename.rstrip('.py')
    def func_name() :
        test_code

Is this possible in python3? And if it is, could you please kindly let me know how can I do that?


回答1:


It's a bizarre way to define tests as mentioned by @user2357112, but I guess you can do something like this:

testcases = ['first', 'second', 'third']

def test_function():
  print("It worked")

for test in testcases:
  globals()["test_{}".format(test)] = test_function

test_first()
test_second()
test_third()



回答2:


Not quite sure why you want to do in this way, but you could use Python Object-Oriented to do this.

Firstly, define a class.

class Test:
    pass

Define your functions.

def func1(self):
    print('I am func1.')

def func2(self):
    print('I am func2.')

def func3(self):
    print('I am func3.')

Then, inject the functions to the class.

testcases = ['first', 'second', 'third']
functions = [func1, func2, func3]

for i, tc in enumerate(testcases):
    setattr(Test, tc, functions[i])

Then, you can use the functions with the name from your list of strings.

test = Test()

test.first()

# Output:
# I am func1.

test.second()

# Output:
# I am func2.

test.third()

# Output:
# I am func3.



回答3:


testfiles = ['first.py', 'second.py', 'third.py']
test_code = 'print(\'hello\')'
def test_first():
    eval(test_code)


def test_second():
    eval(test_code)

def test_third():
    eval(test_code)

for filename in testfiles :
    func_name = 'def test_'+filename[:-3]+'():eval(test_code)'
    exec(func_name)
    eval('test_'+filename[:-3]+'()')


来源:https://stackoverflow.com/questions/62766804/is-there-any-method-to-define-a-function-name-from-string-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!