我想替换这个样板:
def Foo():
pass
if __name__ == "__main__":
run_unit_test(Foo)
有了这个:
@test_if_main
def Foo():
pass
是否有可能?
# utils.py
import inspect
def test_if_main(f):
caller = inspect.stack()[1]
mod = inspect.getmodule(caller[0])
if mod.__name__ == "__main__":
print('running unit tests...')
return f
# Foo.py
from utils import test_if_main
@test_if_main
def Foo():
print(42)
# handled by @test_if_main
# if __name__ == "__main__":
# print("do unit tests here...")
# Bar.py
from Foo import Foo
Foo()
python3 Foo.py
印刷 do unit tests here...
python3 Bar.py
印刷 42
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句