Files
pytorch/caffe2/python/context_test.py
Tristan Rice dc7d8a889e caffe2: refactor context to allow being typed (#48340)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/48340

This changes the context managed classes from using a decorator to define them to using inheritance. Inheritance allows the python static type checking to work correctly.

```
context.define_context()
class Bar(object): ...

context.define_context(allow_default=True)
class Foo(object): ...
```

becomes
```
class Foo(context.Managed): ...

class Bar(context.DefaultManaged): ...
```

Behavior differences:
* arg_name has been removed since it's not used anywhere
* classes need to call `super()` in `__enter__/__exit__` methods if they override (none do)

This also defines a context.pyi file to add types for python3. python2 support should not be affected

Test Plan:
ci

  buck test //caffe2/caffe2/python:context_test //caffe2/caffe2/python:checkpoint_test

Reviewed By: dongyuzheng

Differential Revision: D25133469

fbshipit-source-id: 16368bf723eeb6ce3308d6827f5ac5e955b4e29a
2020-11-30 18:31:14 -08:00

68 lines
1.8 KiB
Python

from caffe2.python import context, test_util
from threading import Thread
class MyContext(context.Managed):
pass
class DefaultMyContext(context.DefaultManaged):
pass
class ChildMyContext(MyContext):
pass
class TestContext(test_util.TestCase):
def use_my_context(self):
try:
for _ in range(100):
with MyContext() as a:
for _ in range(100):
self.assertTrue(MyContext.current() == a)
except Exception as e:
self._exceptions.append(e)
def testMultiThreaded(self):
threads = []
self._exceptions = []
for _ in range(8):
thread = Thread(target=self.use_my_context)
thread.start()
threads.append(thread)
for t in threads:
t.join()
for e in self._exceptions:
raise e
@MyContext()
def testDecorator(self):
self.assertIsNotNone(MyContext.current())
def testNonDefaultCurrent(self):
with self.assertRaises(AssertionError):
MyContext.current()
ctx = MyContext()
self.assertEqual(MyContext.current(value=ctx), ctx)
self.assertIsNone(MyContext.current(required=False))
def testDefaultCurrent(self):
self.assertIsInstance(DefaultMyContext.current(), DefaultMyContext)
def testNestedContexts(self):
with MyContext() as ctx1:
with DefaultMyContext() as ctx2:
self.assertEqual(DefaultMyContext.current(), ctx2)
self.assertEqual(MyContext.current(), ctx1)
def testChildClasses(self):
with ChildMyContext() as ctx:
self.assertEqual(ChildMyContext.current(), ctx)
self.assertEqual(MyContext.current(), ctx)