How to resolve the hardcoding when a newer version of the library i use uses a different function name? - python

核能气质少年 提交于 2019-12-13 20:12:26

问题


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/

Originally, i have bs4 code, but my users have bs3, so i have to put the following code everywhere:

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')

回答1:


May be you should just monkey-patch the 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')


来源:https://stackoverflow.com/questions/20218788/how-to-resolve-the-hardcoding-when-a-newer-version-of-the-library-i-use-uses-a-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!