minor: remove all uses of types module

This commit is contained in:
Mike Dirolf 2010-01-26 13:31:36 -05:00
parent 2aa45d1307
commit d80de9cb13
16 changed files with 66 additions and 88 deletions

View File

@ -18,8 +18,6 @@ The `gridfs` package is an implementation of GridFS on top of `pymongo`,
exposing a file-like interface.
"""
import types
from grid_file import GridFile
from pymongo.database import Database
@ -72,12 +70,12 @@ class GridFS(object):
- `collection` (optional): root collection where this file is located
"""
spec = filename_or_spec
if isinstance(filename_or_spec, types.StringTypes):
if isinstance(filename_or_spec, basestring):
spec = {"filename": filename_or_spec}
if not isinstance(spec, dict):
raise TypeError("filename_or_spec must be an "
"instance of (str, dict, SON)")
if not isinstance(collection, types.StringTypes):
if not isinstance(collection, basestring):
raise TypeError("collection must be an instance of (str, unicode)")
# convert to _id's so we can uniquely create GridFile instances
@ -100,7 +98,7 @@ class GridFS(object):
:Parameters:
- `collection` (optional): root collection to list files from
"""
if not isinstance(collection, types.StringTypes):
if not isinstance(collection, basestring):
raise TypeError("collection must be an instance of (str, unicode)")
names = []
for grid_file in self.__database[collection].files.find():

View File

@ -14,7 +14,6 @@
"""File-like object used for reading from and writing to GridFS"""
import types
import datetime
import math
import os
@ -95,13 +94,13 @@ class GridFile(object):
- `collection` (optional): the collection in which to store/retrieve
this file
"""
if not isinstance(file_spec, types.DictType):
if not isinstance(file_spec, dict):
raise TypeError("file_spec must be an instance of (dict, SON)")
if not isinstance(database, Database):
raise TypeError("database must be an instance of database")
if not isinstance(collection, types.StringTypes):
if not isinstance(collection, basestring):
raise TypeError("collection must be an instance of (str, unicode)")
if not isinstance(mode, types.StringTypes):
if not isinstance(mode, basestring):
raise TypeError("mode must be an instance of (str, unicode)")
if mode not in ("r", "w"):
raise ValueError("mode must be one of ('r', 'w')")
@ -311,7 +310,7 @@ class GridFile(object):
"""
self.__assert_open("w")
if not isinstance(str, types.StringType):
if not isinstance(str, basestring):
raise TypeError("can only write strings")
while str:

View File

@ -15,9 +15,6 @@
"""Tools for representing binary data to be stored in MongoDB.
"""
import types
class Binary(str):
"""Representation of binary data to be stored in or retrieved from MongoDB.
@ -37,9 +34,9 @@ class Binary(str):
"""
def __new__(cls, data, subtype=2):
if not isinstance(data, types.StringType):
if not isinstance(data, str):
raise TypeError("data must be an instance of str")
if not isinstance(subtype, types.IntType):
if not isinstance(subtype, int):
raise TypeError("subtype must be an instance of int")
if subtype >= 256 or subtype < 0:
raise ValueError("subtype must be contained in [0, 256)")

View File

@ -16,7 +16,6 @@
Generally not needed to be used by application developers."""
import types
import struct
import re
import datetime
@ -524,7 +523,7 @@ def is_valid(bson):
:Parameters:
- `bson`: the data to be validated
"""
if not isinstance(bson, types.StringType):
if not isinstance(bson, str):
raise TypeError("BSON data must be an instance of a subclass of str")
# 4 MB limit

View File

@ -14,7 +14,6 @@
"""Collection level utilities for Mongo."""
import types
import warnings
import struct
@ -48,10 +47,10 @@ class Collection(object):
- `options`: dictionary of collection options.
see `pymongo.database.Database.create_collection` for details.
"""
if not isinstance(name, types.StringTypes):
if not isinstance(name, basestring):
raise TypeError("name must be an instance of (str, unicode)")
if not isinstance(options, (types.DictType, types.NoneType)):
if options is not None and not isinstance(options, dict):
raise TypeError("options must be an instance of dict")
if not name or ".." in name:
@ -168,7 +167,7 @@ class Collection(object):
- `manipulate` (optional): manipulate the SON object before saving it
- `safe` (optional): check that the save succeeded?
"""
if not isinstance(to_save, types.DictType):
if not isinstance(to_save, dict):
raise TypeError("cannot save object of type %s" % type(to_save))
if "_id" not in to_save:
@ -201,7 +200,7 @@ class Collection(object):
Bulk insert works with any iterable
"""
docs = doc_or_docs
if isinstance(docs, types.DictType):
if isinstance(docs, dict):
docs = [docs]
if manipulate:
@ -263,11 +262,11 @@ class Collection(object):
.. _update modifiers: http://www.mongodb.org/display/DOCS/Updating
"""
if not isinstance(spec, types.DictType):
if not isinstance(spec, dict):
raise TypeError("spec must be an instance of dict")
if not isinstance(document, types.DictType):
if not isinstance(document, dict):
raise TypeError("document must be an instance of dict")
if not isinstance(upsert, types.BooleanType):
if not isinstance(upsert, bool):
raise TypeError("upsert must be an instance of bool")
if upsert and manipulate:
@ -322,7 +321,7 @@ class Collection(object):
if isinstance(spec, ObjectId):
spec = {"_id": spec}
if not isinstance(spec, types.DictType):
if not isinstance(spec, dict):
raise TypeError("spec must be an instance of dict, not %s" %
type(spec))
@ -366,7 +365,7 @@ class Collection(object):
"""
as_dict = {}
for field in fields:
if not isinstance(field, types.StringTypes):
if not isinstance(field, basestring):
raise TypeError("fields must be a list of key names as "
"(string, unicode)")
as_dict[field] = 1
@ -425,19 +424,19 @@ class Collection(object):
slave_okay = self.__database.connection.slave_okay
if not isinstance(spec, types.DictType):
if not isinstance(spec, dict):
raise TypeError("spec must be an instance of dict")
if not isinstance(fields, (types.ListType, types.NoneType)):
if fields is not None and not isinstance(fields, list):
raise TypeError("fields must be an instance of list")
if not isinstance(skip, types.IntType):
if not isinstance(skip, int):
raise TypeError("skip must be an instance of int")
if not isinstance(limit, types.IntType):
if not isinstance(limit, int):
raise TypeError("limit must be an instance of int")
if not isinstance(timeout, types.BooleanType):
if not isinstance(timeout, bool):
raise TypeError("timeout must be an instance of bool")
if not isinstance(snapshot, types.BooleanType):
if not isinstance(snapshot, bool):
raise TypeError("snapshot must be an instance of bool")
if not isinstance(tailable, types.BooleanType):
if not isinstance(tailable, bool):
raise TypeError("tailable must be an instance of bool")
if fields is not None:
@ -565,10 +564,10 @@ class Collection(object):
- `index_or_name`: index (or name of index) to drop
"""
name = index_or_name
if isinstance(index_or_name, types.ListType):
if isinstance(index_or_name, list):
name = self._gen_index_name(index_or_name)
if not isinstance(name, types.StringTypes):
if not isinstance(name, basestring):
raise TypeError("index_or_name must be an index name or list")
self.__database.connection._purge_index(self.__database.name,
@ -674,7 +673,7 @@ class Collection(object):
:Parameters:
- `new_name`: new name for this collection
"""
if not isinstance(new_name, types.StringTypes):
if not isinstance(new_name, basestring):
raise TypeError("new_name must be an instance of (str, unicode)")
if not new_name or ".." in new_name:

View File

@ -36,7 +36,6 @@ To get a :class:`~pymongo.database.Database` instance from a
import sys
import socket
import struct
import types
import threading
import random
import errno
@ -146,9 +145,9 @@ class Connection(object): # TODO support auth for pooling
warnings.warn("The timeout parameter to Connection is deprecated",
DeprecationWarning)
if not isinstance(host, types.StringTypes):
if not isinstance(host, basestring):
raise TypeError("host must be an instance of (str, unicode)")
if not isinstance(port, types.IntType):
if not isinstance(port, int):
raise TypeError("port must be an instance of int")
self.__host = None
@ -181,9 +180,9 @@ class Connection(object): # TODO support auth for pooling
pair with
- `port`: the port number on which to connect
"""
if not isinstance(host, types.StringType):
if not isinstance(host, str):
raise TypeError("host must be an instance of str")
if not isinstance(port, types.IntType):
if not isinstance(port, int):
raise TypeError("port must be an instance of int")
self.__nodes.append((host, port))
@ -618,7 +617,7 @@ class Connection(object): # TODO support auth for pooling
.. seealso:: :meth:`set_cursor_manager` and
the :mod:`~pymongo.cursor_manager` module
"""
if not isinstance(cursor_id, (types.IntType, types.LongType)):
if not isinstance(cursor_id, (int, long)):
raise TypeError("cursor_id must be an instance of (int, long)")
self.__cursor_manager.close(cursor_id)
@ -632,7 +631,7 @@ class Connection(object): # TODO support auth for pooling
:Parameters:
- `cursor_ids`: list of cursor ids to kill
"""
if not isinstance(cursor_ids, types.ListType):
if not isinstance(cursor_ids, list):
raise TypeError("cursor_ids must be a list")
return self._send_message(message.kill_cursors(cursor_ids))
@ -668,7 +667,7 @@ class Connection(object): # TODO support auth for pooling
if isinstance(name, Database):
name = name.name
if not isinstance(name, types.StringTypes):
if not isinstance(name, basestring):
raise TypeError("name_or_database must be an instance of "
"(Database, str, unicode)")

View File

@ -14,7 +14,6 @@
"""Cursor class to iterate over Mongo query results."""
import types
import struct
import warnings
@ -167,7 +166,7 @@ class Cursor(object):
:Parameters:
- `limit`: the number of results to return
"""
if not isinstance(limit, types.IntType):
if not isinstance(limit, int):
raise TypeError("limit must be an int")
self.__check_okay_to_chain()
@ -184,7 +183,7 @@ class Cursor(object):
:Parameters:
- `skip`: the number of results to skip
"""
if not isinstance(skip, (types.IntType, types.LongType)):
if not isinstance(skip, (int, long)):
raise TypeError("skip must be an int")
self.__check_okay_to_chain()
@ -221,7 +220,7 @@ class Cursor(object):
- `index`: An integer or slice index to be applied to this cursor
"""
self.__check_okay_to_chain()
if isinstance(index, types.SliceType):
if isinstance(index, slice):
if index.step is not None:
raise IndexError("Cursor instances do not support slice steps")
@ -242,7 +241,7 @@ class Cursor(object):
self.__limit = limit
return self
if isinstance(index, (types.IntType, types.LongType)):
if isinstance(index, (int, long)):
if index < 0:
raise IndexError("Cursor instances do not support negative indices")
clone = self.clone()
@ -328,7 +327,7 @@ class Cursor(object):
.. versionadded:: 1.2
"""
if not isinstance(key, types.StringTypes):
if not isinstance(key, basestring):
raise TypeError("key must be an instance of (str, unicode)")
command = SON([("distinct", self.__collection.name), ("key", key)])
@ -375,7 +374,7 @@ class Cursor(object):
self.__hint = None
return self
if not isinstance(index, (types.ListType)):
if not isinstance(index, (list)):
raise TypeError("hint takes a list specifying an index")
self.__hint = helpers._index_document(index)
return self
@ -415,7 +414,7 @@ class Cursor(object):
response = db.connection._send_message_with_response(message,
**kwargs)
if isinstance(response, types.TupleType):
if isinstance(response, tuple):
(connection_id, response) = response
else:
connection_id = None

View File

@ -18,8 +18,6 @@ New cursor managers should be defined as subclasses of CursorManager and can be
installed on a connection by calling
`pymongo.connection.Connection.set_cursor_manager`."""
import types
class CursorManager(object):
"""The default cursor manager.
@ -43,7 +41,7 @@ class CursorManager(object):
:Parameters:
- `cursor_id`: cursor id to close
"""
if not isinstance(cursor_id, (types.IntType, types.LongType)):
if not isinstance(cursor_id, (int, long)):
raise TypeError("cursor_id must be an instance of (int, long)")
self.__connection.kill_cursors([cursor_id])
@ -78,7 +76,7 @@ class BatchCursorManager(CursorManager):
:Parameters:
- `cursor_id`: cursor id to close
"""
if not isinstance(cursor_id, (types.IntType, types.LongType)):
if not isinstance(cursor_id, (int, long)):
raise TypeError("cursor_id must be an instance of (int, long)")
self.__dying_cursors.append(cursor_id)

View File

@ -14,7 +14,6 @@
"""Database level operations."""
import types
import warnings
try:
import hashlib
@ -46,7 +45,7 @@ class Database(object):
- `connection`: a connection to Mongo
- `name`: database name
"""
if not isinstance(name, types.StringTypes):
if not isinstance(name, basestring):
raise TypeError("name must be an instance of (str, unicode)")
self.__check_name(name)
@ -245,7 +244,7 @@ class Database(object):
if isinstance(name, Collection):
name = name.name
if not isinstance(name, types.StringTypes):
if not isinstance(name, basestring):
raise TypeError("name_or_collection must be an instance of "
"(Collection, str, unicode)")
@ -266,7 +265,7 @@ class Database(object):
if isinstance(name, Collection):
name = name.name
if not isinstance(name, types.StringTypes):
if not isinstance(name, basestring):
raise TypeError("name_or_collection must be an instance of "
"(Collection, str, unicode)")
@ -298,7 +297,7 @@ class Database(object):
:Parameters:
- `level`: the profiling level to use
"""
if not isinstance(level, types.IntType) or level < 0 or level > 2:
if not isinstance(level, int) or level < 0 or level > 2:
raise ValueError("level must be one of (OFF, SLOW_ONLY, ALL)")
self.command({"profile": level})
@ -357,9 +356,9 @@ class Database(object):
def _password_digest(self, username, password):
"""Get a password digest to use for authentication.
"""
if not isinstance(password, types.StringTypes):
if not isinstance(password, basestring):
raise TypeError("password must be an instance of (str, unicode)")
if not isinstance(username, types.StringTypes):
if not isinstance(username, basestring):
raise TypeError("username must be an instance of (str, unicode)")
md5hash = _md5func()
@ -438,9 +437,9 @@ class Database(object):
- `name`: the name of the user to authenticate
- `password`: the password of the user to authenticate
"""
if not isinstance(name, types.StringTypes):
if not isinstance(name, basestring):
raise TypeError("name must be an instance of (str, unicode)")
if not isinstance(password, types.StringTypes):
if not isinstance(password, basestring):
raise TypeError("password must be an instance of (str, unicode)")
result = self.command({"getnonce": 1})

View File

@ -14,8 +14,6 @@
"""Tools for manipulating DBRefs (references to MongoDB documents)."""
import types
from son import SON
@ -38,9 +36,9 @@ class DBRef(object):
.. versionadded:: 1.1.1
The `database` parameter.
"""
if not isinstance(collection, types.StringTypes):
if not isinstance(collection, basestring):
raise TypeError("collection must be an instance of (str, unicode)")
if not isinstance(database, (types.StringTypes, types.NoneType)):
if database is not None and not isinstance(database, basestring):
raise TypeError("database must be an instance of (str, unicode)")
self.__collection = collection

View File

@ -17,7 +17,6 @@
Performs all writes to Master instance and distributes reads among all
instances."""
import types
import random
from database import Database
@ -47,7 +46,7 @@ class MasterSlaveConnection(object):
"""
if not isinstance(master, Connection):
raise TypeError("master must be a Connection instance")
if not isinstance(slaves, types.ListType) or len(slaves) == 0:
if not isinstance(slaves, list) or len(slaves) == 0:
raise TypeError("slaves must be a list of length >= 1")
for slave in slaves:

View File

@ -18,8 +18,6 @@ New manipulators should be defined as subclasses of SONManipulator and can be
installed on a database by calling
`pymongo.database.Database.add_son_manipulator`."""
import types
from objectid import ObjectId
from dbref import DBRef
from son import SON
@ -136,12 +134,12 @@ class AutoReference(SONManipulator):
"""
def transform_value(value):
if isinstance(value, types.DictType):
if isinstance(value, dict):
if "_id" in value and "_ns" in value:
return DBRef(value["_ns"], transform_value(value["_id"]))
else:
return transform_dict(SON(value))
elif isinstance(value, types.ListType):
elif isinstance(value, list):
return [transform_value(v) for v in value]
return value
@ -159,9 +157,9 @@ class AutoReference(SONManipulator):
def transform_value(value):
if isinstance(value, DBRef):
return self.__database.dereference(value)
elif isinstance(value, types.ListType):
elif isinstance(value, list):
return [transform_value(v) for v in value]
elif isinstance(value, types.DictType):
elif isinstance(value, dict):
return transform_dict(SON(value))
return value

View File

@ -16,7 +16,6 @@ import random
import traceback
import datetime
import re
import types
import sys
sys.path[0:0] = [""]
@ -186,7 +185,7 @@ def simplify(case): # TODO this is a hack
(success, value) = simplify(value)
simplified[key] = value
return (success, success and simplified or case)
if isinstance(case, types.ListType):
if isinstance(case, list):
simplified = list(case)
if random.choice([True, False]):
# delete

View File

@ -14,7 +14,6 @@
"""Test the cursor module."""
import unittest
import types
import random
import warnings
import sys
@ -244,7 +243,7 @@ class TestCursor(unittest.TestCase):
db.test.save({"x": i})
self.assertEqual(10, db.test.find().count())
self.assert_(isinstance(db.test.find().count(), types.IntType))
self.assert_(isinstance(db.test.find().count(), int))
self.assertEqual(10, db.test.find().limit(5).count())
self.assertEqual(10, db.test.find().skip(5).count())

View File

@ -15,7 +15,6 @@
"""Test the database module."""
import unittest
import types
import random
import datetime
import sys
@ -161,11 +160,11 @@ class TestDatabase(unittest.TestCase):
db.set_profiling_level(OFF)
info = db.profiling_info()
self.assert_(isinstance(info, types.ListType))
self.assert_(isinstance(info, list))
self.assert_(len(info) >= 1)
self.assert_(isinstance(info[0]["info"], types.StringTypes))
self.assert_(isinstance(info[0]["info"], basestring))
self.assert_(isinstance(info[0]["ts"], datetime.datetime))
self.assert_(isinstance(info[0]["millis"], types.FloatType))
self.assert_(isinstance(info[0]["millis"], float))
def test_iteration(self):
db = self.connection.pymongo_test
@ -222,7 +221,7 @@ class TestDatabase(unittest.TestCase):
self.assertRaises(TypeError, db._password_digest, None)
self.assert_(isinstance(db._password_digest("mike", "password"),
types.UnicodeType))
unicode))
self.assertEqual(db._password_digest("mike", "password"),
u"cd7e45b3b2767dc2fa9b6b548457ed00")
self.assertEqual(db._password_digest("mike", "password"),

View File

@ -15,7 +15,6 @@
"""Tests for the dbref module."""
import unittest
import types
import sys
sys.path[0:0] = [""]