2008-12-04 62 views
13

哪種方法對於在特定版本的python中導入模塊最有意義?我的用例是我正在編寫將部署到Python 2.3環境中的代碼,並在幾個月內升級到python 2.5。這:導入特定於版本的python模塊的最佳方法

if sys.version_info[:2] >= (2, 5): 
    from string import Template 
else: 
    from our.compat.string import Template 

或本

try: 
    from string import Template 
except ImportError: 
    from our.compat.string import Template 

我知道,這兩種情況下是同樣正確和工作正常,但哪一個是最好?

回答

27

總是第二種方式 - 你永遠不會知道不同的Python安裝將安裝什麼。 Template是一個小問題的特定情況,但是當您測試功能而不是版本時,您總是更加健壯。

這就是我如何讓Testoob支持Python 2.2 - 2.6:我嘗試以不同的方式導入模塊,直到它工作。它也與第三方庫相關。

這裏是一個極端的例子 - 支持不同的選項ElementTree的出現:

try: import elementtree.ElementTree as ET 
except ImportError: 
    try: import cElementTree as ET 
    except ImportError: 
     try: import lxml.etree as ET 
     except ImportError: 
      import xml.etree.ElementTree as ET # Python 2.5 and up 
+0

你已經錯過了`從xml.etree進口cElementTree作爲ET`爲Python 2.5和高達 – jfs 2008-12-05 00:42:37

2

我可能會爭辯說,第二個將是可取的。有時候,你可以從一個較新版本的Python中安裝一個模塊到一個較舊版本的模塊中。例如,wsgiref帶有Python 2.5,但它並不是很少被安裝到舊版本中(我認爲它可以在Python 2.3中使用)。