Contents
PyMongo supports Python 3.x where x >= 1.
We do not support Python 3.0.x. It has many problems (some that directly impact PyMongo) and was end-of-lifed with the release of Python 3.1.
Only one intentional change. Instances of bytes are encoded as BSON type 5 (Binary data) with subtype 0. In Python 3 they are decoded back to bytes. In Python 2 they will be decoded to Binary with subtype 0.
For example, let’s insert a bytes instance using Python 3 then read it back. Notice the byte string is decoded back to bytes:
Python 3.1.4 (default, Mar 21 2012, 14:34:01)
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> c = pymongo.MongoClient()
>>> c.test.bintest.insert({'binary': b'this is a byte string'})
ObjectId('4f9086b1fba5222021000000')
>>> c.test.bintest.find_one()
{'binary': b'this is a byte string', '_id': ObjectId('4f9086b1fba5222021000000')}
Now retrieve the same document in Python 2. Notice the byte string is decoded to Binary:
Python 2.7.3 (default, Apr 12 2012, 10:35:17)
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> c = pymongo.MongoClient()
>>> c.test.bintest.find_one()
{u'binary': Binary('this is a byte string', 0), u'_id': ObjectId('4f9086b1fba5222021000000')}
PyMongo makes use of the 2to3 tool to translate much of its code to valid Python 3 syntax at install time. The translated modules are written to the build subdirectory before being installed, leaving the original source files intact. If you start the python interactive shell from the top level source directory after running python setup.py install the untranslated modules will be the first thing in your path. Importing pymongo will result in an exception similar to:
Python 3.1.5 (default, Jun 2 2012, 12:24:49)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pymongo/__init__.py", line 58, in <module>
version = get_version_string()
File "pymongo/__init__.py", line 54, in get_version_string
if isinstance(version_tuple[-1], basestring):
NameError: global name 'basestring' is not defined
Note the path in the traceback (pymongo/__init__.py). Changing out of the source directory takes the untranslated modules out of your path:
$ cd ..
$ python
Python 3.1.5 (default, Jun 2 2012, 12:24:49)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> pymongo.__file__
'/home/behackett/py3k/lib/python3.1/site-packages/pymongo-2.2-py3.1-linux-x86_64.egg/pymongo/__init__.py'