2

l have this function that works perfectly with python2

 def writeCache(env, cache):
        with env.begin(write=True) as txn:
            for k, v in cache.items():
                txn.put(k, v)

However when l execute it with python3.5.2 it returns the following error :

txn.put(k, v)
TypeError: Won't implicitly convert Unicode to bytes; use .encode()

First try to resolve that :

def writeCache(env, cache):
            with env.begin(write=True) as txn:
                for k, v in cache.items():
                    k.encode()

works but variable v is not included.

def writeCache(env, cache):
                with env.begin(write=True) as txn:
                    for k, v in cache.items():
                        k.encode()
                        v.encode()

l get the following :

AttributeError: 'bytes' object has no attribute 'encode'

which is related to v.encode()

vincent75
  • 343
  • 5
  • 14

2 Answers2

4
txn.put(str(k).encode(), str(v).encode())

that works for me.

Phhi7
  • 41
  • 3
0

You don't really give a lot of information, but this is my best guess:

        for k, v in cache.items():
            txn.put(k.encode(), v)

Judging from the TypeError in the title, the txn.put() method wants to have bytes, but at least one of the arguments is a (unicode) string.

v apparently is a bytes object already (hence the AttributeError), so there's no need to encode it anymore. But if k.encode() works, then it is most probably the offending (unicode) string, and encoding it should solve the issue.

Note that str.encode() uses 'utf-8' by default. It's not clear if the same default is used in Python 2, where the conversion is done implicitly. I guess it depends on the library that you are using (the one where txn.put() comes from).

lenz
  • 4,586
  • 4
  • 22
  • 35