[英]How to resolve the hardcoding when a newer version of the library i use uses a different function name? - python
Is there a better way to resolve the problem of hardcoding compatiable code when a library i use uses a different name of the function? 当我使用的库使用函数的其他名称时,是否有更好的方法来解决对兼容代码进行硬编码的问题?
Also, I cannot change the library code. 另外, 我无法更改库代码。 (because that function i'm using is EVERYWHERE in the old version of the code).
(因为在旧版本的代码中,我正在使用的功能无处不在)。 The library is BeautifulSoup 3 and 4. see
Method Name
section in http://www.crummy.com/software/BeautifulSoup/bs4/doc/ 该库为BeautifulSoup 3和4。请参见http://www.crummy.com/software/BeautifulSoup/bs4/doc/中的“
Method Name
部分。
Originally, i have bs4 code, but my users have bs3, so i have to put the following code everywhere: 本来我有bs4代码,但我的用户有bs3,所以我必须将以下代码放在各处:
try:
from bs4 import BeautifulSoup as bs
except:
from BeautifulSoup import BeautifulSoup as bs
page = '''<html>foo bar<p>blah blah black sheep</p> bar</html>'''
try:
p = bs(page).find_all('p')
except: # Imagine i have to do this all over my code that uses `find_all` or `findAll`
p = bs(page).findAll('p')
May be you should just monkey-patch the bs: 可能是您应该对bs进行猴子补丁处理:
try:
from bs4 import BeautifulSoup as bs
except:
from BeautifulSoup import BeautifulSoup as bs
bs.find_all = getattr(bs, 'find_all', False) or getattr(bs, 'findAll')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.