How to overcome Python 3.4 NameError: name 'basestring' is not defined

。_饼干妹妹 提交于 2019-12-10 17:14:31

问题


I've got a file called hello.txt in the local directory along side the test.py, which contains this Python 3.4 code:

import easywebdav
webdav = easywebdav.connect('192.168.1.6', username='myUser', password='myPasswd', protocol='http', port=80)
srcDir = "myDir"
webdav.mkdir(srcDir)
webdav.upload("hello.txt", srcDir)

When I run this I get this:

Traceback (most recent call last):
  File "./test.py", line 196, in <module>
    webdav.upload("hello.txt", srcDir)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/easywebdav/client.py", line 153, in upload
    if isinstance(local_path_or_fileobj, basestring):
NameError: name 'basestring' is not defined

Googling this results in several hits, all of which point to the same fix which, in case the paths moved in future, is to include "right after import types":

try:
    unicode = unicode
except NameError:
    # 'unicode' is undefined, must be Python 3
    str = str
    unicode = str
    bytes = bytes
    basestring = (str,bytes)
else:
    # 'unicode' exists, must be Python 2
    str = str
    unicode = unicode
    bytes = str
    basestring = basestring

I wasn't using import types, but to include it or not doesn't appear to make a difference in PyDev - I get an error either way. The line which causes an error is:

unicode = unicode

saying, 'undefined variable'.

OK my python knowledge falters at this point and I've looked for similar posts on this site and not found one specific enough to basestring that I understand to help. I know I need to specify basestring but I don't know how to. Would anyone be charitable enough to point me in the right direction?


回答1:


You can change easywebdav's client.py file like the top two changes in this checkin: https://github.com/hhaderer/easywebdav/commit/983ced508751788434c97b43586a68101eaee67b

The changes consist in replacing basestring by str in client.py.




回答2:


I came up with an elegant pattern that does not require modification of any source files. Please note it might be extended for other modules to keep all 'hacks' in one place:

# py3ports.py
import easywebdav.client
easywebdav.basestring = str
easywebdav.client.basestring = str

# mylib.py
from py3ports import easywebdav


来源:https://stackoverflow.com/questions/26130644/how-to-overcome-python-3-4-nameerror-name-basestring-is-not-defined

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