简体   繁体   English

当我使用的较新版本的库使用不同的函数名称时,如何解决硬编码? -蟒蛇

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

相关问题 如何在安装较新版本和默认版本时打开早期版本的python? - How do I open an earlier version of python when the newer version is installed and the default? 是否有 __file__ 版本,当在函数中使用时,会获取使用库的文件的名称? - Is there a version of __file__ that when used in a function, will get the name of the file that uses the library? 如何使用“venv”更新 Python 虚拟环境以使用更新版本的 Python? - How do I update a Python virtual environment with `venv` to use a newer version of Python? 如何在标准库中的 venv 中使用不同的 Python 版本? (不是 virtualenv!) - How do I use different Python version in venv from standard library? (Not virtualenv!) 如何使用较新版本的libc? - How to use newer version libc? 我安装了 2 个版本的 python,但 cmake 使用的是旧版本。 如何强制 cmake 使用较新版本? - I have 2 versions of python installed, but cmake is using older version. How do I force cmake to use the newer version? 在计算输出时,如何在python中使用unittest来测试使用set.pop()的函数 - How can I use unittest in python to test function that uses set.pop() when calculating the output 机器人框架-如何使用相同的名称功能,但来自我在“关键字”部分中创建的不同python库 - robot framework - how to use the same name functions but come from different python library I created in Keywords section 配置 python sqlite3 模块以使用不同的(较新版本)sqlite 系统库(升级 sqlite) - Configure python sqlite3 module to use different (newer version) sqlite system lib (Upgrade sqlite) Pip 使用与我安装的版本不同的 python 版本 - Pip uses a different python version than the one I installed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM