简体   繁体   English

编写“仅执行”Python模块的最佳实践是什么?

[英]What's the best practice for writing an “execute only” Python module?

I have a Python module that is intended exclusively for running as a script and never as something that should be imported, and I'd like to enforce (and communicate) that intention in my code. 我有一个Python模块,专门用于作为脚本运行,从不作为应该导入的东西,我想在我的代码中强制执行(和沟通)这个意图。

What is the best practice for accomplishing this? 完成此任务的最佳做法是什么?


I can imagine a few options such as wrapping the whole file in 我可以想象一些选项,比如包装整个文件

if __name__ == '__main__':
    # All the code in the module

or aborting at the start 或者在开始时流产

if __name__ != '__main__':
    exit()

# All the code in the module

perhaps with a warning 也许有警告

if __name__ != '__main__':
    print('You should not import this')
    exit()

# All the code in the module

or even an assertion 甚至是断言

assert __name__ == '__main__', 'You should not import this'

But I'm not sure which (if any) is appropriate, stylistically or technically. 但我不确定哪种(如果有的话)是合适的,风格上或技术上的。

While you indeed can do 虽然你确实可以做到

if __name__ != '__main__':
    raise ImportError(...)
    # or maybe just emit a warning

it may stand in your feet the other day. 它可能会在前一天站在你的脚下。

At least, you should keep the functions, classes and other definitions alone - they don't do any harm and maybe you or someone else needs them later. 至少,你应该保留功能,类和其他定义 - 它们不会造成任何伤害,也许你或其他人以后需要它们。

If you import a module which just exposes functions and classes and values without doing output or other things, all you lose is some milliseconds. 如果你导入一个只暴露函数,类和值而不做输出或其他事情的模块,那么你所损失的只有几毫秒。

Instead, you should put the code which executes on startup into a function ( main() ?) and execute that in the usual manner. 相反,你应该把在启动时执行的代码放到一个函数( main() ?)中并以通常的方式执行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用Vim编写和运行python文件的工作流程中的最佳实践是什么? - What's the best practice in the workflow of writing and running python files with Vim? 与stdout分开写入屏幕的最佳实践是什么? - What's the best practice for writing to the screen separately from stdout? Python:执行 50 个 python 函数的最佳实践是什么? - Python: What is the best practice to execute 50 python functions? 在python中访问SimpleDB的最佳模块是什么? - What's the best module to access SimpleDB in python? 编写可维护的网络爬虫的最佳实践是什么? - What is the best practice for writing maintainable web scrapers? 在Anaconda中安装Python模块的开发版本的最佳实践是什么? - What's the best practice for installing development versions of Python modules in Anaconda? Python 多行注释的 PEP8 / 最佳实践是什么? - What's the PEP8 / best practice for Python multiline comments? 在 Python 中处理单值元组的最佳实践是什么? - What's the best practice for handling single-value tuples in Python? 在 DynamoDB 中处理数字的最佳实践是什么(Python + boto3) - What's the best practice for working with numbers in DynamoDB (Python + boto3) 在 python 3.9 之后输入提示的最佳做法是什么? - What's the best practice of typing hint after python 3.9?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM