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

StackOverflow https://stackoverflow.com/questions/20218788

Question

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')
Was it helpful?

Solution

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top