[英]What's the best practice in the workflow of writing and running python files with Vim?
[英]What's the best practice for writing an “execute only” Python module?
我有一个Python模块,专门用于作为脚本运行,从不作为应该导入的东西,我想在我的代码中强制执行(和沟通)这个意图。
完成此任务的最佳做法是什么?
我可以想象一些选项,比如包装整个文件
if __name__ == '__main__':
# All the code in the module
或者在开始时流产
if __name__ != '__main__':
exit()
# All the code in the module
也许有警告
if __name__ != '__main__':
print('You should not import this')
exit()
# All the code in the module
甚至是断言
assert __name__ == '__main__', 'You should not import this'
但我不确定哪种(如果有的话)是合适的,风格上或技术上的。
虽然你确实可以做到
if __name__ != '__main__':
raise ImportError(...)
# or maybe just emit a warning
它可能会在前一天站在你的脚下。
至少,你应该保留功能,类和其他定义 - 它们不会造成任何伤害,也许你或其他人以后需要它们。
如果你导入一个只暴露函数,类和值而不做输出或其他事情的模块,那么你所损失的只有几毫秒。
相反,你应该把在启动时执行的代码放到一个函数( main()
?)中并以通常的方式执行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.