簡體   English   中英

編寫“僅執行”Python模塊的最佳實踐是什么?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM