如果未使用的导入在导入时运行函数,是否可以接受?

2024-04-25 13:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用许多不同的基本脚本在不同的时间推送数据、拉取报告等,这些脚本有一个cron条目在VM上运行。你知道吗

当这些脚本启动时,我想运行一个共享的函数。不过,我目前的做法让人感觉不太清楚。你知道吗

我举了一个基本的例子:

sharedmodule.py

def script_start_func()
    # do stuff

script_start_func()

然后我将这个模块导入到每个正在运行的脚本中,以便在导入模块时运行函数,如下所示:

one_of_many_different_scripts.py

import sharedmodule  #flagged in IDE as unused

# do normal script stuff

感觉应该有更好的方法来达到同样的目的,尽管在当时它似乎是一种合理的方法,不需要在每个脚本的顶部加sharedmodule.script_start_func()。你知道吗

有没有更好的方法?你知道吗

我开始认为,实际上调用函数只是一个额外的行,并且清楚地知道发生了什么?你知道吗

我已经搜索了这个主题,但似乎找不到现有的答案。你知道吗

谢谢


Tags: 模块数据方法函数py脚本报告时间
1条回答
网友
1楼 · 发布于 2024-04-25 13:39:01

我将引用“Python之禅”来回答:

> python -c "import this"

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one and preferably only one obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea let's do more of those!

第二行指出显式优于隐式。这就是我想要传达的。显式调用函数比隐式调用好得多,原因如下:

  • 它使您可以控制何时何地调用该函数
  • 它有助于在出现问题时进行调试,因为您可以注释掉调用,在调用之前和/或之后打印一些调试信息
  • 代码更容易理解,因为调用不会隐藏在调用脚本中

当然,这样做的代价是,必须多打一行字,但我相信好处大于代价。你知道吗

相关问题 更多 >