We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
no_sub_classes context mgr is failing silently
I noticed that the no_sub_classes context manager is not working at all but its also swallowing exceptions and thus, failing silently. In fact, see below:
```
In [1]: import mongoengine as me
   ...: me.connect()
   ...: 
   ...: class Parent(me.Document):
   ...:     name = me.StringField()
   ...:     meta = {'allow_inheritance': True}
   ...: 
   ...: class SuperParent(Parent):
   ...:     pass
   ...: 
   ...: Parent(name='John').save()
   ...: SuperParent(name='Hulk').save()
Out[1]: <SuperParent: SuperParent object>

In [2]: 
   ...: with me.context_managers.no_sub_classes(Parent):
   ...:     print 'before'
   ...:     print Parent.objects().first()	# raises InvalidDocument: Cannot encode object: <class '__main__.Parent'> but gets silenced by context
   ...:     print 'after'			# Never gets executed
   ...: print'out of context'
before
out of context
```
This is due to the no_subclasses' \__exit\__ method which is returning something that evaluates to True and by convention, the __exit__ methods of context manager swallows exceptions when doing so (https://stackoverflow.com/a/18399069)

This means that the no_sub_classes is even swallowing the AssertionError that are actually raised within the unit tests. I'll push a PR shortly.

One last thing, the context is patching the main Document class, so it is confusing to have the context manager returning the class. In fact:
```
with no_subclasses(Parent) as ParentNoSubClasses:
    print (Parent is ParentNoSubClasses) # True
```
It should only be used like:
```
with no_subclasses(Parent):
    print (Parent is ParentNoSubClasses)
```
I'd love to get rid of the "with ... as" but I'm assuming that you are against breaking changes so I won't change this. I'll push a PR to fix the issues mentioned earlier

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mongoengine/context_managers.py`
Content:
```
1 from contextlib import contextmanager
2 from pymongo.write_concern import WriteConcern
3 from mongoengine.common import _import_class
4 from mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db
5 
6 
7 __all__ = ('switch_db', 'switch_collection', 'no_dereference',
8            'no_sub_classes', 'query_counter', 'set_write_concern')
9 
10 
11 class switch_db(object):
12     """switch_db alias context manager.
13 
14     Example ::
15 
16         # Register connections
17         register_connection('default', 'mongoenginetest')
18         register_connection('testdb-1', 'mongoenginetest2')
19 
20         class Group(Document):
21             name = StringField()
22 
23         Group(name='test').save()  # Saves in the default db
24 
25         with switch_db(Group, 'testdb-1') as Group:
26             Group(name='hello testdb!').save()  # Saves in testdb-1
27     """
28 
29     def __init__(self, cls, db_alias):
30         """Construct the switch_db context manager
31 
32         :param cls: the class to change the registered db
33         :param db_alias: the name of the specific database to use
34         """
35         self.cls = cls
36         self.collection = cls._get_collection()
37         self.db_alias = db_alias
38         self.ori_db_alias = cls._meta.get('db_alias', DEFAULT_CONNECTION_NAME)
39 
40     def __enter__(self):
41         """Change the db_alias and clear the cached collection."""
42         self.cls._meta['db_alias'] = self.db_alias
43         self.cls._collection = None
44         return self.cls
45 
46     def __exit__(self, t, value, traceback):
47         """Reset the db_alias and collection."""
48         self.cls._meta['db_alias'] = self.ori_db_alias
49         self.cls._collection = self.collection
50 
51 
52 class switch_collection(object):
53     """switch_collection alias context manager.
54 
55     Example ::
56 
57         class Group(Document):
58             name = StringField()
59 
60         Group(name='test').save()  # Saves in the default db
61 
62         with switch_collection(Group, 'group1') as Group:
63             Group(name='hello testdb!').save()  # Saves in group1 collection
64     """
65 
66     def __init__(self, cls, collection_name):
67         """Construct the switch_collection context manager.
68 
69         :param cls: the class to change the registered db
70         :param collection_name: the name of the collection to use
71         """
72         self.cls = cls
73         self.ori_collection = cls._get_collection()
74         self.ori_get_collection_name = cls._get_collection_name
75         self.collection_name = collection_name
76 
77     def __enter__(self):
78         """Change the _get_collection_name and clear the cached collection."""
79 
80         @classmethod
81         def _get_collection_name(cls):
82             return self.collection_name
83 
84         self.cls._get_collection_name = _get_collection_name
85         self.cls._collection = None
86         return self.cls
87 
88     def __exit__(self, t, value, traceback):
89         """Reset the collection."""
90         self.cls._collection = self.ori_collection
91         self.cls._get_collection_name = self.ori_get_collection_name
92 
93 
94 class no_dereference(object):
95     """no_dereference context manager.
96 
97     Turns off all dereferencing in Documents for the duration of the context
98     manager::
99 
100         with no_dereference(Group) as Group:
101             Group.objects.find()
102     """
103 
104     def __init__(self, cls):
105         """Construct the no_dereference context manager.
106 
107         :param cls: the class to turn dereferencing off on
108         """
109         self.cls = cls
110 
111         ReferenceField = _import_class('ReferenceField')
112         GenericReferenceField = _import_class('GenericReferenceField')
113         ComplexBaseField = _import_class('ComplexBaseField')
114 
115         self.deref_fields = [k for k, v in self.cls._fields.iteritems()
116                              if isinstance(v, (ReferenceField,
117                                                GenericReferenceField,
118                                                ComplexBaseField))]
119 
120     def __enter__(self):
121         """Change the objects default and _auto_dereference values."""
122         for field in self.deref_fields:
123             self.cls._fields[field]._auto_dereference = False
124         return self.cls
125 
126     def __exit__(self, t, value, traceback):
127         """Reset the default and _auto_dereference values."""
128         for field in self.deref_fields:
129             self.cls._fields[field]._auto_dereference = True
130         return self.cls
131 
132 
133 class no_sub_classes(object):
134     """no_sub_classes context manager.
135 
136     Only returns instances of this class and no sub (inherited) classes::
137 
138         with no_sub_classes(Group) as Group:
139             Group.objects.find()
140     """
141 
142     def __init__(self, cls):
143         """Construct the no_sub_classes context manager.
144 
145         :param cls: the class to turn querying sub classes on
146         """
147         self.cls = cls
148 
149     def __enter__(self):
150         """Change the objects default and _auto_dereference values."""
151         self.cls._all_subclasses = self.cls._subclasses
152         self.cls._subclasses = (self.cls,)
153         return self.cls
154 
155     def __exit__(self, t, value, traceback):
156         """Reset the default and _auto_dereference values."""
157         self.cls._subclasses = self.cls._all_subclasses
158         delattr(self.cls, '_all_subclasses')
159         return self.cls
160 
161 
162 class query_counter(object):
163     """Query_counter context manager to get the number of queries."""
164 
165     def __init__(self):
166         """Construct the query_counter."""
167         self.counter = 0
168         self.db = get_db()
169 
170     def __enter__(self):
171         """On every with block we need to drop the profile collection."""
172         self.db.set_profiling_level(0)
173         self.db.system.profile.drop()
174         self.db.set_profiling_level(2)
175         return self
176 
177     def __exit__(self, t, value, traceback):
178         """Reset the profiling level."""
179         self.db.set_profiling_level(0)
180 
181     def __eq__(self, value):
182         """== Compare querycounter."""
183         counter = self._get_count()
184         return value == counter
185 
186     def __ne__(self, value):
187         """!= Compare querycounter."""
188         return not self.__eq__(value)
189 
190     def __lt__(self, value):
191         """< Compare querycounter."""
192         return self._get_count() < value
193 
194     def __le__(self, value):
195         """<= Compare querycounter."""
196         return self._get_count() <= value
197 
198     def __gt__(self, value):
199         """> Compare querycounter."""
200         return self._get_count() > value
201 
202     def __ge__(self, value):
203         """>= Compare querycounter."""
204         return self._get_count() >= value
205 
206     def __int__(self):
207         """int representation."""
208         return self._get_count()
209 
210     def __repr__(self):
211         """repr query_counter as the number of queries."""
212         return u"%s" % self._get_count()
213 
214     def _get_count(self):
215         """Get the number of queries."""
216         ignore_query = {'ns': {'$ne': '%s.system.indexes' % self.db.name}}
217         count = self.db.system.profile.find(ignore_query).count() - self.counter
218         self.counter += 1
219         return count
220 
221 
222 @contextmanager
223 def set_write_concern(collection, write_concerns):
224     combined_concerns = dict(collection.write_concern.document.items())
225     combined_concerns.update(write_concerns)
226     yield collection.with_options(write_concern=WriteConcern(**combined_concerns))
227
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mongoengine/context_managers.py b/mongoengine/context_managers.py
--- a/mongoengine/context_managers.py
+++ b/mongoengine/context_managers.py
@@ -145,18 +145,17 @@
         :param cls: the class to turn querying sub classes on
         """
         self.cls = cls
+        self.cls_initial_subclasses = None
 
     def __enter__(self):
         """Change the objects default and _auto_dereference values."""
-        self.cls._all_subclasses = self.cls._subclasses
-        self.cls._subclasses = (self.cls,)
+        self.cls_initial_subclasses = self.cls._subclasses
+        self.cls._subclasses = (self.cls._class_name,)
         return self.cls
 
     def __exit__(self, t, value, traceback):
         """Reset the default and _auto_dereference values."""
-        self.cls._subclasses = self.cls._all_subclasses
-        delattr(self.cls, '_all_subclasses')
-        return self.cls
+        self.cls._subclasses = self.cls_initial_subclasses
 
 
 class query_counter(object):

{"golden_diff": "diff --git a/mongoengine/context_managers.py b/mongoengine/context_managers.py\n--- a/mongoengine/context_managers.py\n+++ b/mongoengine/context_managers.py\n@@ -145,18 +145,17 @@\n         :param cls: the class to turn querying sub classes on\n         \"\"\"\n         self.cls = cls\n+        self.cls_initial_subclasses = None\n \n     def __enter__(self):\n         \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n-        self.cls._all_subclasses = self.cls._subclasses\n-        self.cls._subclasses = (self.cls,)\n+        self.cls_initial_subclasses = self.cls._subclasses\n+        self.cls._subclasses = (self.cls._class_name,)\n         return self.cls\n \n     def __exit__(self, t, value, traceback):\n         \"\"\"Reset the default and _auto_dereference values.\"\"\"\n-        self.cls._subclasses = self.cls._all_subclasses\n-        delattr(self.cls, '_all_subclasses')\n-        return self.cls\n+        self.cls._subclasses = self.cls_initial_subclasses\n \n \n class query_counter(object):\n", "issue": "no_sub_classes context mgr is failing silently\nI noticed that the no_sub_classes context manager is not working at all but its also swallowing exceptions and thus, failing silently. In fact, see below:\r\n```\r\nIn [1]: import mongoengine as me\r\n   ...: me.connect()\r\n   ...: \r\n   ...: class Parent(me.Document):\r\n   ...:     name = me.StringField()\r\n   ...:     meta = {'allow_inheritance': True}\r\n   ...: \r\n   ...: class SuperParent(Parent):\r\n   ...:     pass\r\n   ...: \r\n   ...: Parent(name='John').save()\r\n   ...: SuperParent(name='Hulk').save()\r\nOut[1]: <SuperParent: SuperParent object>\r\n\r\nIn [2]: \r\n   ...: with me.context_managers.no_sub_classes(Parent):\r\n   ...:     print 'before'\r\n   ...:     print Parent.objects().first()\t# raises InvalidDocument: Cannot encode object: <class '__main__.Parent'> but gets silenced by context\r\n   ...:     print 'after'\t\t\t# Never gets executed\r\n   ...: print'out of context'\r\nbefore\r\nout of context\r\n```\r\nThis is due to the no_subclasses' \\__exit\\__ method which is returning something that evaluates to True and by convention, the __exit__ methods of context manager swallows exceptions when doing so (https://stackoverflow.com/a/18399069)\r\n\r\nThis means that the no_sub_classes is even swallowing the AssertionError that are actually raised within the unit tests. I'll push a PR shortly.\r\n\r\nOne last thing, the context is patching the main Document class, so it is confusing to have the context manager returning the class. In fact:\r\n```\r\nwith no_subclasses(Parent) as ParentNoSubClasses:\r\n    print (Parent is ParentNoSubClasses) # True\r\n```\r\nIt should only be used like:\r\n```\r\nwith no_subclasses(Parent):\r\n    print (Parent is ParentNoSubClasses)\r\n```\r\nI'd love to get rid of the \"with ... as\" but I'm assuming that you are against breaking changes so I won't change this. I'll push a PR to fix the issues mentioned earlier\n", "before_files": [{"content": "from contextlib import contextmanager\nfrom pymongo.write_concern import WriteConcern\nfrom mongoengine.common import _import_class\nfrom mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db\n\n\n__all__ = ('switch_db', 'switch_collection', 'no_dereference',\n           'no_sub_classes', 'query_counter', 'set_write_concern')\n\n\nclass switch_db(object):\n    \"\"\"switch_db alias context manager.\n\n    Example ::\n\n        # Register connections\n        register_connection('default', 'mongoenginetest')\n        register_connection('testdb-1', 'mongoenginetest2')\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_db(Group, 'testdb-1') as Group:\n            Group(name='hello testdb!').save()  # Saves in testdb-1\n    \"\"\"\n\n    def __init__(self, cls, db_alias):\n        \"\"\"Construct the switch_db context manager\n\n        :param cls: the class to change the registered db\n        :param db_alias: the name of the specific database to use\n        \"\"\"\n        self.cls = cls\n        self.collection = cls._get_collection()\n        self.db_alias = db_alias\n        self.ori_db_alias = cls._meta.get('db_alias', DEFAULT_CONNECTION_NAME)\n\n    def __enter__(self):\n        \"\"\"Change the db_alias and clear the cached collection.\"\"\"\n        self.cls._meta['db_alias'] = self.db_alias\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the db_alias and collection.\"\"\"\n        self.cls._meta['db_alias'] = self.ori_db_alias\n        self.cls._collection = self.collection\n\n\nclass switch_collection(object):\n    \"\"\"switch_collection alias context manager.\n\n    Example ::\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_collection(Group, 'group1') as Group:\n            Group(name='hello testdb!').save()  # Saves in group1 collection\n    \"\"\"\n\n    def __init__(self, cls, collection_name):\n        \"\"\"Construct the switch_collection context manager.\n\n        :param cls: the class to change the registered db\n        :param collection_name: the name of the collection to use\n        \"\"\"\n        self.cls = cls\n        self.ori_collection = cls._get_collection()\n        self.ori_get_collection_name = cls._get_collection_name\n        self.collection_name = collection_name\n\n    def __enter__(self):\n        \"\"\"Change the _get_collection_name and clear the cached collection.\"\"\"\n\n        @classmethod\n        def _get_collection_name(cls):\n            return self.collection_name\n\n        self.cls._get_collection_name = _get_collection_name\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the collection.\"\"\"\n        self.cls._collection = self.ori_collection\n        self.cls._get_collection_name = self.ori_get_collection_name\n\n\nclass no_dereference(object):\n    \"\"\"no_dereference context manager.\n\n    Turns off all dereferencing in Documents for the duration of the context\n    manager::\n\n        with no_dereference(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_dereference context manager.\n\n        :param cls: the class to turn dereferencing off on\n        \"\"\"\n        self.cls = cls\n\n        ReferenceField = _import_class('ReferenceField')\n        GenericReferenceField = _import_class('GenericReferenceField')\n        ComplexBaseField = _import_class('ComplexBaseField')\n\n        self.deref_fields = [k for k, v in self.cls._fields.iteritems()\n                             if isinstance(v, (ReferenceField,\n                                               GenericReferenceField,\n                                               ComplexBaseField))]\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = False\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = True\n        return self.cls\n\n\nclass no_sub_classes(object):\n    \"\"\"no_sub_classes context manager.\n\n    Only returns instances of this class and no sub (inherited) classes::\n\n        with no_sub_classes(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_sub_classes context manager.\n\n        :param cls: the class to turn querying sub classes on\n        \"\"\"\n        self.cls = cls\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        self.cls._all_subclasses = self.cls._subclasses\n        self.cls._subclasses = (self.cls,)\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        self.cls._subclasses = self.cls._all_subclasses\n        delattr(self.cls, '_all_subclasses')\n        return self.cls\n\n\nclass query_counter(object):\n    \"\"\"Query_counter context manager to get the number of queries.\"\"\"\n\n    def __init__(self):\n        \"\"\"Construct the query_counter.\"\"\"\n        self.counter = 0\n        self.db = get_db()\n\n    def __enter__(self):\n        \"\"\"On every with block we need to drop the profile collection.\"\"\"\n        self.db.set_profiling_level(0)\n        self.db.system.profile.drop()\n        self.db.set_profiling_level(2)\n        return self\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the profiling level.\"\"\"\n        self.db.set_profiling_level(0)\n\n    def __eq__(self, value):\n        \"\"\"== Compare querycounter.\"\"\"\n        counter = self._get_count()\n        return value == counter\n\n    def __ne__(self, value):\n        \"\"\"!= Compare querycounter.\"\"\"\n        return not self.__eq__(value)\n\n    def __lt__(self, value):\n        \"\"\"< Compare querycounter.\"\"\"\n        return self._get_count() < value\n\n    def __le__(self, value):\n        \"\"\"<= Compare querycounter.\"\"\"\n        return self._get_count() <= value\n\n    def __gt__(self, value):\n        \"\"\"> Compare querycounter.\"\"\"\n        return self._get_count() > value\n\n    def __ge__(self, value):\n        \"\"\">= Compare querycounter.\"\"\"\n        return self._get_count() >= value\n\n    def __int__(self):\n        \"\"\"int representation.\"\"\"\n        return self._get_count()\n\n    def __repr__(self):\n        \"\"\"repr query_counter as the number of queries.\"\"\"\n        return u\"%s\" % self._get_count()\n\n    def _get_count(self):\n        \"\"\"Get the number of queries.\"\"\"\n        ignore_query = {'ns': {'$ne': '%s.system.indexes' % self.db.name}}\n        count = self.db.system.profile.find(ignore_query).count() - self.counter\n        self.counter += 1\n        return count\n\n\n@contextmanager\ndef set_write_concern(collection, write_concerns):\n    combined_concerns = dict(collection.write_concern.document.items())\n    combined_concerns.update(write_concerns)\n    yield collection.with_options(write_concern=WriteConcern(**combined_concerns))\n", "path": "mongoengine/context_managers.py"}], "after_files": [{"content": "from contextlib import contextmanager\nfrom pymongo.write_concern import WriteConcern\nfrom mongoengine.common import _import_class\nfrom mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db\n\n\n__all__ = ('switch_db', 'switch_collection', 'no_dereference',\n           'no_sub_classes', 'query_counter', 'set_write_concern')\n\n\nclass switch_db(object):\n    \"\"\"switch_db alias context manager.\n\n    Example ::\n\n        # Register connections\n        register_connection('default', 'mongoenginetest')\n        register_connection('testdb-1', 'mongoenginetest2')\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_db(Group, 'testdb-1') as Group:\n            Group(name='hello testdb!').save()  # Saves in testdb-1\n    \"\"\"\n\n    def __init__(self, cls, db_alias):\n        \"\"\"Construct the switch_db context manager\n\n        :param cls: the class to change the registered db\n        :param db_alias: the name of the specific database to use\n        \"\"\"\n        self.cls = cls\n        self.collection = cls._get_collection()\n        self.db_alias = db_alias\n        self.ori_db_alias = cls._meta.get('db_alias', DEFAULT_CONNECTION_NAME)\n\n    def __enter__(self):\n        \"\"\"Change the db_alias and clear the cached collection.\"\"\"\n        self.cls._meta['db_alias'] = self.db_alias\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the db_alias and collection.\"\"\"\n        self.cls._meta['db_alias'] = self.ori_db_alias\n        self.cls._collection = self.collection\n\n\nclass switch_collection(object):\n    \"\"\"switch_collection alias context manager.\n\n    Example ::\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_collection(Group, 'group1') as Group:\n            Group(name='hello testdb!').save()  # Saves in group1 collection\n    \"\"\"\n\n    def __init__(self, cls, collection_name):\n        \"\"\"Construct the switch_collection context manager.\n\n        :param cls: the class to change the registered db\n        :param collection_name: the name of the collection to use\n        \"\"\"\n        self.cls = cls\n        self.ori_collection = cls._get_collection()\n        self.ori_get_collection_name = cls._get_collection_name\n        self.collection_name = collection_name\n\n    def __enter__(self):\n        \"\"\"Change the _get_collection_name and clear the cached collection.\"\"\"\n\n        @classmethod\n        def _get_collection_name(cls):\n            return self.collection_name\n\n        self.cls._get_collection_name = _get_collection_name\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the collection.\"\"\"\n        self.cls._collection = self.ori_collection\n        self.cls._get_collection_name = self.ori_get_collection_name\n\n\nclass no_dereference(object):\n    \"\"\"no_dereference context manager.\n\n    Turns off all dereferencing in Documents for the duration of the context\n    manager::\n\n        with no_dereference(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_dereference context manager.\n\n        :param cls: the class to turn dereferencing off on\n        \"\"\"\n        self.cls = cls\n\n        ReferenceField = _import_class('ReferenceField')\n        GenericReferenceField = _import_class('GenericReferenceField')\n        ComplexBaseField = _import_class('ComplexBaseField')\n\n        self.deref_fields = [k for k, v in self.cls._fields.iteritems()\n                             if isinstance(v, (ReferenceField,\n                                               GenericReferenceField,\n                                               ComplexBaseField))]\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = False\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = True\n        return self.cls\n\n\nclass no_sub_classes(object):\n    \"\"\"no_sub_classes context manager.\n\n    Only returns instances of this class and no sub (inherited) classes::\n\n        with no_sub_classes(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_sub_classes context manager.\n\n        :param cls: the class to turn querying sub classes on\n        \"\"\"\n        self.cls = cls\n        self.cls_initial_subclasses = None\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        self.cls_initial_subclasses = self.cls._subclasses\n        self.cls._subclasses = (self.cls._class_name,)\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        self.cls._subclasses = self.cls_initial_subclasses\n\n\nclass query_counter(object):\n    \"\"\"Query_counter context manager to get the number of queries.\"\"\"\n\n    def __init__(self):\n        \"\"\"Construct the query_counter.\"\"\"\n        self.counter = 0\n        self.db = get_db()\n\n    def __enter__(self):\n        \"\"\"On every with block we need to drop the profile collection.\"\"\"\n        self.db.set_profiling_level(0)\n        self.db.system.profile.drop()\n        self.db.set_profiling_level(2)\n        return self\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the profiling level.\"\"\"\n        self.db.set_profiling_level(0)\n\n    def __eq__(self, value):\n        \"\"\"== Compare querycounter.\"\"\"\n        counter = self._get_count()\n        return value == counter\n\n    def __ne__(self, value):\n        \"\"\"!= Compare querycounter.\"\"\"\n        return not self.__eq__(value)\n\n    def __lt__(self, value):\n        \"\"\"< Compare querycounter.\"\"\"\n        return self._get_count() < value\n\n    def __le__(self, value):\n        \"\"\"<= Compare querycounter.\"\"\"\n        return self._get_count() <= value\n\n    def __gt__(self, value):\n        \"\"\"> Compare querycounter.\"\"\"\n        return self._get_count() > value\n\n    def __ge__(self, value):\n        \"\"\">= Compare querycounter.\"\"\"\n        return self._get_count() >= value\n\n    def __int__(self):\n        \"\"\"int representation.\"\"\"\n        return self._get_count()\n\n    def __repr__(self):\n        \"\"\"repr query_counter as the number of queries.\"\"\"\n        return u\"%s\" % self._get_count()\n\n    def _get_count(self):\n        \"\"\"Get the number of queries.\"\"\"\n        ignore_query = {'ns': {'$ne': '%s.system.indexes' % self.db.name}}\n        count = self.db.system.profile.find(ignore_query).count() - self.counter\n        self.counter += 1\n        return count\n\n\n@contextmanager\ndef set_write_concern(collection, write_concerns):\n    combined_concerns = dict(collection.write_concern.document.items())\n    combined_concerns.update(write_concerns)\n    yield collection.with_options(write_concern=WriteConcern(**combined_concerns))\n", "path": "mongoengine/context_managers.py"}]}