[med-svn] [mypy] 01/04: Imported Upstream version 0.4.2

Michael Crusoe misterc-guest at moszumanska.debian.org
Mon Jul 11 15:03:12 UTC 2016


This is an automated email from the git hooks/post-receive script.

misterc-guest pushed a commit to branch master
in repository mypy.

commit 7a93abf96035b14e5d3ea4c9a0d2b0db1392cc0f
Author: Michael R. Crusoe <crusoe at ucdavis.edu>
Date:   Thu Jun 9 14:08:24 2016 -0700

    Imported Upstream version 0.4.2
---
 PKG-INFO                                           |   2 +-
 lib-typing/2.7/test_typing.py                      |  94 ++-
 lib-typing/2.7/typing.py                           |  94 ++-
 lib-typing/3.2/test_typing.py                      |  91 ++-
 lib-typing/3.2/typing.py                           |  97 ++-
 mypy/build.py                                      | 109 +++-
 mypy/checker.py                                    | 182 +++---
 mypy/checkexpr.py                                  | 131 +++-
 mypy/checkmember.py                                |  26 +-
 mypy/checkstrformat.py                             |   2 +-
 mypy/constraints.py                                |  17 +-
 mypy/erasetype.py                                  |  23 +-
 mypy/errors.py                                     |   7 +
 mypy/expandtype.py                                 |   9 +-
 mypy/fastparse.py                                  |  70 ++-
 mypy/fixup.py                                      |   7 +-
 mypy/join.py                                       |  13 +-
 mypy/main.py                                       |   6 +
 mypy/meet.py                                       |  20 +-
 mypy/messages.py                                   |  24 +-
 mypy/nodes.py                                      |  29 +-
 mypy/parse.py                                      |   2 +-
 mypy/replacetvars.py                               |   2 +-
 mypy/sametypes.py                                  |   9 +-
 mypy/semanal.py                                    |  88 ++-
 mypy/solve.py                                      |   4 +-
 mypy/strconv.py                                    |   3 +
 mypy/stubgen.py                                    |  51 +-
 mypy/subtypes.py                                   |  24 +-
 mypy/traverser.py                                  |  11 +-
 mypy/treetransform.py                              |   5 +-
 mypy/typeanal.py                                   |  38 +-
 mypy/typefixture.py                                |  10 +-
 mypy/types.py                                      |  78 ++-
 mypy/version.py                                    |   2 +-
 mypy/visitor.py                                    |   3 +
 mypy/waiter.py                                     |  44 +-
 scripts/pyxlslave.py~                              |  24 -
 setup.py                                           |   8 +-
 typeshed/stdlib/2.7/__builtin__.pyi                |  27 +-
 typeshed/stdlib/2.7/_socket.pyi                    |   2 +-
 typeshed/stdlib/2.7/argparse.pyi                   |  35 +-
 typeshed/stdlib/2.7/builtins.pyi                   |  27 +-
 typeshed/stdlib/2.7/calendar.pyi                   |   2 +-
 typeshed/stdlib/2.7/datetime.pyi                   |   6 +-
 typeshed/stdlib/2.7/getopt.pyi                     |  17 +
 typeshed/stdlib/2.7/gettext.pyi                    |   3 +-
 typeshed/stdlib/2.7/json.pyi                       |   4 +-
 typeshed/stdlib/2.7/logging/__init__.pyi           |  92 +--
 typeshed/stdlib/2.7/logging/handlers.pyi           | 116 ++--
 typeshed/stdlib/2.7/pprint.pyi                     |  11 +-
 typeshed/stdlib/2.7/re.pyi                         |  50 +-
 typeshed/stdlib/2.7/socket.pyi                     |   6 +-
 typeshed/stdlib/2.7/subprocess.pyi                 |  10 +-
 typeshed/stdlib/2.7/sys.pyi                        |   2 +-
 typeshed/stdlib/2.7/tempfile.pyi                   |  65 +-
 typeshed/stdlib/2.7/threading.pyi                  |   2 +-
 typeshed/stdlib/2.7/typing.pyi                     |   7 +-
 typeshed/stdlib/2.7/urlparse.pyi                   |  13 +-
 typeshed/stdlib/3.3/xml/etree/ElementTree.pyi      |   9 -
 typeshed/stdlib/3.4/xml/etree/ElementTree.pyi      |   9 -
 typeshed/stdlib/3.5/xml/etree/ElementTree.pyi      |   9 -
 typeshed/stdlib/3/__future__.pyi                   |   9 +-
 typeshed/stdlib/3/_ast.pyi                         |   2 +-
 typeshed/stdlib/3/_io.pyi                          |  48 --
 typeshed/stdlib/3/builtins.pyi                     |  18 +-
 typeshed/stdlib/3/calendar.pyi                     |   2 +-
 typeshed/stdlib/3/codecs.pyi                       |   2 +-
 typeshed/stdlib/3/datetime.pyi                     |   2 +-
 typeshed/stdlib/3/email/__init__.pyi               |  31 +-
 typeshed/stdlib/3/email/_policybase.pyi            |  34 --
 typeshed/stdlib/3/email/charset.pyi                |  44 +-
 typeshed/stdlib/3/email/contentmanager.pyi         |  39 +-
 typeshed/stdlib/3/email/errors.pyi                 |  34 +-
 typeshed/stdlib/3/email/feedparser.pyi             |  43 +-
 typeshed/stdlib/3/email/generator.pyi              |  49 +-
 typeshed/stdlib/3/email/header.pyi                 |  44 +-
 typeshed/stdlib/3/email/headerregistry.pyi         | 232 ++++----
 typeshed/stdlib/3/email/message.pyi                | 211 ++++---
 typeshed/stdlib/3/email/parser.pyi                 |  66 ++-
 typeshed/stdlib/3/email/policy.pyi                 |  84 ++-
 typeshed/stdlib/3/getopt.pyi                       |   8 +-
 typeshed/stdlib/3/getpass.pyi                      |   2 +-
 typeshed/stdlib/3/gettext.pyi                      |  71 +--
 typeshed/stdlib/3/html/__init__.pyi                |   2 +-
 typeshed/stdlib/3/html/parser.pyi                  |  47 +-
 typeshed/stdlib/3/io.pyi                           | 307 ++++++----
 typeshed/stdlib/3/os/__init__.pyi                  |   3 +
 typeshed/stdlib/3/re.pyi                           |  68 ++-
 typeshed/stdlib/3/socket.pyi                       |  10 +-
 typeshed/stdlib/3/socketserver.pyi                 |  84 ++-
 typeshed/stdlib/3/ssl.pyi                          | 414 +++++++------
 typeshed/stdlib/3/subprocess.pyi                   |  13 +-
 typeshed/stdlib/3/sys.pyi                          |   9 +-
 typeshed/stdlib/3/tkinter/__init__.pyi             | 660 +++++++++++++++++++++
 typeshed/stdlib/3/tkinter/constants.pyi            |  83 +++
 typeshed/stdlib/3/tkinter/ttk.pyi                  | 158 +++++
 typeshed/stdlib/3/typing.pyi                       |   7 +-
 typeshed/stdlib/3/urllib/request.pyi               | 202 ++++++-
 typeshed/stdlib/3/urllib/response.pyi              |  36 +-
 typeshed/stdlib/3/urllib/robotparser.pyi           |  23 +-
 typeshed/third_party/2.7/requests/__init__.pyi     |   1 +
 typeshed/third_party/2.7/requests/api.pyi          |  17 +-
 typeshed/third_party/2.7/six/moves/__init__.pyi    |   1 +
 typeshed/third_party/3/requests/__init__.pyi       |   1 +
 typeshed/third_party/3/six/moves/__init__.pyi      |   1 +
 .../third_party/3/six/moves/urllib/request.pyi     |   2 +-
 .../third_party/3/six/moves/urllib/response.pyi    |   8 -
 .../third_party/3/six/moves/urllib_response.pyi    |  12 +-
 109 files changed, 3790 insertions(+), 1437 deletions(-)

diff --git a/PKG-INFO b/PKG-INFO
index 4e0f94d..9596a38 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: mypy-lang
-Version: 0.4.1
+Version: 0.4.2
 Summary: Optional static typing for Python
 Home-page: http://www.mypy-lang.org/
 Author: Jukka Lehtosalo
diff --git a/lib-typing/2.7/test_typing.py b/lib-typing/2.7/test_typing.py
index 0994662..434afdb 100644
--- a/lib-typing/2.7/test_typing.py
+++ b/lib-typing/2.7/test_typing.py
@@ -1,9 +1,10 @@
 from __future__ import absolute_import, unicode_literals
 
+import collections
 import pickle
 import re
 import sys
-from unittest import TestCase, main
+from unittest import TestCase, main, SkipTest
 
 from typing import Any
 from typing import TypeVar, AnyStr
@@ -13,6 +14,8 @@ from typing import Tuple
 from typing import Callable
 from typing import Generic
 from typing import cast
+from typing import Type
+from typing import NewType
 from typing import NamedTuple
 from typing import IO, TextIO, BinaryIO
 from typing import Pattern, Match
@@ -336,6 +339,20 @@ class UnionTests(BaseTestCase):
         A = Union[str, Pattern]
         A
 
+    def test_etree(self):
+        # See https://github.com/python/typing/issues/229
+        # (Only relevant for Python 2.)
+        try:
+            from xml.etree.cElementTree import Element
+        except ImportError:
+            raise SkipTest("cElementTree not found")
+        Union[Element, str]  # Shouldn't crash
+
+        def Elem(*args):
+            return Element(*args)
+
+        Union[Elem, str]  # Nor should this
+
 
 class TypeVarUnionTests(BaseTestCase):
 
@@ -407,7 +424,7 @@ class TupleTests(BaseTestCase):
 
     def test_repr(self):
         self.assertEqual(repr(Tuple), 'typing.Tuple')
-        self.assertEqual(repr(Tuple[()]), 'typing.Tuple[]')
+        self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]')
         self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]')
         self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]')
 
@@ -970,13 +987,17 @@ class CollectionsAbcTests(BaseTestCase):
         with self.assertRaises(TypeError):
             typing.List[int]()
 
-    def test_list_subclass_instantiation(self):
+    def test_list_subclass(self):
 
         class MyList(typing.List[int]):
             pass
 
         a = MyList()
         self.assertIsInstance(a, MyList)
+        self.assertIsInstance(a, typing.Sequence)
+
+        self.assertIsSubclass(MyList, list)
+        self.assertNotIsSubclass(list, MyList)
 
     def test_no_dict_instantiation(self):
         with self.assertRaises(TypeError):
@@ -986,13 +1007,17 @@ class CollectionsAbcTests(BaseTestCase):
         with self.assertRaises(TypeError):
             typing.Dict[str, int]()
 
-    def test_dict_subclass_instantiation(self):
+    def test_dict_subclass(self):
 
         class MyDict(typing.Dict[str, int]):
             pass
 
         d = MyDict()
         self.assertIsInstance(d, MyDict)
+        self.assertIsInstance(d, typing.MutableMapping)
+
+        self.assertIsSubclass(MyDict, dict)
+        self.assertNotIsSubclass(dict, MyDict)
 
     def test_no_defaultdict_instantiation(self):
         with self.assertRaises(TypeError):
@@ -1002,7 +1027,7 @@ class CollectionsAbcTests(BaseTestCase):
         with self.assertRaises(TypeError):
             typing.DefaultDict[str, int]()
 
-    def test_defaultdict_subclass_instantiation(self):
+    def test_defaultdict_subclass(self):
 
         class MyDefDict(typing.DefaultDict[str, int]):
             pass
@@ -1010,6 +1035,9 @@ class CollectionsAbcTests(BaseTestCase):
         dd = MyDefDict()
         self.assertIsInstance(dd, MyDefDict)
 
+        self.assertIsSubclass(MyDefDict, collections.defaultdict)
+        self.assertNotIsSubclass(collections.defaultdict, MyDefDict)
+
     def test_no_set_instantiation(self):
         with self.assertRaises(TypeError):
             typing.Set()
@@ -1090,6 +1118,62 @@ class CollectionsAbcTests(BaseTestCase):
         self.assertEqual(len(MMB[str, str]()), 0)
         self.assertEqual(len(MMB[KT, VT]()), 0)
 
+        self.assertNotIsSubclass(dict, MMA)
+        self.assertNotIsSubclass(dict, MMB)
+
+        self.assertIsSubclass(MMA, typing.Mapping)
+        self.assertIsSubclass(MMB, typing.Mapping)
+        self.assertIsSubclass(MMC, typing.Mapping)
+
+
+class TypeTests(BaseTestCase):
+
+    def test_type_basic(self):
+
+        class User(object): pass
+        class BasicUser(User): pass
+        class ProUser(User): pass
+
+        def new_user(user_class):
+            # type: (Type[User]) -> User
+            return user_class()
+
+        joe = new_user(BasicUser)
+
+    def test_type_typevar(self):
+
+        class User(object): pass
+        class BasicUser(User): pass
+        class ProUser(User): pass
+
+        global U
+        U = TypeVar('U', bound=User)
+
+        def new_user(user_class):
+            # type: (Type[U]) -> U
+            return user_class()
+
+        joe = new_user(BasicUser)
+
+
+class NewTypeTests(BaseTestCase):
+
+    def test_basic(self):
+        UserId = NewType('UserId', int)
+        UserName = NewType('UserName', str)
+        self.assertIsInstance(UserId(5), int)
+        self.assertIsInstance(UserName('Joe'), type('Joe'))
+        self.assertEqual(UserId(5) + 1, 6)
+
+    def test_errors(self):
+        UserId = NewType('UserId', int)
+        UserName = NewType('UserName', str)
+        with self.assertRaises(TypeError):
+            issubclass(UserId, int)
+        with self.assertRaises(TypeError):
+            class D(UserName):
+                pass
+
 
 class NamedTupleTests(BaseTestCase):
 
diff --git a/lib-typing/2.7/typing.py b/lib-typing/2.7/typing.py
index 57af77c..e7a0e14 100644
--- a/lib-typing/2.7/typing.py
+++ b/lib-typing/2.7/typing.py
@@ -20,9 +20,10 @@ __all__ = [
     'Callable',
     'Generic',
     'Optional',
+    'Tuple',
+    'Type',
     'TypeVar',
     'Union',
-    'Tuple',
 
     # ABCs (from collections.abc).
     'AbstractSet',  # collections.abc.Set.
@@ -60,10 +61,12 @@ __all__ = [
     'AnyStr',
     'cast',
     'get_type_hints',
+    'NewType',
     'no_type_check',
     'no_type_check_decorator',
     'overload',
     'Text',
+    'TYPE_CHECKING',
 ]
 
 # The pseudo-submodules 're' and 'io' are part of the public
@@ -300,7 +303,7 @@ def _type_check(arg, msg):
         return type(None)
     if isinstance(arg, basestring):
         arg = _ForwardRef(arg)
-    if not isinstance(arg, (type, _TypeAlias)):
+    if not isinstance(arg, (type, _TypeAlias)) and not callable(arg):
         raise TypeError(msg + " Got %.100r." % (arg,))
     return arg
 
@@ -454,6 +457,7 @@ class TypeVar(TypingMeta):
 
 
 # Some unconstrained type variables.  These are used by the container types.
+# (These are not for export.)
 T = TypeVar('T')  # Any type.
 KT = TypeVar('KT')  # Key type.
 VT = TypeVar('VT')  # Value type.
@@ -463,6 +467,7 @@ VT_co = TypeVar('VT_co', covariant=True)  # Value type covariant containers.
 T_contra = TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
 
 # A useful type variable with constraints.  This represents string types.
+# (This one *is* for export!)
 AnyStr = TypeVar('AnyStr', bytes, unicode)
 
 
@@ -508,7 +513,10 @@ class UnionMeta(TypingMeta):
             if isinstance(t1, _TypeAlias):
                 # _TypeAlias is not a real class.
                 continue
-            if any(issubclass(t1, t2)
+            if not isinstance(t1, type):
+                assert callable(t1)  # A callable might sneak through.
+                continue
+            if any(isinstance(t2, type) and issubclass(t1, t2)
                    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
                 all_params.remove(t1)
         # It's not a union if there's only one type left.
@@ -694,6 +702,8 @@ class TupleMeta(TypingMeta):
             params = [_type_repr(p) for p in self.__tuple_params__]
             if self.__tuple_use_ellipsis__:
                 params.append('...')
+            if not params:
+                params.append('()')
             r += '[%s]' % (
                 ', '.join(params))
         return r
@@ -911,8 +921,6 @@ def _next_in_mro(cls):
 class GenericMeta(TypingMeta, abc.ABCMeta):
     """Metaclass for generic types."""
 
-    __extra__ = None
-
     def __new__(cls, name, bases, namespace,
                 tvars=None, args=None, origin=None, extra=None):
         self = super(GenericMeta, cls).__new__(cls, name, bases, namespace)
@@ -960,10 +968,7 @@ class GenericMeta(TypingMeta, abc.ABCMeta):
         self.__parameters__ = tvars
         self.__args__ = args
         self.__origin__ = origin
-        if extra is not None:
-            self.__extra__ = extra
-        # Else __extra__ is inherited, eventually from the
-        # (meta-)class default above.
+        self.__extra__ = namespace.get('__extra__')
         # Speed hack (https://github.com/python/typing/issues/196).
         self.__next_in_mro__ = _next_in_mro(self)
         return self
@@ -1289,6 +1294,7 @@ class _ProtocolMeta(GenericMeta):
                             attr != '__next_in_mro__' and
                             attr != '__parameters__' and
                             attr != '__origin__' and
+                            attr != '__extra__' and
                             attr != '__module__'):
                         attrs.add(attr)
 
@@ -1414,10 +1420,12 @@ class ByteString(Sequence[int]):
     pass
 
 
+ByteString.register(str)
 ByteString.register(bytearray)
 
 
 class List(list, MutableSequence[T]):
+    __extra__ = list
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, List):
@@ -1427,6 +1435,7 @@ class List(list, MutableSequence[T]):
 
 
 class Set(set, MutableSet[T]):
+    __extra__ = set
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, Set):
@@ -1452,6 +1461,7 @@ class _FrozenSetMeta(GenericMeta):
 class FrozenSet(frozenset, AbstractSet[T_co]):
     __metaclass__ = _FrozenSetMeta
     __slots__ = ()
+    __extra__ = frozenset
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, FrozenSet):
@@ -1479,6 +1489,7 @@ class ValuesView(MappingView[VT_co]):
 
 
 class Dict(dict, MutableMapping[KT, VT]):
+    __extra__ = dict
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, Dict):
@@ -1488,6 +1499,7 @@ class Dict(dict, MutableMapping[KT, VT]):
 
 
 class DefaultDict(collections.defaultdict, MutableMapping[KT, VT]):
+    __extra__ = collections.defaultdict
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, DefaultDict):
@@ -1516,6 +1528,37 @@ class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]):
         return super(Generator, cls).__new__(cls, *args, **kwds)
 
 
+# Internal type variable used for Type[].
+CT = TypeVar('CT', covariant=True, bound=type)
+
+
+# This is not a real generic class.  Don't use outside annotations.
+class Type(type, Generic[CT]):
+    """A special construct usable to annotate class objects.
+
+    For example, suppose we have the following classes::
+
+      class User: ...  # Abstract base for User classes
+      class BasicUser(User): ...
+      class ProUser(User): ...
+      class TeamUser(User): ...
+
+    And a function that takes a class argument that's a subclass of
+    User and returns an instance of the corresponding class::
+
+      U = TypeVar('U', bound=User)
+      def new_user(user_class: Type[U]) -> U:
+          user = user_class()
+          # (Here we could write the user object to a database)
+          return user
+
+      joe = new_user(BasicUser)
+
+    At this point the type checker knows that joe has type BasicUser.
+    """
+    __extra__ = type
+
+
 def NamedTuple(typename, fields):
     """Typed version of namedtuple.
 
@@ -1543,10 +1586,43 @@ def NamedTuple(typename, fields):
     return cls
 
 
+def NewType(name, tp):
+    """NewType creates simple unique types with almost zero
+    runtime overhead. NewType(name, tp) is considered a subtype of tp
+    by static type checkers. At runtime, NewType(name, tp) returns
+    a dummy function that simply returns its argument. Usage::
+
+        UserId = NewType('UserId', int)
+
+        def name_by_id(user_id):
+            # type: (UserId) -> str
+            ...
+
+        UserId('user')          # Fails type check
+
+        name_by_id(42)          # Fails type check
+        name_by_id(UserId(42))  # OK
+
+        num = UserId(5) + 1     # type: int
+    """
+
+    def new_type(x):
+        return x
+
+    # Some versions of Python 2 complain because of making all strings unicode
+    new_type.__name__ = str(name)
+    new_type.__supertype__ = tp
+    return new_type
+
+
 # Python-version-specific alias (Python 2: unicode; Python 3: str)
 Text = unicode
 
 
+# Constant that's True when type checking, but False here.
+TYPE_CHECKING = False
+
+
 class IO(Generic[AnyStr]):
     """Generic base class for TextIO and BinaryIO.
 
diff --git a/lib-typing/3.2/test_typing.py b/lib-typing/3.2/test_typing.py
index 90bad77..a7f8dd5 100644
--- a/lib-typing/3.2/test_typing.py
+++ b/lib-typing/3.2/test_typing.py
@@ -1,8 +1,9 @@
 import contextlib
+import collections
 import pickle
 import re
 import sys
-from unittest import TestCase, main, skipUnless
+from unittest import TestCase, main, skipUnless, SkipTest
 
 from typing import Any
 from typing import TypeVar, AnyStr
@@ -14,6 +15,8 @@ from typing import Generic
 from typing import cast
 from typing import get_type_hints
 from typing import no_type_check, no_type_check_decorator
+from typing import Type
+from typing import NewType
 from typing import NamedTuple
 from typing import IO, TextIO, BinaryIO
 from typing import Pattern, Match
@@ -337,6 +340,20 @@ class UnionTests(BaseTestCase):
         A = Union[str, Pattern]
         A
 
+    def test_etree(self):
+        # See https://github.com/python/typing/issues/229
+        # (Only relevant for Python 2.)
+        try:
+            from xml.etree.cElementTree import Element
+        except ImportError:
+            raise SkipTest("cElementTree not found")
+        Union[Element, str]  # Shouldn't crash
+
+        def Elem(*args):
+            return Element(*args)
+
+        Union[Elem, str]  # Nor should this
+
 
 class TypeVarUnionTests(BaseTestCase):
 
@@ -408,7 +425,7 @@ class TupleTests(BaseTestCase):
 
     def test_repr(self):
         self.assertEqual(repr(Tuple), 'typing.Tuple')
-        self.assertEqual(repr(Tuple[()]), 'typing.Tuple[]')
+        self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]')
         self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]')
         self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]')
 
@@ -1218,13 +1235,17 @@ class CollectionsAbcTests(BaseTestCase):
         with self.assertRaises(TypeError):
             typing.List[int]()
 
-    def test_list_subclass_instantiation(self):
+    def test_list_subclass(self):
 
         class MyList(typing.List[int]):
             pass
 
         a = MyList()
         self.assertIsInstance(a, MyList)
+        self.assertIsInstance(a, typing.Sequence)
+
+        self.assertIsSubclass(MyList, list)
+        self.assertNotIsSubclass(list, MyList)
 
     def test_no_dict_instantiation(self):
         with self.assertRaises(TypeError):
@@ -1234,13 +1255,17 @@ class CollectionsAbcTests(BaseTestCase):
         with self.assertRaises(TypeError):
             typing.Dict[str, int]()
 
-    def test_dict_subclass_instantiation(self):
+    def test_dict_subclass(self):
 
         class MyDict(typing.Dict[str, int]):
             pass
 
         d = MyDict()
         self.assertIsInstance(d, MyDict)
+        self.assertIsInstance(d, typing.MutableMapping)
+
+        self.assertIsSubclass(MyDict, dict)
+        self.assertNotIsSubclass(dict, MyDict)
 
     def test_no_defaultdict_instantiation(self):
         with self.assertRaises(TypeError):
@@ -1250,7 +1275,7 @@ class CollectionsAbcTests(BaseTestCase):
         with self.assertRaises(TypeError):
             typing.DefaultDict[str, int]()
 
-    def test_defaultdict_subclass_instantiation(self):
+    def test_defaultdict_subclass(self):
 
         class MyDefDict(typing.DefaultDict[str, int]):
             pass
@@ -1258,6 +1283,9 @@ class CollectionsAbcTests(BaseTestCase):
         dd = MyDefDict()
         self.assertIsInstance(dd, MyDefDict)
 
+        self.assertIsSubclass(MyDefDict, collections.defaultdict)
+        self.assertNotIsSubclass(collections.defaultdict, MyDefDict)
+
     def test_no_set_instantiation(self):
         with self.assertRaises(TypeError):
             typing.Set()
@@ -1338,6 +1366,13 @@ class CollectionsAbcTests(BaseTestCase):
         self.assertEqual(len(MMB[str, str]()), 0)
         self.assertEqual(len(MMB[KT, VT]()), 0)
 
+        self.assertNotIsSubclass(dict, MMA)
+        self.assertNotIsSubclass(dict, MMB)
+
+        self.assertIsSubclass(MMA, typing.Mapping)
+        self.assertIsSubclass(MMB, typing.Mapping)
+        self.assertIsSubclass(MMC, typing.Mapping)
+
 
 class OtherABCTests(BaseTestCase):
 
@@ -1354,6 +1389,52 @@ class OtherABCTests(BaseTestCase):
         self.assertNotIsInstance(42, typing.ContextManager)
 
 
+class TypeTests(BaseTestCase):
+
+    def test_type_basic(self):
+
+        class User: pass
+        class BasicUser(User): pass
+        class ProUser(User): pass
+
+        def new_user(user_class: Type[User]) -> User:
+            return user_class()
+
+        joe = new_user(BasicUser)
+
+    def test_type_typevar(self):
+
+        class User: pass
+        class BasicUser(User): pass
+        class ProUser(User): pass
+
+        U = TypeVar('U', bound=User)
+
+        def new_user(user_class: Type[U]) -> U:
+            return user_class()
+
+        joe = new_user(BasicUser)
+
+
+class NewTypeTests(BaseTestCase):
+
+    def test_basic(self):
+        UserId = NewType('UserId', int)
+        UserName = NewType('UserName', str)
+        self.assertIsInstance(UserId(5), int)
+        self.assertIsInstance(UserName('Joe'), str)
+        self.assertEqual(UserId(5) + 1, 6)
+
+    def test_errors(self):
+        UserId = NewType('UserId', int)
+        UserName = NewType('UserName', str)
+        with self.assertRaises(TypeError):
+            issubclass(UserId, int)
+        with self.assertRaises(TypeError):
+            class D(UserName):
+                pass
+
+
 class NamedTupleTests(BaseTestCase):
 
     def test_basics(self):
diff --git a/lib-typing/3.2/typing.py b/lib-typing/3.2/typing.py
index d275011..4cac66c 100644
--- a/lib-typing/3.2/typing.py
+++ b/lib-typing/3.2/typing.py
@@ -19,9 +19,10 @@ __all__ = [
     'Callable',
     'Generic',
     'Optional',
+    'Tuple',
+    'Type',
     'TypeVar',
     'Union',
-    'Tuple',
 
     # ABCs (from collections.abc).
     'AbstractSet',  # collections.abc.Set.
@@ -63,10 +64,12 @@ __all__ = [
     'AnyStr',
     'cast',
     'get_type_hints',
+    'NewType',
     'no_type_check',
     'no_type_check_decorator',
     'overload',
     'Text',
+    'TYPE_CHECKING',
 ]
 
 # The pseudo-submodules 're' and 'io' are part of the public
@@ -305,7 +308,7 @@ def _type_check(arg, msg):
         return type(None)
     if isinstance(arg, str):
         arg = _ForwardRef(arg)
-    if not isinstance(arg, (type, _TypeAlias)):
+    if not isinstance(arg, (type, _TypeAlias)) and not callable(arg):
         raise TypeError(msg + " Got %.100r." % (arg,))
     return arg
 
@@ -447,6 +450,7 @@ class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
 
 
 # Some unconstrained type variables.  These are used by the container types.
+# (These are not for export.)
 T = TypeVar('T')  # Any type.
 KT = TypeVar('KT')  # Key type.
 VT = TypeVar('VT')  # Value type.
@@ -456,6 +460,7 @@ VT_co = TypeVar('VT_co', covariant=True)  # Value type covariant containers.
 T_contra = TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
 
 # A useful type variable with constraints.  This represents string types.
+# (This one *is* for export!)
 AnyStr = TypeVar('AnyStr', bytes, str)
 
 
@@ -500,7 +505,10 @@ class UnionMeta(TypingMeta):
             if isinstance(t1, _TypeAlias):
                 # _TypeAlias is not a real class.
                 continue
-            if any(issubclass(t1, t2)
+            if not isinstance(t1, type):
+                assert callable(t1)  # A callable might sneak through.
+                continue
+            if any(isinstance(t2, type) and issubclass(t1, t2)
                    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
                 all_params.remove(t1)
         # It's not a union if there's only one type left.
@@ -681,6 +689,8 @@ class TupleMeta(TypingMeta):
             params = [_type_repr(p) for p in self.__tuple_params__]
             if self.__tuple_use_ellipsis__:
                 params.append('...')
+            if not params:
+                params.append('()')
             r += '[%s]' % (
                 ', '.join(params))
         return r
@@ -894,8 +904,6 @@ def _next_in_mro(cls):
 class GenericMeta(TypingMeta, abc.ABCMeta):
     """Metaclass for generic types."""
 
-    __extra__ = None
-
     def __new__(cls, name, bases, namespace,
                 tvars=None, args=None, origin=None, extra=None):
         self = super().__new__(cls, name, bases, namespace, _root=True)
@@ -943,10 +951,7 @@ class GenericMeta(TypingMeta, abc.ABCMeta):
         self.__parameters__ = tvars
         self.__args__ = args
         self.__origin__ = origin
-        if extra is not None:
-            self.__extra__ = extra
-        # Else __extra__ is inherited, eventually from the
-        # (meta-)class default above.
+        self.__extra__ = extra
         # Speed hack (https://github.com/python/typing/issues/196).
         self.__next_in_mro__ = _next_in_mro(self)
         return self
@@ -1307,6 +1312,7 @@ class _ProtocolMeta(GenericMeta):
                             attr != '__next_in_mro__' and
                             attr != '__parameters__' and
                             attr != '__origin__' and
+                            attr != '__extra__' and
                             attr != '__module__'):
                         attrs.add(attr)
 
@@ -1470,7 +1476,7 @@ class ByteString(Sequence[int], extra=collections_abc.ByteString):
 ByteString.register(type(memoryview(b'')))
 
 
-class List(list, MutableSequence[T]):
+class List(list, MutableSequence[T], extra=list):
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, List):
@@ -1479,7 +1485,7 @@ class List(list, MutableSequence[T]):
         return list.__new__(cls, *args, **kwds)
 
 
-class Set(set, MutableSet[T]):
+class Set(set, MutableSet[T], extra=set):
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, Set):
@@ -1502,7 +1508,8 @@ class _FrozenSetMeta(GenericMeta):
         return super().__subclasscheck__(cls)
 
 
-class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta):
+class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta,
+                extra=frozenset):
     __slots__ = ()
 
     def __new__(cls, *args, **kwds):
@@ -1538,7 +1545,7 @@ if hasattr(contextlib, 'AbstractContextManager'):
     __all__.append('ContextManager')
 
 
-class Dict(dict, MutableMapping[KT, VT]):
+class Dict(dict, MutableMapping[KT, VT], extra=dict):
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, Dict):
@@ -1546,7 +1553,8 @@ class Dict(dict, MutableMapping[KT, VT]):
                             "use dict() instead")
         return dict.__new__(cls, *args, **kwds)
 
-class DefaultDict(collections.defaultdict, MutableMapping[KT, VT]):
+class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
+                  extra=collections.defaultdict):
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, DefaultDict):
@@ -1574,6 +1582,36 @@ class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
         return super().__new__(cls, *args, **kwds)
 
 
+# Internal type variable used for Type[].
+CT = TypeVar('CT', covariant=True, bound=type)
+
+
+# This is not a real generic class.  Don't use outside annotations.
+class Type(type, Generic[CT], extra=type):
+    """A special construct usable to annotate class objects.
+
+    For example, suppose we have the following classes::
+
+      class User: ...  # Abstract base for User classes
+      class BasicUser(User): ...
+      class ProUser(User): ...
+      class TeamUser(User): ...
+
+    And a function that takes a class argument that's a subclass of
+    User and returns an instance of the corresponding class::
+
+      U = TypeVar('U', bound=User)
+      def new_user(user_class: Type[U]) -> U:
+          user = user_class()
+          # (Here we could write the user object to a database)
+          return user
+
+      joe = new_user(BasicUser)
+
+    At this point the type checker knows that joe has type BasicUser.
+    """
+
+
 def NamedTuple(typename, fields):
     """Typed version of namedtuple.
 
@@ -1601,10 +1639,41 @@ def NamedTuple(typename, fields):
     return cls
 
 
+def NewType(name, tp):
+    """NewType creates simple unique types with almost zero
+    runtime overhead. NewType(name, tp) is considered a subtype of tp
+    by static type checkers. At runtime, NewType(name, tp) returns
+    a dummy function that simply returns its argument. Usage::
+
+        UserId = NewType('UserId', int)
+
+        def name_by_id(user_id: UserId) -> str:
+            ...
+
+        UserId('user')          # Fails type check
+
+        name_by_id(42)          # Fails type check
+        name_by_id(UserId(42))  # OK
+
+        num = UserId(5) + 1     # type: int
+    """
+
+    def new_type(x):
+        return x
+
+    new_type.__name__ = name
+    new_type.__supertype__ = tp
+    return new_type
+
+
 # Python-version-specific alias (Python 2: unicode; Python 3: str)
 Text = str
 
 
+# Constant that's True when type checking, but False here.
+TYPE_CHECKING = False
+
+
 class IO(Generic[AnyStr]):
     """Generic base class for TextIO and BinaryIO.
 
diff --git a/mypy/build.py b/mypy/build.py
index d37dc78..ec2d29a 100644
--- a/mypy/build.py
+++ b/mypy/build.py
@@ -28,7 +28,7 @@ from mypy.nodes import (MypyFile, Node, Import, ImportFrom, ImportAll,
                         SymbolTableNode, MODULE_REF)
 from mypy.semanal import FirstPass, SemanticAnalyzer, ThirdPass
 from mypy.checker import TypeChecker
-from mypy.errors import Errors, CompileError, report_internal_error
+from mypy.errors import Errors, CompileError, DecodeError, report_internal_error
 from mypy import fixup
 from mypy.report import Reports
 from mypy import defaults
@@ -66,6 +66,8 @@ DISALLOW_UNTYPED_CALLS = 'disallow-untyped-calls'
 DISALLOW_UNTYPED_DEFS = 'disallow-untyped-defs'
 # Type check unannotated functions
 CHECK_UNTYPED_DEFS = 'check-untyped-defs'
+# Also check typeshed for missing annotations
+WARN_INCOMPLETE_STUB = 'warn-incomplete-stub'
 
 PYTHON_EXTENSIONS = ['.pyi', '.py']
 
@@ -320,6 +322,7 @@ CacheMeta = NamedTuple('CacheMeta',
                         ('data_mtime', float),  # mtime of data_json
                         ('data_json', str),  # path of <id>.data.json
                         ('suppressed', List[str]),  # dependencies that weren't imported
+                        ('flags', Optional[List[str]]),  # build flags
                         ])
 # NOTE: dependencies + suppressed == all unreachable imports;
 # suppressed contains those reachable imports that were prevented by
@@ -380,7 +383,8 @@ class BuildManager:
                                         self.pyversion,
                                         DISALLOW_UNTYPED_CALLS in self.flags,
                                         DISALLOW_UNTYPED_DEFS in self.flags,
-                                        check_untyped_defs)
+                                        check_untyped_defs,
+                                        WARN_INCOMPLETE_STUB in self.flags)
         self.missing_modules = set()  # type: Set[str]
 
     def all_imported_modules_in_file(self,
@@ -521,10 +525,51 @@ find_module_cache = {}  # type: Dict[Tuple[str, Tuple[str, ...]], str]
 # in the last component.
 find_module_dir_cache = {}  # type: Dict[Tuple[str, Tuple[str, ...]], List[str]]
 
+# Cache directory listings.  We assume that while one os.listdir()
+# call may be more expensive than one os.stat() call, a small number
+# of os.stat() calls is quickly more expensive than caching the
+# os.listdir() outcome, and the advantage of the latter is that it
+# gives us the case-correct filename on Windows and Mac.
+find_module_listdir_cache = {}  # type: Dict[str, Optional[List[str]]]
+
 
 def find_module_clear_caches():
     find_module_cache.clear()
     find_module_dir_cache.clear()
+    find_module_listdir_cache.clear()
+
+
+def list_dir(path: str) -> Optional[List[str]]:
+    """Return a cached directory listing.
+
+    Returns None if the path doesn't exist or isn't a directory.
+    """
+    if path in find_module_listdir_cache:
+        return find_module_listdir_cache[path]
+    try:
+        res = os.listdir(path)
+    except OSError:
+        res = None
+    find_module_listdir_cache[path] = res
+    return res
+
+
+def is_file(path: str) -> bool:
+    """Return whether path exists and is a file.
+
+    On case-insensitive filesystems (like Mac or Windows) this returns
+    False if the case of the path's last component does not exactly
+    match the case found in the filesystem.
+    """
+    head, tail = os.path.split(path)
+    if not tail:
+        return False
+    names = list_dir(head)
+    if not names:
+        return False
+    if tail not in names:
+        return False
+    return os.path.isfile(path)
 
 
 def find_module(id: str, lib_path: Iterable[str]) -> str:
@@ -557,11 +602,15 @@ def find_module(id: str, lib_path: Iterable[str]) -> str:
         sepinit = os.sep + '__init__'
         for base_dir in candidate_base_dirs:
             base_path = base_dir + seplast  # so e.g. '/usr/lib/python3.4/foo/bar/baz'
+            # Prefer package over module, i.e. baz/__init__.py* over baz.py*.
+            for extension in PYTHON_EXTENSIONS:
+                path = base_path + sepinit + extension
+                if is_file(path) and verify_module(id, path):
+                    return path
+            # No package, look for module.
             for extension in PYTHON_EXTENSIONS:
                 path = base_path + extension
-                if not os.path.isfile(path):
-                    path = base_path + sepinit + extension
-                if os.path.isfile(path) and verify_module(id, path):
+                if is_file(path) and verify_module(id, path):
                     return path
         return None
 
@@ -637,6 +686,10 @@ def read_with_python_encoding(path: str, pyversion: Tuple[int, int]) -> str:
                 encoding = _encoding
 
         source_bytearray.extend(f.read())
+        try:
+            source_bytearray.decode(encoding)
+        except LookupError as lookuperr:
+            raise DecodeError(str(lookuperr))
         return source_bytearray.decode(encoding)
 
 
@@ -674,8 +727,7 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
       A CacheMeta instance if the cache data was found and appears
       valid; otherwise None.
     """
-    # TODO: May need to take more build options into account; in
-    # particular SILENT_IMPORTS may affect the cache dramatically.
+    # TODO: May need to take more build options into account
     meta_json, data_json = get_cache_names(id, path, manager.pyversion)
     manager.trace('Looking for {} {}'.format(id, data_json))
     if not os.path.exists(meta_json):
@@ -696,11 +748,22 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
         meta.get('data_mtime'),
         data_json,
         meta.get('suppressed', []),
+        meta.get('flags'),
     )
     if (m.id != id or m.path != path or
             m.mtime is None or m.size is None or
             m.dependencies is None or m.data_mtime is None):
         return None
+
+    # Metadata generated by older mypy version and no flags were saved
+    if m.flags is None:
+        return None
+
+    cached_flags = select_flags_affecting_cache(m.flags)
+    current_flags = select_flags_affecting_cache(manager.flags)
+    if cached_flags != current_flags:
+        return None
+
     # TODO: Share stat() outcome with find_module()
     st = os.stat(path)  # TODO: Errors
     if st.st_mtime != m.mtime or st.st_size != m.size:
@@ -715,6 +778,19 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
     return m
 
 
+def select_flags_affecting_cache(flags: Iterable[str]) -> AbstractSet[str]:
+    return set(flags).intersection(FLAGS_AFFECTING_CACHE)
+
+
+FLAGS_AFFECTING_CACHE = set([
+    SILENT_IMPORTS,
+    ALMOST_SILENT,
+    DISALLOW_UNTYPED_CALLS,
+    DISALLOW_UNTYPED_DEFS,
+    CHECK_UNTYPED_DEFS,
+])
+
+
 def random_string():
     return binascii.hexlify(os.urandom(8)).decode('ascii')
 
@@ -758,14 +834,19 @@ def write_cache(id: str, path: str, tree: MypyFile,
             'data_mtime': data_mtime,
             'dependencies': dependencies,
             'suppressed': suppressed,
+            'flags': manager.flags,
             }
     with open(meta_json_tmp, 'w') as f:
         json.dump(meta, f, sort_keys=True)
         f.write('\n')
-    # TODO: On Windows, os.rename() may not be atomic, and we could
-    # use os.replace().  However that's new in Python 3.3.
-    os.rename(data_json_tmp, data_json)
-    os.rename(meta_json_tmp, meta_json)
+    # TODO: This is a temporary change until Python 3.2 support is dropped, see #1504
+    # os.rename will raise an exception rather than replace files on Windows
+    try:
+        replace = os.replace
+    except AttributeError:
+        replace = os.rename
+    replace(data_json_tmp, data_json)
+    replace(meta_json_tmp, meta_json)
 
 
 """Dependency manager.
@@ -839,7 +920,7 @@ For single nodes, processing is simple.  If the node was cached, we
 deserialize the cache data and fix up cross-references.  Otherwise, we
 do semantic analysis followed by type checking.  We also handle (c)
 above; if a module has valid cache data *but* any of its
-dependendencies was processed from source, then the module should be
+dependencies was processed from source, then the module should be
 processed from source.
 
 A relatively simple optimization (outside SCCs) we might do in the
@@ -1145,7 +1226,7 @@ class State:
                 except IOError as ioerr:
                     raise CompileError([
                         "mypy: can't read file '{}': {}".format(self.path, ioerr.strerror)])
-                except UnicodeDecodeError as decodeerr:
+                except (UnicodeDecodeError, DecodeError) as decodeerr:
                     raise CompileError([
                         "mypy: can't decode file '{}': {}".format(self.path, str(decodeerr))])
             self.tree = manager.parse_file(self.id, self.xpath, source)
@@ -1376,7 +1457,7 @@ def process_graph(graph: Graph, manager: BuildManager) -> None:
         else:
             fresh_msg = "stale due to deps (%s)" % " ".join(sorted(stale_deps))
         if len(scc) == 1:
-            manager.log("Processing SCC sigleton (%s) as %s" % (" ".join(scc), fresh_msg))
+            manager.log("Processing SCC singleton (%s) as %s" % (" ".join(scc), fresh_msg))
         else:
             manager.log("Processing SCC of size %d (%s) as %s" %
                         (len(scc), " ".join(scc), fresh_msg))
diff --git a/mypy/checker.py b/mypy/checker.py
index 2fcb9d4..335344a 100644
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -2,6 +2,8 @@
 
 import itertools
 import contextlib
+import os
+import os.path
 
 from typing import (
     Any, Dict, Set, List, cast, Tuple, TypeVar, Union, Optional, NamedTuple
@@ -15,7 +17,7 @@ from mypy.nodes import (
     TupleExpr, ListExpr, ExpressionStmt, ReturnStmt, IfStmt,
     WhileStmt, OperatorAssignmentStmt, WithStmt, AssertStmt,
     RaiseStmt, TryStmt, ForStmt, DelStmt, CallExpr, IntExpr, StrExpr,
-    BytesExpr, UnicodeExpr, FloatExpr, OpExpr, UnaryExpr, CastExpr, SuperExpr,
+    BytesExpr, UnicodeExpr, FloatExpr, OpExpr, UnaryExpr, CastExpr, RevealTypeExpr, SuperExpr,
     TypeApplication, DictExpr, SliceExpr, FuncExpr, TempNode, SymbolTableNode,
     Context, ListComprehension, ConditionalExpr, GeneratorExpr,
     Decorator, SetExpr, TypeVarExpr, PrintStmt,
@@ -202,7 +204,7 @@ class ConditionalTypeBinder:
         """
         result = self.frames.pop()
 
-        options = self.frames_on_escape.pop(len(self.frames) - 1, [])
+        options = self.frames_on_escape.pop(len(self.frames) - 1, [])  # type: List[Frame]
         if canskip:
             options.append(self.frames[-1])
         if fallthrough:
@@ -375,11 +377,13 @@ class TypeChecker(NodeVisitor[Type]):
     disallow_untyped_defs = False
     # Should we check untyped function defs?
     check_untyped_defs = False
+    warn_incomplete_stub = False
+    is_typeshed_stub = False
 
     def __init__(self, errors: Errors, modules: Dict[str, MypyFile],
                  pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
                  disallow_untyped_calls=False, disallow_untyped_defs=False,
-                 check_untyped_defs=False) -> None:
+                 check_untyped_defs=False, warn_incomplete_stub=False) -> None:
         """Construct a type checker.
 
         Use errors to report type check errors.
@@ -404,6 +408,7 @@ class TypeChecker(NodeVisitor[Type]):
         self.disallow_untyped_calls = disallow_untyped_calls
         self.disallow_untyped_defs = disallow_untyped_defs
         self.check_untyped_defs = check_untyped_defs
+        self.warn_incomplete_stub = warn_incomplete_stub
 
     def visit_file(self, file_node: MypyFile, path: str) -> None:
         """Type check a mypy file with the given path."""
@@ -414,6 +419,8 @@ class TypeChecker(NodeVisitor[Type]):
         self.globals = file_node.names
         self.weak_opts = file_node.weak_opts
         self.enter_partial_types()
+        # gross, but no other clear way to tell
+        self.is_typeshed_stub = self.is_stub and 'typeshed' in os.path.normpath(path).split(os.sep)
 
         for d in file_node.defs:
             self.accept(d)
@@ -426,6 +433,15 @@ class TypeChecker(NodeVisitor[Type]):
         self.errors.set_ignored_lines(set())
         self.current_node_deferred = False
 
+        all_ = self.globals.get('__all__')
+        if all_ is not None and all_.type is not None:
+            seq_str = self.named_generic_type('typing.Sequence',
+                                              [self.named_type('builtins.str')])
+            if not is_subtype(all_.type, seq_str):
+                str_seq_s, all_s = self.msg.format_distinctly(seq_str, all_.type)
+                self.fail(messages.ALL_MUST_BE_SEQ_STR.format(str_seq_s, all_s),
+                          all_.node)
+
     def check_second_pass(self):
         """Run second pass of type checking which goes through deferred nodes."""
         self.pass_num = 1
@@ -666,7 +682,8 @@ class TypeChecker(NodeVisitor[Type]):
                     self.fail(messages.INIT_MUST_HAVE_NONE_RETURN_TYPE,
                               item.type)
 
-                if self.disallow_untyped_defs:
+                show_untyped = not self.is_typeshed_stub or self.warn_incomplete_stub
+                if self.disallow_untyped_defs and show_untyped:
                     # Check for functions with unspecified/not fully specified types.
                     def is_implicit_any(t: Type) -> bool:
                         return isinstance(t, AnyType) and t.implicit
@@ -938,7 +955,7 @@ class TypeChecker(NodeVisitor[Type]):
                 if name in nodes.inplace_operator_methods:
                     # Figure out the name of the corresponding operator method.
                     method = '__' + name[3:]
-                    # An inplace overator method such as __iadd__ might not be
+                    # An inplace operator method such as __iadd__ might not be
                     # always introduced safely if a base class defined __add__.
                     # TODO can't come up with an example where this is
                     #      necessary; now it's "just in case"
@@ -988,43 +1005,55 @@ class TypeChecker(NodeVisitor[Type]):
                      only used for generating error messages.
           supertype: The name of the supertype.
         """
-        if (isinstance(override, Overloaded) or
-                isinstance(original, Overloaded) or
-                len(cast(CallableType, override).arg_types) !=
-                len(cast(CallableType, original).arg_types) or
-                cast(CallableType, override).min_args !=
-                cast(CallableType, original).min_args):
-            # Use boolean variable to clarify code.
-            fail = False
-            if not is_subtype(override, original):
-                fail = True
-            elif (not isinstance(original, Overloaded) and
-                  isinstance(override, Overloaded) and
-                  name in nodes.reverse_op_methods.keys()):
-                # Operator method overrides cannot introduce overloading, as
-                # this could be unsafe with reverse operator methods.
-                fail = True
-            if fail:
+        # Use boolean variable to clarify code.
+        fail = False
+        if not is_subtype(override, original):
+            fail = True
+        elif (not isinstance(original, Overloaded) and
+              isinstance(override, Overloaded) and
+              name in nodes.reverse_op_methods.keys()):
+            # Operator method overrides cannot introduce overloading, as
+            # this could be unsafe with reverse operator methods.
+            fail = True
+
+        if fail:
+            emitted_msg = False
+            if (isinstance(override, CallableType) and
+                    isinstance(original, CallableType) and
+                    len(override.arg_types) == len(original.arg_types) and
+                    override.min_args == original.min_args):
+                # Give more detailed messages for the common case of both
+                # signatures having the same number of arguments and no
+                # overloads.
+
+                # override might have its own generic function type
+                # variables. If an argument or return type of override
+                # does not have the correct subtyping relationship
+                # with the original type even after these variables
+                # are erased, then it is definitely an incompatiblity.
+
+                override_ids = override.type_var_ids()
+
+                def erase_override(t: Type) -> Type:
+                    return erase_typevars(t, ids_to_erase=override_ids)
+
+                for i in range(len(override.arg_types)):
+                    if not is_subtype(original.arg_types[i],
+                                      erase_override(override.arg_types[i])):
+                        self.msg.argument_incompatible_with_supertype(
+                            i + 1, name, name_in_super, supertype, node)
+                        emitted_msg = True
+
+                if not is_subtype(erase_override(override.ret_type),
+                                  original.ret_type):
+                    self.msg.return_type_incompatible_with_supertype(
+                        name, name_in_super, supertype, node)
+                    emitted_msg = True
+
+            if not emitted_msg:
+                # Fall back to generic incompatibility message.
                 self.msg.signature_incompatible_with_supertype(
                     name, name_in_super, supertype, node)
-            return
-        else:
-            # Give more detailed messages for the common case of both
-            # signatures having the same number of arguments and no
-            # overloads.
-
-            coverride = cast(CallableType, override)
-            coriginal = cast(CallableType, original)
-
-            for i in range(len(coverride.arg_types)):
-                if not is_subtype(coriginal.arg_types[i],
-                                  coverride.arg_types[i]):
-                    self.msg.argument_incompatible_with_supertype(
-                        i + 1, name, name_in_super, supertype, node)
-
-            if not is_subtype(coverride.ret_type, coriginal.ret_type):
-                self.msg.return_type_incompatible_with_supertype(
-                    name, name_in_super, supertype, node)
 
     def visit_class_def(self, defn: ClassDef) -> Type:
         """Type check a class definition."""
@@ -1576,10 +1605,12 @@ class TypeChecker(NodeVisitor[Type]):
                     self.fail(messages.NO_RETURN_VALUE_EXPECTED, s)
                 else:
                     self.check_subtype(
-                        typ, return_type, s,
-                        messages.INCOMPATIBLE_RETURN_VALUE_TYPE
-                        + ": expected {}, got {}".format(return_type, typ)
-                    )
+                        subtype_label='got',
+                        subtype=typ,
+                        supertype_label='expected',
+                        supertype=return_type,
+                        context=s,
+                        msg=messages.INCOMPATIBLE_RETURN_VALUE_TYPE)
             else:
                 # Empty returns are valid in Generators with Any typed returns.
                 if (self.function_stack[-1].is_generator and isinstance(return_type, AnyType)):
@@ -1765,7 +1796,7 @@ class TypeChecker(NodeVisitor[Type]):
         for i in range(len(s.handlers)):
             self.binder.push_frame()
             if s.types[i]:
-                t = self.exception_type(s.types[i])
+                t = self.visit_except_handler_test(s.types[i])
                 if s.vars[i]:
                     # To support local variables, we make this a definition line,
                     # causing assignment to set the variable's type.
@@ -1805,38 +1836,32 @@ class TypeChecker(NodeVisitor[Type]):
         if s.finally_body:
             self.accept(s.finally_body)
 
-    def exception_type(self, n: Node) -> Type:
-        if isinstance(n, TupleExpr):
-            t = None  # type: Type
-            for item in n.items:
-                tt = self.exception_type(item)
-                if t:
-                    t = join_types(t, tt)
-                else:
-                    t = tt
-            return t
-        else:
-            # A single exception type; should evaluate to a type object type.
-            type = self.accept(n)
-            return self.check_exception_type(type, n)
-        self.fail('Unsupported exception', n)
-        return AnyType()
+    def visit_except_handler_test(self, n: Node) -> Type:
+        """Type check an exception handler test clause."""
+        type = self.accept(n)
 
-    def check_exception_type(self, type: Type, context: Context) -> Type:
-        if isinstance(type, FunctionLike):
-            item = type.items()[0]
-            ret = item.ret_type
-            if (is_subtype(ret, self.named_type('builtins.BaseException'))
+        all_types = []  # type: List[Type]
+        test_types = type.items if isinstance(type, TupleType) else [type]
+
+        for ttype in test_types:
+            if isinstance(ttype, AnyType):
+                all_types.append(ttype)
+                continue
+
+            if not isinstance(ttype, FunctionLike):
+                self.fail(messages.INVALID_EXCEPTION_TYPE, n)
+                return AnyType()
+
+            item = ttype.items()[0]
+            ret_type = item.ret_type
+            if not (is_subtype(ret_type, self.named_type('builtins.BaseException'))
                     and item.is_type_obj()):
-                return ret
-            else:
-                self.fail(messages.INVALID_EXCEPTION_TYPE, context)
+                self.fail(messages.INVALID_EXCEPTION_TYPE, n)
                 return AnyType()
-        elif isinstance(type, AnyType):
-            return AnyType()
-        else:
-            self.fail(messages.INVALID_EXCEPTION_TYPE, context)
-            return AnyType()
+
+            all_types.append(ret_type)
+
+        return UnionType.make_simplified_union(all_types)
 
     def visit_for_stmt(self, s: ForStmt) -> Type:
         """Type check a for statement."""
@@ -1924,7 +1949,11 @@ class TypeChecker(NodeVisitor[Type]):
         # Process decorators from the inside out.
         for i in range(len(e.decorators)):
             n = len(e.decorators) - 1 - i
-            dec = self.accept(e.decorators[n])
+            d = e.decorators[n]
+            if isinstance(d, NameExpr) and d.fullname == 'typing.overload':
+                self.fail('Single overload definition, multiple required', e)
+                continue
+            dec = self.accept(d)
             temp = self.temp_node(sig)
             sig, t2 = self.expr_checker.check_call(dec, [temp],
                                                    [nodes.ARG_POS], e)
@@ -2069,6 +2098,9 @@ class TypeChecker(NodeVisitor[Type]):
     def visit_cast_expr(self, e: CastExpr) -> Type:
         return self.expr_checker.visit_cast_expr(e)
 
+    def visit_reveal_type_expr(self, e: RevealTypeExpr) -> Type:
+        return self.expr_checker.visit_reveal_type_expr(e)
+
     def visit_super_expr(self, e: SuperExpr) -> Type:
         return self.expr_checker.visit_super_expr(e)
 
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
index 658c9be..64263ce 100644
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -5,12 +5,12 @@ from typing import cast, Dict, List, Tuple, Callable, Union, Optional
 from mypy.types import (
     Type, AnyType, CallableType, Overloaded, NoneTyp, Void, TypeVarDef,
     TupleType, Instance, TypeVarType, ErasedType, UnionType,
-    PartialType, DeletedType, UnboundType
+    PartialType, DeletedType, UnboundType, TypeType
 )
 from mypy.nodes import (
     NameExpr, RefExpr, Var, FuncDef, OverloadedFuncDef, TypeInfo, CallExpr,
     Node, MemberExpr, IntExpr, StrExpr, BytesExpr, UnicodeExpr, FloatExpr,
-    OpExpr, UnaryExpr, IndexExpr, CastExpr, TypeApplication, ListExpr,
+    OpExpr, UnaryExpr, IndexExpr, CastExpr, RevealTypeExpr, TypeApplication, ListExpr,
     TupleExpr, DictExpr, FuncExpr, SuperExpr, SliceExpr, Context,
     ListComprehension, GeneratorExpr, SetExpr, MypyFile, Decorator,
     ConditionalExpr, ComparisonExpr, TempNode, SetComprehension,
@@ -277,9 +277,49 @@ class ExpressionChecker:
         elif isinstance(callee, TypeVarType):
             return self.check_call(callee.upper_bound, args, arg_kinds, context, arg_names,
                                    callable_node, arg_messages)
+        elif isinstance(callee, TypeType):
+            # Pass the original Type[] as context since that's where errors should go.
+            item = self.analyze_type_type_callee(callee.item, callee)
+            return self.check_call(item, args, arg_kinds, context, arg_names,
+                                   callable_node, arg_messages)
         else:
             return self.msg.not_callable(callee, context), AnyType()
 
+    def analyze_type_type_callee(self, item: Type, context: Context) -> Type:
+        """Analyze the callee X in X(...) where X is Type[item].
+
+        Return a Y that we can pass to check_call(Y, ...).
+        """
+        if isinstance(item, AnyType):
+            return AnyType()
+        if isinstance(item, Instance):
+            return type_object_type(item.type, self.named_type)
+        if isinstance(item, UnionType):
+            return UnionType([self.analyze_type_type_callee(item, context)
+                              for item in item.items], item.line)
+        if isinstance(item, TypeVarType):
+            # Pretend we're calling the typevar's upper bound,
+            # i.e. its constructor (a poor approximation for reality,
+            # but better than AnyType...), but replace the return type
+            # with typevar.
+            callee = self.analyze_type_type_callee(item.upper_bound, context)
+            if isinstance(callee, CallableType):
+                if callee.is_generic():
+                    callee = None
+                else:
+                    callee = callee.copy_modified(ret_type=item)
+            elif isinstance(callee, Overloaded):
+                if callee.items()[0].is_generic():
+                    callee = None
+                else:
+                    callee = Overloaded([c.copy_modified(ret_type=item)
+                                         for c in callee.items()])
+            if callee:
+                return callee
+
+        self.msg.unsupported_type_type(item, context)
+        return AnyType()
+
     def infer_arg_types_in_context(self, callee: CallableType,
                                    args: List[Node]) -> List[Type]:
         """Infer argument expression types using a callable type as context.
@@ -306,7 +346,7 @@ class ExpressionChecker:
                     arg_type = self.accept(arg, callee.arg_types[-1])
                 else:
                     arg_type = self.accept(arg)
-            if isinstance(arg_type, ErasedType):
+            if has_erased_component(arg_type):
                 res.append(NoneTyp())
             else:
                 res.append(arg_type)
@@ -368,7 +408,7 @@ class ExpressionChecker:
                 # See also github issues #462 and #360.
                 ret_type = NoneTyp()
         args = infer_type_arguments(callable.type_var_ids(), ret_type, erased_ctx)
-        # Only substite non-None and non-erased types.
+        # Only substitute non-None and non-erased types.
         new_args = []  # type: List[Type]
         for arg in args:
             if isinstance(arg, NoneTyp) or has_erased_component(arg):
@@ -464,7 +504,7 @@ class ExpressionChecker:
         # information to infer the argument. Replace them with None values so
         # that they are not applied yet below.
         for i, arg in enumerate(inferred_args):
-            if isinstance(arg, NoneTyp) or isinstance(arg, ErasedType):
+            if isinstance(arg, NoneTyp) or has_erased_component(arg):
                 inferred_args[i] = None
 
         callee_type = cast(CallableType, self.apply_generic_arguments(
@@ -506,7 +546,7 @@ class ExpressionChecker:
         # case assume that all variables have type Any to avoid extra
         # bogus error messages.
         for i, inferred_type in enumerate(inferred_args):
-            if not inferred_type:
+            if not inferred_type or has_erased_component(inferred_type):
                 # Could not infer a non-trivial type for a type variable.
                 self.msg.could_not_infer_type_arguments(
                     callee_type, i + 1, context)
@@ -663,7 +703,7 @@ class ExpressionChecker:
         best_match = 0
         for typ in overload.items():
             similarity = self.erased_signature_similarity(arg_types, arg_kinds, arg_names,
-                                                          typ)
+                                                          typ, context=context)
             if similarity > 0 and similarity >= best_match:
                 if (match and not is_same_type(match[-1].ret_type,
                                                typ.ret_type) and
@@ -702,12 +742,14 @@ class ExpressionChecker:
                 # matching signature, or default to the first one if none
                 # match.
                 for m in match:
-                    if self.match_signature_types(arg_types, arg_kinds, arg_names, m):
+                    if self.match_signature_types(arg_types, arg_kinds, arg_names, m,
+                                                  context=context):
                         return m
                 return match[0]
 
     def erased_signature_similarity(self, arg_types: List[Type], arg_kinds: List[int],
-                                    arg_names: List[str], callee: CallableType) -> int:
+                                    arg_names: List[str], callee: CallableType,
+                                    context: Context) -> int:
         """Determine whether arguments could match the signature at runtime.
 
         Return similarity level (0 = no match, 1 = can match, 2 = non-promotion match). See
@@ -739,14 +781,15 @@ class ExpressionChecker:
 
         try:
             self.check_argument_types(arg_types, arg_kinds, callee, formal_to_actual,
-                                      None, check_arg=check_arg)
+                                      context=context, check_arg=check_arg)
         except Finished:
             pass
 
         return similarity
 
     def match_signature_types(self, arg_types: List[Type], arg_kinds: List[int],
-                              arg_names: List[str], callee: CallableType) -> bool:
+                              arg_names: List[str], callee: CallableType,
+                              context: Context) -> bool:
         """Determine whether arguments types match the signature.
 
         Assume that argument counts are compatible.
@@ -768,7 +811,7 @@ class ExpressionChecker:
                 ok = False
 
         self.check_argument_types(arg_types, arg_kinds, callee, formal_to_actual,
-                                  None, check_arg=check_arg)
+                                  context=context, check_arg=check_arg)
         return ok
 
     def apply_generic_arguments(self, callable: CallableType, types: List[Type],
@@ -1133,31 +1176,47 @@ class ExpressionChecker:
             return result
 
     def visit_tuple_slice_helper(self, left_type: TupleType, slic: SliceExpr):
-        begin = 0
-        end = len(left_type.items)
-        stride = 1
+        begin = None  # type: int
+        end = None  # type: int
+        stride = None  # type:int
+
         if slic.begin_index:
-            if isinstance(slic.begin_index, IntExpr):
-                begin = slic.begin_index.value
-            else:
-                self.chk.fail(messages.TUPLE_SLICE_MUST_BE_AN_INT_LITERAL, slic.begin_index)
+            begin = self._get_value(slic.begin_index)
+            if begin is None:
+                self.chk.fail(
+                    messages.TUPLE_SLICE_MUST_BE_AN_INT_LITERAL,
+                    slic.begin_index)
                 return AnyType()
+
         if slic.end_index:
-            if isinstance(slic.end_index, IntExpr):
-                end = slic.end_index.value
-            else:
-                self.chk.fail(messages.TUPLE_SLICE_MUST_BE_AN_INT_LITERAL, slic.end_index)
+            end = self._get_value(slic.end_index)
+            if end is None:
+                self.chk.fail(
+                    messages.TUPLE_SLICE_MUST_BE_AN_INT_LITERAL,
+                    slic.end_index)
                 return AnyType()
+
         if slic.stride:
-            if isinstance(slic.stride, IntExpr):
-                stride = slic.stride.value
-            else:
-                self.chk.fail(messages.TUPLE_SLICE_MUST_BE_AN_INT_LITERAL, slic.stride)
+            stride = self._get_value(slic.stride)
+            if stride is None:
+                self.chk.fail(
+                    messages.TUPLE_SLICE_MUST_BE_AN_INT_LITERAL,
+                    slic.stride)
                 return AnyType()
 
         return TupleType(left_type.items[begin:end:stride], left_type.fallback,
                     left_type.line, left_type.implicit)
 
+    def _get_value(self, index: Node) -> Optional[int]:
+        if isinstance(index, IntExpr):
+            return index.value
+        elif isinstance(index, UnaryExpr):
+            if index.op == '-':
+                operand = index.expr
+                if isinstance(operand, IntExpr):
+                    return -1 * operand.value
+        return None
+
     def visit_cast_expr(self, expr: CastExpr) -> Type:
         """Type check a cast expression."""
         source_type = self.accept(expr.expr, context=AnyType())
@@ -1172,6 +1231,12 @@ class ExpressionChecker:
                 (not isinstance(source_type, Void) and
                  not isinstance(target_type, Void)))
 
+    def visit_reveal_type_expr(self, expr: RevealTypeExpr) -> Type:
+        """Type check a reveal_type expression."""
+        revealed_type = self.accept(expr.expr)
+        self.msg.reveal_type(revealed_type, expr)
+        return revealed_type
+
     def visit_type_application(self, tapp: TypeApplication) -> Type:
         """Type check a type application (expr[type, ...])."""
         self.chk.fail(messages.GENERIC_TYPE_NOT_VALID_AS_EXPRESSION, tapp)
@@ -1293,6 +1358,14 @@ class ExpressionChecker:
 
         arg_kinds = [arg.kind for arg in e.arguments]
 
+        if callable_ctx.is_ellipsis_args:
+            # Fill in Any arguments to match the arguments of the lambda.
+            callable_ctx = callable_ctx.copy_modified(
+                is_ellipsis_args=False,
+                arg_types=[AnyType()] * len(arg_kinds),
+                arg_kinds=arg_kinds
+            )
+
         if callable_ctx.arg_kinds != arg_kinds:
             # Incompatible context; cannot use it to infer types.
             self.chk.fail(messages.CANNOT_INFER_LAMBDA_TYPE, e)
@@ -1643,7 +1716,7 @@ def overload_arg_similarity(actual: Type, formal: Type) -> int:
 
     Return a similarity level:
       0: no match
-      1: actual is compatible, but only using type promitions (e.g. int vs float)
+      1: actual is compatible, but only using type promotions (e.g. int vs float)
       2: actual is compatible without type promotions (e.g. int vs object)
 
     The distinction is important in cases where multiple overload items match. We want
@@ -1651,7 +1724,7 @@ def overload_arg_similarity(actual: Type, formal: Type) -> int:
     """
     # Replace type variables with their upper bounds. Overloading
     # resolution is based on runtime behavior which erases type
-    # parameters, so no need to handle type variables occuring within
+    # parameters, so no need to handle type variables occurring within
     # a type.
     if isinstance(actual, TypeVarType):
         actual = actual.erase_to_union_or_bound()
diff --git a/mypy/checkmember.py b/mypy/checkmember.py
index 8eeea02..e3a692c 100644
--- a/mypy/checkmember.py
+++ b/mypy/checkmember.py
@@ -4,7 +4,8 @@ from typing import cast, Callable, List, Optional
 
 from mypy.types import (
     Type, Instance, AnyType, TupleType, CallableType, FunctionLike, TypeVarDef,
-    Overloaded, TypeVarType, TypeTranslator, UnionType, PartialType, DeletedType, NoneTyp
+    Overloaded, TypeVarType, TypeTranslator, UnionType, PartialType,
+    DeletedType, NoneTyp, TypeType
 )
 from mypy.nodes import TypeInfo, FuncBase, Var, FuncDef, SymbolNode, Context
 from mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2, function_type, Decorator, OverloadedFuncDef
@@ -113,6 +114,23 @@ def analyze_member_access(name: str, typ: Type, node: Context, is_lvalue: bool,
     elif isinstance(typ, DeletedType):
         msg.deleted_as_rvalue(typ, node)
         return AnyType()
+    elif isinstance(typ, TypeType):
+        # Similar to FunctionLike + is_type_obj() above.
+        item = None
+        if isinstance(typ.item, Instance):
+            item = typ.item
+        elif isinstance(typ.item, TypeVarType):
+            if isinstance(typ.item.upper_bound, Instance):
+                item = typ.item.upper_bound
+        if item:
+            result = analyze_class_attribute_access(item, name, node, is_lvalue,
+                                                    builtin_type, not_ready_callback, msg)
+            if result:
+                return result
+        fallback = builtin_type('builtins.type')
+        return analyze_member_access(name, fallback, node, is_lvalue, is_super,
+                                     builtin_type, not_ready_callback, msg,
+                                     report_type=report_type)
     return msg.has_no_attr(report_type, name, node)
 
 
@@ -237,6 +255,10 @@ def check_method_type(functype: FunctionLike, itype: Instance, is_classmethod: b
         elif not is_classmethod:
             # Check that self argument has type 'Any' or valid instance type.
             selfarg = item.arg_types[0]
+            # If this is a method of a tuple class, correct for the fact that
+            # we passed to typ.fallback in analyze_member_access. See #1432.
+            if isinstance(selfarg, TupleType):
+                selfarg = selfarg.fallback
             if not subtypes.is_equivalent(selfarg, itype):
                 msg.invalid_method_type(item, context)
         else:
@@ -463,7 +485,7 @@ def map_type_from_supertype(typ: Type, sub_info: TypeInfo,
     inst_type = map_instance_to_supertype(inst_type, super_info)
     # Finally expand the type variables in type with those in the previously
     # constructed type. Note that both type and inst_type may have type
-    # variables, but in type they are interpreterd in supertype context while
+    # variables, but in type they are interpreted in supertype context while
     # in inst_type they are interpreted in subtype context. This works even if
     # the names of type variables in supertype and subtype overlap.
     return expand_type_by_instance(typ, inst_type)
diff --git a/mypy/checkstrformat.py b/mypy/checkstrformat.py
index 0b203e5..368bfae 100644
--- a/mypy/checkstrformat.py
+++ b/mypy/checkstrformat.py
@@ -33,7 +33,7 @@ class ConversionSpecifier:
 
 
 class StringFormatterChecker:
-    """String interplation/formatter type checker.
+    """String interpolation/formatter type checker.
 
     This class works closely together with checker.ExpressionChecker.
     """
diff --git a/mypy/constraints.py b/mypy/constraints.py
index 4ea64f4..8e5fdee 100644
--- a/mypy/constraints.py
+++ b/mypy/constraints.py
@@ -5,7 +5,7 @@ from typing import List, Optional, cast
 from mypy.types import (
     CallableType, Type, TypeVisitor, UnboundType, AnyType, Void, NoneTyp, TypeVarType,
     Instance, TupleType, UnionType, Overloaded, ErasedType, PartialType, DeletedType,
-    is_named_instance
+    TypeType, is_named_instance
 )
 from mypy.maptype import map_instance_to_supertype
 from mypy import nodes
@@ -348,12 +348,23 @@ class ConstraintBuilderVisitor(TypeVisitor[List[Constraint]]):
             res.extend(infer_constraints(t, AnyType(), self.direction))
         return res
 
-    def visit_overloaded(self, type: Overloaded) -> List[Constraint]:
+    def visit_overloaded(self, template: Overloaded) -> List[Constraint]:
         res = []  # type: List[Constraint]
-        for t in type.items():
+        for t in template.items():
             res.extend(infer_constraints(t, self.actual, self.direction))
         return res
 
+    def visit_type_type(self, template: TypeType) -> List[Constraint]:
+        if isinstance(self.actual, CallableType) and self.actual.is_type_obj():
+            return infer_constraints(template.item, self.actual.ret_type, self.direction)
+        elif isinstance(self.actual, Overloaded) and self.actual.is_type_obj():
+            return infer_constraints(template.item, self.actual.items()[0].ret_type,
+                                     self.direction)
+        elif isinstance(self.actual, TypeType):
+            return infer_constraints(template.item, self.actual.item, self.direction)
+        else:
+            return []
+
 
 def neg_op(op: int) -> int:
     """Map SubtypeOf to SupertypeOf and vice versa."""
diff --git a/mypy/erasetype.py b/mypy/erasetype.py
index 15ccd4f..e805f85 100644
--- a/mypy/erasetype.py
+++ b/mypy/erasetype.py
@@ -1,7 +1,9 @@
+from typing import Optional, Container
+
 from mypy.types import (
     Type, TypeVisitor, UnboundType, ErrorType, AnyType, Void, NoneTyp,
     Instance, TypeVarType, CallableType, TupleType, UnionType, Overloaded, ErasedType,
-    PartialType, DeletedType, TypeTranslator, TypeList
+    PartialType, DeletedType, TypeTranslator, TypeList, TypeType
 )
 
 
@@ -16,6 +18,7 @@ def erase_type(typ: Type) -> Type:
       B[X] -> B[Any]
       Tuple[A, B] -> tuple
       Callable[...] -> Callable[[], None]
+      Type[X] -> Type[Any]
     """
 
     return typ.accept(EraseTypeVisitor())
@@ -65,11 +68,14 @@ class EraseTypeVisitor(TypeVisitor[Type]):
         return t.items()[0].accept(self)
 
     def visit_tuple_type(self, t: TupleType) -> Type:
-        return t.fallback
+        return t.fallback.accept(self)
 
     def visit_union_type(self, t: UnionType) -> Type:
         return AnyType()        # XXX: return underlying type if only one?
 
+    def visit_type_type(self, t: TypeType) -> Type:
+        return TypeType(t.item.accept(self), line=t.line)
+
 
 def erase_generic_types(t: Type) -> Type:
     """Remove generic type arguments and type variables from a type.
@@ -96,13 +102,20 @@ class GenericTypeEraser(TypeTranslator):
         return Instance(t.type, [], t.line)
 
 
-def erase_typevars(t: Type) -> Type:
-    """Replace all type variables in a type with any."""
-    return t.accept(TypeVarEraser())
+def erase_typevars(t: Type, ids_to_erase: Optional[Container[int]] = None) -> Type:
+    """Replace all type variables in a type with any,
+    or just the ones in the provided collection.
+    """
+    return t.accept(TypeVarEraser(ids_to_erase))
 
 
 class TypeVarEraser(TypeTranslator):
     """Implementation of type erasure"""
 
+    def __init__(self, ids_to_erase: Optional[Container[int]]) -> None:
+        self.ids_to_erase = ids_to_erase
+
     def visit_type_var(self, t: TypeVarType) -> Type:
+        if self.ids_to_erase is not None and t.id not in self.ids_to_erase:
+            return t
         return AnyType()
diff --git a/mypy/errors.py b/mypy/errors.py
index c2fc663..b0a2c62 100644
--- a/mypy/errors.py
+++ b/mypy/errors.py
@@ -346,6 +346,13 @@ class CompileError(Exception):
         self.use_stdout = use_stdout
 
 
+class DecodeError(Exception):
+    """Exception raised when a file cannot be decoded due to an unknown encoding type.
+
+    Essentially a wrapper for the LookupError raised by `bytearray.decode`
+    """
+
+
 def remove_path_prefix(path: str, prefix: str) -> str:
     """If path starts with prefix, return copy of path with the prefix removed.
     Otherwise, return path. If path is None, return None.
diff --git a/mypy/expandtype.py b/mypy/expandtype.py
index 60730b5..e25190f 100644
--- a/mypy/expandtype.py
+++ b/mypy/expandtype.py
@@ -3,7 +3,7 @@ from typing import Dict, Tuple, List, cast
 from mypy.types import (
     Type, Instance, CallableType, TypeVisitor, UnboundType, ErrorType, AnyType,
     Void, NoneTyp, TypeVarType, Overloaded, TupleType, UnionType, ErasedType, TypeList,
-    PartialType, DeletedType
+    PartialType, DeletedType, TypeType
 )
 
 
@@ -94,6 +94,13 @@ class ExpandTypeVisitor(TypeVisitor[Type]):
     def visit_partial_type(self, t: PartialType) -> Type:
         return t
 
+    def visit_type_type(self, t: TypeType) -> Type:
+        # TODO: Verify that the new item type is valid (instance or
+        # union of instances or Any).  Sadly we can't report errors
+        # here yet.
+        item = t.item.accept(self)
+        return TypeType(item)
+
     def expand_types(self, types: List[Type]) -> List[Type]:
         a = []  # type: List[Type]
         for t in types:
diff --git a/mypy/fastparse.py b/mypy/fastparse.py
index 5e1e93a..6bcb12b 100644
--- a/mypy/fastparse.py
+++ b/mypy/fastparse.py
@@ -38,6 +38,9 @@ except ImportError:
 T = TypeVar('T')
 U = TypeVar('U')
 
+TYPE_COMMENT_SYNTAX_ERROR = 'syntax error in type comment'
+TYPE_COMMENT_AST_ERROR = 'invalid type comment'
+
 
 def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
           pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
@@ -56,19 +59,20 @@ def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
         else:
             ast2 = ast27.parse(source, fnam, 'exec')
             ast = conversions.py2to3(ast2)
-    except SyntaxError as e:
-        if errors:
-            errors.set_file('<input>' if fnam is None else fnam)
-            errors.report(e.lineno, e.msg)  # type: ignore
-        else:
-            raise
-    else:
+
         tree = ASTConverter(pyversion=pyversion,
+                            is_stub=is_stub_file,
                             custom_typing_module=custom_typing_module,
                             ).visit(ast)
         tree.path = fnam
         tree.is_stub = is_stub_file
         return tree
+    except (SyntaxError, TypeCommentParseError) as e:
+        if errors:
+            errors.set_file('<input>' if fnam is None else fnam)
+            errors.report(e.lineno, e.msg)
+        else:
+            raise
 
     return MypyFile([],
                     [],
@@ -78,9 +82,13 @@ def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
 
 
 def parse_type_comment(type_comment: str, line: int) -> Type:
-    typ = ast35.parse(type_comment, '<type_comment>', 'eval')
-    assert isinstance(typ, ast35.Expression)
-    return TypeConverter(line=line).visit(typ.body)
+    try:
+        typ = ast35.parse(type_comment, '<type_comment>', 'eval')
+    except SyntaxError:
+        raise TypeCommentParseError(TYPE_COMMENT_SYNTAX_ERROR, line)
+    else:
+        assert isinstance(typ, ast35.Expression)
+        return TypeConverter(line=line).visit(typ.body)
 
 
 def with_line(f: Callable[[Any, T], U]) -> Callable[[Any, T], U]:
@@ -100,11 +108,15 @@ def find(f: Callable[[T], bool], seq: Sequence[T]) -> T:
 
 
 class ASTConverter(ast35.NodeTransformer):
-    def __init__(self, pyversion: Tuple[int, int], custom_typing_module: str = None) -> None:
+    def __init__(self,
+                 pyversion: Tuple[int, int],
+                 is_stub: bool,
+                 custom_typing_module: str = None) -> None:
         self.class_nesting = 0
         self.imports = []  # type: List[ImportBase]
 
         self.pyversion = pyversion
+        self.is_stub = is_stub
         self.custom_typing_module = custom_typing_module
 
     def generic_visit(self, node: ast35.AST) -> None:
@@ -234,7 +246,10 @@ class ASTConverter(ast35.NodeTransformer):
         arg_names = [arg.variable.name() for arg in args]
         arg_types = None  # type: List[Type]
         if n.type_comment is not None:
-            func_type_ast = ast35.parse(n.type_comment, '<func_type>', 'func_type')
+            try:
+                func_type_ast = ast35.parse(n.type_comment, '<func_type>', 'func_type')
+            except SyntaxError:
+                raise TypeCommentParseError(TYPE_COMMENT_SYNTAX_ERROR, n.lineno)
             assert isinstance(func_type_ast, ast35.FunctionType)
             # for ellipsis arg
             if (len(func_type_ast.argtypes) == 1 and
@@ -644,16 +659,31 @@ class ASTConverter(ast35.NodeTransformer):
 
         raise RuntimeError('num not implemented for ' + str(type(n.n)))
 
-    # Str(string s) -- need to specify raw, unicode, etc?
+    # Str(string s)
     @with_line
     def visit_Str(self, n: ast35.Str) -> Node:
-        return StrExpr(n.s)
+        if self.pyversion[0] >= 3 or self.is_stub:
+            # Hack: assume all string literals in Python 2 stubs are normal
+            # strs (i.e. not unicode).  All stubs are parsed with the Python 3
+            # parser, which causes unprefixed string literals to be interpreted
+            # as unicode instead of bytes.  This hack is generally okay,
+            # because mypy considers str literals to be compatible with
+            # unicode.
+            return StrExpr(n.s)
+        else:
+            return UnicodeExpr(n.s)
 
     # Bytes(bytes s)
     @with_line
     def visit_Bytes(self, n: ast35.Bytes) -> Node:
-        # TODO: this is kind of hacky
-        return BytesExpr(str(n.s)[2:-1])
+        # The following line is a bit hacky, but is the best way to maintain
+        # compatibility with how mypy currently parses the contents of bytes literals.
+        contents = str(n.s)[2:-1]
+
+        if self.pyversion[0] >= 3:
+            return BytesExpr(contents)
+        else:
+            return StrExpr(contents)
 
     # NameConstant(singleton value)
     def visit_NameConstant(self, n: ast35.NameConstant) -> Node:
@@ -721,7 +751,7 @@ class TypeConverter(ast35.NodeTransformer):
         self.line = line
 
     def generic_visit(self, node: ast35.AST) -> None:
-        raise RuntimeError('Type node not implemented: ' + str(type(node)))
+        raise TypeCommentParseError(TYPE_COMMENT_AST_ERROR, self.line)
 
     def visit_NoneType(self, n: Any) -> Type:
         return None
@@ -774,3 +804,9 @@ class TypeConverter(ast35.NodeTransformer):
     # List(expr* elts, expr_context ctx)
     def visit_List(self, n: ast35.List) -> Type:
         return TypeList(self.visit_list(n.elts), line=self.line)
+
+
+class TypeCommentParseError(Exception):
+    def __init__(self, msg: str, lineno: int) -> None:
+        self.msg = msg
+        self.lineno = lineno
diff --git a/mypy/fixup.py b/mypy/fixup.py
index 134e611..73fb227 100644
--- a/mypy/fixup.py
+++ b/mypy/fixup.py
@@ -7,7 +7,8 @@ from mypy.nodes import (MypyFile, SymbolNode, SymbolTable, SymbolTableNode,
                         TypeVarExpr, ClassDef,
                         LDEF, MDEF, GDEF, MODULE_REF)
 from mypy.types import (CallableType, EllipsisType, Instance, Overloaded, TupleType,
-                        TypeList, TypeVarType, UnboundType, UnionType, TypeVisitor)
+                        TypeList, TypeVarType, UnboundType, UnionType, TypeVisitor,
+                        TypeType)
 from mypy.visitor import NodeVisitor
 
 
@@ -120,6 +121,7 @@ class NodeFixer(NodeVisitor[None]):
     def visit_type_var_expr(self, tv: TypeVarExpr) -> None:
         for value in tv.values:
             value.accept(self.type_fixer)
+        tv.upper_bound.accept(self.type_fixer)
 
     def visit_var(self, v: Var) -> None:
         if self.current_info is not None:
@@ -213,6 +215,9 @@ class TypeFixer(TypeVisitor[None]):
     def visit_void(self, o: Any) -> None:
         pass  # Nothing to descend into.
 
+    def visit_type_type(self, t: TypeType) -> None:
+        t.item.accept(self)
+
 
 def lookup_qualified(modules: Dict[str, MypyFile], name: str) -> SymbolNode:
     stnode = lookup_qualified_stnode(modules, name)
diff --git a/mypy/join.py b/mypy/join.py
index 2ae0360..0c42b64 100644
--- a/mypy/join.py
+++ b/mypy/join.py
@@ -5,7 +5,8 @@ from typing import cast, List
 from mypy.types import (
     Type, AnyType, NoneTyp, Void, TypeVisitor, Instance, UnboundType,
     ErrorType, TypeVarType, CallableType, TupleType, ErasedType, TypeList,
-    UnionType, FunctionLike, Overloaded, PartialType, DeletedType
+    UnionType, FunctionLike, Overloaded, PartialType, DeletedType,
+    TypeType
 )
 from mypy.maptype import map_instance_to_supertype
 from mypy.subtypes import is_subtype, is_equivalent, is_subtype_ignoring_tvars
@@ -130,6 +131,8 @@ class TypeJoinVisitor(TypeVisitor[Type]):
             return join_instances(t, self.s)
         elif isinstance(self.s, FunctionLike):
             return join_types(t, self.s.fallback)
+        elif isinstance(self.s, TypeType):
+            return join_types(t, self.s)
         else:
             return self.default(self.s)
 
@@ -204,6 +207,14 @@ class TypeJoinVisitor(TypeVisitor[Type]):
         # never get here.
         assert False, "Internal error"
 
+    def visit_type_type(self, t: TypeType) -> Type:
+        if isinstance(self.s, TypeType):
+            return TypeType(self.join(t.item, self.s.item), line=t.line)
+        elif isinstance(self.s, Instance) and self.s.type.fullname() == 'builtins.type':
+            return self.s
+        else:
+            return self.default(self.s)
+
     def join(self, s: Type, t: Type) -> Type:
         return join_types(s, t)
 
diff --git a/mypy/main.py b/mypy/main.py
index 7579f62..d405dd9 100644
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -149,6 +149,9 @@ def process_options() -> Tuple[List[BuildSource], Options]:
                         " or with incomplete type annotations")
     parser.add_argument('--check-untyped-defs', action='store_true',
                         help="type check the interior of functions without type annotations")
+    parser.add_argument('--warn-incomplete-stub', action='store_true',
+                        help="warn if missing type annotation in typeshed, only relevant with"
+                        " --check-untyped-defs enabled")
     parser.add_argument('--fast-parser', action='store_true',
                         help="enable experimental fast parser")
     parser.add_argument('-i', '--incremental', action='store_true',
@@ -243,6 +246,9 @@ def process_options() -> Tuple[List[BuildSource], Options]:
     if args.check_untyped_defs:
         options.build_flags.append(build.CHECK_UNTYPED_DEFS)
 
+    if args.warn_incomplete_stub:
+        options.build_flags.append(build.WARN_INCOMPLETE_STUB)
+
     # experimental
     if args.fast_parser:
         options.build_flags.append(build.FAST_PARSER)
diff --git a/mypy/meet.py b/mypy/meet.py
index 88b4d4f..eff2eed 100644
--- a/mypy/meet.py
+++ b/mypy/meet.py
@@ -3,7 +3,8 @@ from typing import cast, List
 from mypy.join import is_similar_callables, combine_similar_callables
 from mypy.types import (
     Type, AnyType, TypeVisitor, UnboundType, Void, ErrorType, NoneTyp, TypeVarType,
-    Instance, CallableType, TupleType, ErasedType, TypeList, UnionType, PartialType, DeletedType
+    Instance, CallableType, TupleType, ErasedType, TypeList,
+    UnionType, PartialType, DeletedType, TypeType
 )
 from mypy.subtypes import is_subtype
 from mypy.nodes import TypeInfo
@@ -43,7 +44,7 @@ def is_overlapping_types(t: Type, s: Type, use_promotions: bool = False) -> bool
     variables are erased at runtime and the overlapping check is based
     on runtime behavior.
 
-    If use_promitions is True, also consider type promotions (int and
+    If use_promotions is True, also consider type promotions (int and
     float would only be overlapping if it's True).
 
     This does not consider multiple inheritance. For example, A and B in
@@ -55,7 +56,7 @@ def is_overlapping_types(t: Type, s: Type, use_promotions: bool = False) -> bool
         class C(A, B): ...
 
     The rationale is that this case is usually very unlikely as multiple
-    inhreitance is rare. Also, we can't reliably determine whether
+    inheritance is rare. Also, we can't reliably determine whether
     multiple inheritance actually occurs somewhere in a program, due to
     stub files hiding implementation details, dynamic loading etc.
 
@@ -184,6 +185,8 @@ class TypeMeetVisitor(TypeVisitor[Type]):
                     return self.s
                 else:
                     return NoneTyp()
+        elif isinstance(self.s, TypeType):
+            return meet_types(t, self.s)
         else:
             return self.default(self.s)
 
@@ -207,6 +210,17 @@ class TypeMeetVisitor(TypeVisitor[Type]):
         # We can't determine the meet of partial types. We should never get here.
         assert False, 'Internal error'
 
+    def visit_type_type(self, t: TypeType) -> Type:
+        if isinstance(self.s, TypeType):
+            typ = self.meet(t.item, self.s.item)
+            if not isinstance(typ, NoneTyp):
+                typ = TypeType(typ, line=t.line)
+            return typ
+        elif isinstance(self.s, Instance) and self.s.type.fullname() == 'builtins.type':
+            return t
+        else:
+            return self.default(self.s)
+
     def meet(self, s, t):
         return meet_types(s, t)
 
diff --git a/mypy/messages.py b/mypy/messages.py
index 9d54849..2946910 100644
--- a/mypy/messages.py
+++ b/mypy/messages.py
@@ -11,7 +11,7 @@ from typing import cast, List, Dict, Any, Sequence, Iterable, Tuple
 from mypy.errors import Errors
 from mypy.types import (
     Type, CallableType, Instance, TypeVarType, TupleType, UnionType, Void, NoneTyp, AnyType,
-    Overloaded, FunctionLike, DeletedType
+    Overloaded, FunctionLike, DeletedType, TypeType
 )
 from mypy.nodes import (
     TypeInfo, Context, MypyFile, op_methods, FuncDef, reverse_type_aliases,
@@ -81,6 +81,7 @@ RETURN_TYPE_EXPECTED = "Function is missing a return type annotation"
 ARGUMENT_TYPE_EXPECTED = "Function is missing a type annotation for one or more arguments"
 KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE = \
     'Keyword argument only valid with "str" key type in call to "dict"'
+ALL_MUST_BE_SEQ_STR = 'Type of __all__ must be {}, not {}'
 
 
 class MessageBuilder:
@@ -140,7 +141,8 @@ class MessageBuilder:
     def report(self, msg: str, context: Context, severity: str, file: str = None) -> None:
         """Report an error or note (unless disabled)."""
         if self.disable_count <= 0:
-            self.errors.report(context.get_line(), msg.strip(), severity=severity, file=file)
+            self.errors.report(context.get_line() if context else -1,
+                               msg.strip(), severity=severity, file=file)
 
     def fail(self, msg: str, context: Context, file: str = None) -> None:
         """Report an error message (unless disabled)."""
@@ -263,6 +265,9 @@ class MessageBuilder:
             return '"Any"'
         elif isinstance(typ, DeletedType):
             return '<deleted>'
+        elif isinstance(typ, TypeType):
+            return 'Type[{}]'.format(
+                strip_quotes(self.format_simple(typ.item, verbosity)))
         elif typ is None:
             raise RuntimeError('Type is None')
         else:
@@ -288,7 +293,7 @@ class MessageBuilder:
     # Specific operations
     #
 
-    # The following operations are for genering specific error messages. They
+    # The following operations are for generating specific error messages. They
     # get some information as arguments, and they build an error message based
     # on them.
 
@@ -437,7 +442,12 @@ class MessageBuilder:
                 if n == 1:
                     self.invalid_index_type(arg_type, base, context)
                 else:
-                    self.fail(INCOMPATIBLE_TYPES_IN_ASSIGNMENT, context)
+                    msg = '{} (expression has type {}, target has type {})'
+                    arg_type_str, callee_type_str = self.format_distinctly(arg_type,
+                                                                           callee.arg_types[n - 1])
+                    self.fail(msg.format(INCOMPATIBLE_TYPES_IN_ASSIGNMENT,
+                                         arg_type_str, callee_type_str),
+                              context)
                 return
 
             target = 'to {} '.format(name)
@@ -818,6 +828,12 @@ class MessageBuilder:
     def invalid_signature(self, func_type: Type, context: Context) -> None:
         self.fail('Invalid signature "{}"'.format(func_type), context)
 
+    def reveal_type(self, typ: Type, context: Context) -> None:
+        self.fail('Revealed type is \'{}\''.format(typ), context)
+
+    def unsupported_type_type(self, item: Type, context: Context) -> None:
+        self.fail('Unsupported type Type[{}]'.format(self.format(item)), context)
+
 
 def capitalize(s: str) -> str:
     """Capitalize the first character of a string."""
diff --git a/mypy/nodes.py b/mypy/nodes.py
index cde6e0c..33613f3 100644
--- a/mypy/nodes.py
+++ b/mypy/nodes.py
@@ -308,7 +308,7 @@ class OverloadedFuncDef(FuncBase):
         self.set_line(items[0].line)
 
     def name(self) -> str:
-        return self.items[1].func.name()
+        return self.items[0].func.name()
 
     def accept(self, visitor: NodeVisitor[T]) -> T:
         return visitor.visit_overloaded_func_def(self)
@@ -719,7 +719,7 @@ class Block(Node):
 
 
 class ExpressionStmt(Node):
-    """An expression as a statament, such as print(s)."""
+    """An expression as a statement, such as print(s)."""
     expr = None  # type: Node
 
     def __init__(self, expr: Node) -> None:
@@ -961,6 +961,17 @@ class IntExpr(Node):
         return visitor.visit_int_expr(self)
 
 
+# How mypy uses StrExpr, BytesExpr, and UnicodeExpr:
+# In Python 2 mode:
+# b'x', 'x' -> StrExpr
+# u'x' -> UnicodeExpr
+# BytesExpr is unused
+#
+# In Python 3 mode:
+# b'x' -> BytesExpr
+# 'x', u'x' -> StrExpr
+# UnicodeExpr is unused
+
 class StrExpr(Node):
     """String literal"""
 
@@ -1368,6 +1379,18 @@ class CastExpr(Node):
         return visitor.visit_cast_expr(self)
 
 
+class RevealTypeExpr(Node):
+    """Reveal type expression reveal_type(expr)."""
+
+    expr = None  # type: Node
+
+    def __init__(self, expr: Node) -> None:
+        self.expr = expr
+
+    def accept(self, visitor: NodeVisitor[T]) -> T:
+        return visitor.visit_reveal_type_expr(self)
+
+
 class SuperExpr(Node):
     """Expression super().name"""
 
@@ -1713,6 +1736,8 @@ class TypeInfo(SymbolNode):
     names = None  # type: SymbolTable      # Names defined directly in this type
     is_abstract = False                    # Does the class have any abstract attributes?
     abstract_attributes = None  # type: List[str]
+    # Classes inheriting from Enum shadow their true members with a __getattr__, so we
+    # have to treat them as a special case.
     is_enum = False
     # If true, any unknown attributes should have type 'Any' instead
     # of generating a type error.  This would be true if there is a
diff --git a/mypy/parse.py b/mypy/parse.py
index ecf8e21..4cd3389 100644
--- a/mypy/parse.py
+++ b/mypy/parse.py
@@ -1285,7 +1285,7 @@ class Parser:
         # that in expr.
         s = self.current_str()
         if s == '(':
-            # Parerenthesised expression or cast.
+            # Parenthesised expression or cast.
             expr = self.parse_parentheses()
         elif s == '[':
             expr = self.parse_list_expr()
diff --git a/mypy/replacetvars.py b/mypy/replacetvars.py
index 675cc58..1ea5f83 100644
--- a/mypy/replacetvars.py
+++ b/mypy/replacetvars.py
@@ -11,7 +11,7 @@ def replace_type_vars(typ: Type, func_tvars: bool = True) -> Type:
 
 
 class ReplaceTypeVarsVisitor(TypeTranslator):
-    # Only override type variable handling; otherwise perform an indentity
+    # Only override type variable handling; otherwise perform an identity
     # transformation.
 
     func_tvars = False
diff --git a/mypy/sametypes.py b/mypy/sametypes.py
index bfe37a6..319af50 100644
--- a/mypy/sametypes.py
+++ b/mypy/sametypes.py
@@ -2,7 +2,8 @@ from typing import Sequence
 
 from mypy.types import (
     Type, UnboundType, ErrorType, AnyType, NoneTyp, Void, TupleType, UnionType, CallableType,
-    TypeVarType, Instance, TypeVisitor, ErasedType, TypeList, Overloaded, PartialType, DeletedType
+    TypeVarType, Instance, TypeVisitor, ErasedType, TypeList,
+    Overloaded, PartialType, DeletedType, TypeType
 )
 
 
@@ -121,3 +122,9 @@ class SameTypeVisitor(TypeVisitor[bool]):
         # A partial type is not fully defined, so the result is indeterminate. We shouldn't
         # get here.
         raise RuntimeError
+
+    def visit_type_type(self, left: TypeType) -> bool:
+        if isinstance(self.right, TypeType):
+            return is_same_type(left.item, self.right.item)
+        else:
+            return False
diff --git a/mypy/semanal.py b/mypy/semanal.py
index e19681d..414c0c3 100644
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -55,7 +55,7 @@ from mypy.nodes import (
     RaiseStmt, AssertStmt, OperatorAssignmentStmt, WhileStmt,
     ForStmt, BreakStmt, ContinueStmt, IfStmt, TryStmt, WithStmt, DelStmt,
     GlobalDecl, SuperExpr, DictExpr, CallExpr, RefExpr, OpExpr, UnaryExpr,
-    SliceExpr, CastExpr, TypeApplication, Context, SymbolTable,
+    SliceExpr, CastExpr, RevealTypeExpr, TypeApplication, Context, SymbolTable,
     SymbolTableNode, BOUND_TVAR, UNBOUND_TVAR, ListComprehension, GeneratorExpr,
     FuncExpr, MDEF, FuncBase, Decorator, SetExpr, TypeVarExpr,
     StrExpr, BytesExpr, PrintStmt, ConditionalExpr, PromoteExpr,
@@ -127,6 +127,11 @@ TYPE_PROMOTIONS_PYTHON2.update({
     'builtins.bytearray': 'builtins.str',
 })
 
+# Hard coded list of Enum baseclasses.
+ENUM_BASECLASSES = [
+    'enum.Enum',
+    'enum.IntEnum',
+]
 
 # When analyzing a function, should we analyze the whole function in one go, or
 # should we only perform one phase of the analysis? The latter is used for
@@ -168,7 +173,7 @@ class SemanticAnalyzer(NodeVisitor):
     type_stack = None  # type: List[TypeInfo]
     # Type variables that are bound by the directly enclosing class
     bound_tvars = None  # type: List[SymbolTableNode]
-    # Stack of type varialbes that were bound by outer classess
+    # Stack of type variables that were bound by outer classess
     tvar_stack = None  # type: List[List[SymbolTableNode]]
 
     # Stack of functions being analyzed
@@ -217,6 +222,7 @@ class SemanticAnalyzer(NodeVisitor):
         self.check_untyped_defs = check_untyped_defs
         self.postpone_nested_functions_stack = [FUNCTION_BOTH_PHASES]
         self.postponed_functions_stack = []
+        self.all_exports = set()  # type: Set[str]
 
     def visit_file(self, file_node: MypyFile, fnam: str) -> None:
         self.errors.set_file(fnam)
@@ -245,6 +251,11 @@ class SemanticAnalyzer(NodeVisitor):
 
         self.errors.set_ignored_lines(set())
 
+        if '__all__' in self.globals:
+            for name, g in self.globals.items():
+                if name not in self.all_exports:
+                    g.module_public = False
+
     def visit_func_def(self, defn: FuncDef) -> None:
         phase_info = self.postpone_nested_functions_stack[-1]
         if phase_info != FUNCTION_SECOND_PHASE:
@@ -328,7 +339,7 @@ class SemanticAnalyzer(NodeVisitor):
     def is_conditional_func(self, previous: Node, new: FuncDef) -> bool:
         """Does 'new' conditionally redefine 'previous'?
 
-        We reject straight redefinitions of functions, as they are usuallly
+        We reject straight redefinitions of functions, as they are usually
         a programming error. For example:
 
         . def f(): ...
@@ -427,7 +438,7 @@ class SemanticAnalyzer(NodeVisitor):
             self.add_local(defn, defn)
 
     def analyze_property_with_multi_part_definition(self, defn: OverloadedFuncDef) -> None:
-        """Analyze a propery defined using multiple methods (e.g., using @x.setter).
+        """Analyze a property defined using multiple methods (e.g., using @x.setter).
 
         Assume that the first method (@property) has already been analyzed.
         """
@@ -463,7 +474,6 @@ class SemanticAnalyzer(NodeVisitor):
             defn.type = self.anal_type(defn.type)
             self.check_function_signature(defn)
             if isinstance(defn, FuncDef):
-                defn.info = self.type
                 defn.type = set_callable_name(defn.type, defn)
         for arg in defn.arguments:
             if arg.initializer:
@@ -730,7 +740,7 @@ class SemanticAnalyzer(NodeVisitor):
     def analyze_base_classes(self, defn: ClassDef) -> None:
         """Analyze and set up base classes."""
         for base_expr in defn.base_type_exprs:
-            # The base class is originallly an expression; convert it to a type.
+            # The base class is originally an expression; convert it to a type.
             try:
                 base = self.expr_to_analyzed_type(base_expr)
             except TypeTranslationError:
@@ -756,7 +766,7 @@ class SemanticAnalyzer(NodeVisitor):
             elif not isinstance(base, UnboundType):
                 self.fail('Invalid base class', base_expr)
             if isinstance(base, Instance):
-                defn.info.is_enum = base.type.fullname() == 'enum.Enum'
+                defn.info.is_enum = self.decide_is_enum(base)
         # Add 'object' as implicit base if there is no other base class.
         if (not defn.base_types and defn.fullname != 'builtins.object'):
             obj = self.object_type()
@@ -820,6 +830,11 @@ class SemanticAnalyzer(NodeVisitor):
                     visited.add(base.type)
         return False
 
+    def decide_is_enum(self, instance: Instance) -> bool:
+        """Decide if a TypeInfo should be marked as .is_enum=True"""
+        fullname = instance.type.fullname()
+        return fullname in ENUM_BASECLASSES
+
     def analyze_metaclass(self, defn: ClassDef) -> None:
         if defn.metaclass:
             sym = self.lookup_qualified(defn.metaclass, defn)
@@ -1060,6 +1075,11 @@ class SemanticAnalyzer(NodeVisitor):
         self.process_typevar_declaration(s)
         self.process_namedtuple_definition(s)
 
+        if (len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr) and
+                s.lvalues[0].name == '__all__' and s.lvalues[0].kind == GDEF and
+                isinstance(s.rvalue, (ListExpr, TupleExpr))):
+            self.add_exports(*s.rvalue.items)
+
     def check_and_set_up_type_alias(self, s: AssignmentStmt) -> None:
         """Check if assignment creates a type alias and set it up as needed."""
         # For now, type aliases only work at the top level of a module.
@@ -1613,6 +1633,9 @@ class SemanticAnalyzer(NodeVisitor):
                                        s: OperatorAssignmentStmt) -> None:
         s.lvalue.accept(self)
         s.rvalue.accept(self)
+        if (isinstance(s.lvalue, NameExpr) and s.lvalue.name == '__all__' and
+                s.lvalue.kind == GDEF and isinstance(s.rvalue, (ListExpr, TupleExpr))):
+            self.add_exports(*s.rvalue.items)
 
     def visit_while_stmt(self, s: WhileStmt) -> None:
         s.expr.accept(self)
@@ -1795,6 +1818,12 @@ class SemanticAnalyzer(NodeVisitor):
             expr.analyzed = CastExpr(expr.args[1], target)
             expr.analyzed.line = expr.line
             expr.analyzed.accept(self)
+        elif refers_to_fullname(expr.callee, 'builtins.reveal_type'):
+            if not self.check_fixed_args(expr, 1, 'reveal_type'):
+                return
+            expr.analyzed = RevealTypeExpr(expr.args[0])
+            expr.analyzed.line = expr.line
+            expr.analyzed.accept(self)
         elif refers_to_fullname(expr.callee, 'typing.Any'):
             # Special form Any(...).
             if not self.check_fixed_args(expr, 1, 'Any'):
@@ -1822,6 +1851,17 @@ class SemanticAnalyzer(NodeVisitor):
             for a in expr.args:
                 a.accept(self)
 
+            if (isinstance(expr.callee, MemberExpr) and
+                    isinstance(expr.callee.expr, NameExpr) and
+                    expr.callee.expr.name == '__all__' and
+                    expr.callee.expr.kind == GDEF and
+                    expr.callee.name in ('append', 'extend')):
+                if expr.callee.name == 'append' and expr.args:
+                    self.add_exports(expr.args[0])
+                elif (expr.callee.name == 'extend' and expr.args and
+                        isinstance(expr.args[0], (ListExpr, TupleExpr))):
+                    self.add_exports(*expr.args[0].items)
+
     def translate_dict_call(self, call: CallExpr) -> Optional[DictExpr]:
         """Translate 'dict(x=y, ...)' to {'x': y, ...}.
 
@@ -1932,6 +1972,9 @@ class SemanticAnalyzer(NodeVisitor):
         expr.expr.accept(self)
         expr.type = self.anal_type(expr.type)
 
+    def visit_reveal_type_expr(self, expr: RevealTypeExpr) -> None:
+        expr.expr.accept(self)
+
     def visit_type_application(self, expr: TypeApplication) -> None:
         expr.expr.accept(self)
         for i in range(len(expr.types)):
@@ -2188,12 +2231,19 @@ class SemanticAnalyzer(NodeVisitor):
         node._fullname = name
         self.locals[-1][name] = SymbolTableNode(LDEF, node)
 
+    def add_exports(self, *exps: Node) -> None:
+        for exp in exps:
+            if isinstance(exp, StrExpr):
+                self.all_exports.add(exp.value)
+
     def check_no_global(self, n: str, ctx: Context,
-                        is_func: bool = False) -> None:
+                        is_overloaded_func: bool = False) -> None:
         if n in self.globals:
-            if is_func and isinstance(self.globals[n].node, FuncDef):
-                self.fail(("Name '{}' already defined (overload variants "
-                           "must be next to each other)").format(n), ctx)
+            prev_is_overloaded = isinstance(self.globals[n], OverloadedFuncDef)
+            if is_overloaded_func and prev_is_overloaded:
+                self.fail("Nonconsecutive overload {} found".format(n), ctx)
+            elif prev_is_overloaded:
+                self.fail("Definition of '{}' missing 'overload'".format(n), ctx)
             else:
                 self.name_already_defined(n, ctx)
 
@@ -2284,6 +2334,8 @@ class FirstPass(NodeVisitor):
         if mod_id == 'builtins':
             literal_types = [
                 ('None', NoneTyp()),
+                # reveal_type is a mypy-only function that gives an error with the type of its arg
+                ('reveal_type', AnyType()),
             ]  # type: List[Tuple[str, Type]]
 
             # TODO(ddfisher): This guard is only needed because mypy defines
@@ -2332,12 +2384,12 @@ class FirstPass(NodeVisitor):
                 func.original_def = cast(FuncDef, original_def)
             else:
                 # Report error.
-                sem.check_no_global(func.name(), func, True)
+                sem.check_no_global(func.name(), func)
         else:
             sem.globals[func.name()] = SymbolTableNode(GDEF, func, sem.cur_mod_id)
 
     def visit_overloaded_func_def(self, func: OverloadedFuncDef) -> None:
-        self.sem.check_no_global(func.name(), func)
+        self.sem.check_no_global(func.name(), func, True)
         func._fullname = self.sem.qualified_name(func.name())
         self.sem.globals[func.name()] = SymbolTableNode(GDEF, func,
                                                         self.sem.cur_mod_id)
@@ -2383,9 +2435,16 @@ class FirstPass(NodeVisitor):
                 # If the previous symbol is a variable, this should take precedence.
                 self.sem.globals[imported_id] = SymbolTableNode(UNBOUND_IMPORTED, None)
 
+    def visit_while_stmt(self, s: WhileStmt) -> None:
+        s.body.accept(self)
+        if s.else_body:
+            s.else_body.accept(self)
+
     def visit_for_stmt(self, s: ForStmt) -> None:
         self.analyze_lvalue(s.index)
         s.body.accept(self)
+        if s.else_body:
+            s.else_body.accept(self)
 
     def visit_with_stmt(self, s: WithStmt) -> None:
         for n in s.target:
@@ -2514,6 +2573,9 @@ class ThirdPass(TraverserVisitor[None]):
         self.analyze(e.type)
         super().visit_cast_expr(e)
 
+    def visit_reveal_type_expr(self, e: RevealTypeExpr) -> None:
+        super().visit_reveal_type_expr(e)
+
     def visit_type_application(self, e: TypeApplication) -> None:
         for type in e.types:
             self.analyze(type)
diff --git a/mypy/solve.py b/mypy/solve.py
index cc04917..a2cfa28 100644
--- a/mypy/solve.py
+++ b/mypy/solve.py
@@ -23,7 +23,7 @@ def solve_constraints(vars: List[int], constraints: List[Constraint],
     # Collect a list of constraints for each type variable.
     cmap = {}  # type: Dict[int, List[Constraint]]
     for con in constraints:
-        a = cmap.get(con.type_var, [])
+        a = cmap.get(con.type_var, [])  # type: List[Constraint]
         a.append(con)
         cmap[con.type_var] = a
 
@@ -34,7 +34,7 @@ def solve_constraints(vars: List[int], constraints: List[Constraint],
         bottom = None  # type: Type
         top = None  # type: Type
 
-        # Process each contraint separely, and calculate the lower and upper
+        # Process each constraint separately, and calculate the lower and upper
         # bounds based on constraints. Note that we assume that the constraint
         # targets do not have constraint references.
         for c in cmap.get(tvar, []):
diff --git a/mypy/strconv.py b/mypy/strconv.py
index 7276491..fe7937c 100644
--- a/mypy/strconv.py
+++ b/mypy/strconv.py
@@ -372,6 +372,9 @@ class StrConv(NodeVisitor[str]):
     def visit_cast_expr(self, o):
         return self.dump([o.expr, o.type], o)
 
+    def visit_reveal_type_expr(self, o):
+        return self.dump([o.expr], o)
+
     def visit_unary_expr(self, o):
         return self.dump([o.op, o.expr], o)
 
diff --git a/mypy/stubgen.py b/mypy/stubgen.py
index 81e8dc4..972278f 100644
--- a/mypy/stubgen.py
+++ b/mypy/stubgen.py
@@ -330,29 +330,34 @@ class StubGenerator(mypy.traverser.TraverserVisitor):
         return base_types
 
     def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
-        lvalue = o.lvalues[0]
-        if isinstance(lvalue, NameExpr) and self.is_namedtuple(o.rvalue):
-            self.process_namedtuple(lvalue, o.rvalue)
-            return
-        if isinstance(lvalue, TupleExpr):
-            items = lvalue.items
-        elif isinstance(lvalue, ListExpr):
-            items = lvalue.items
-        else:
-            items = [lvalue]
-        sep = False
-        found = False
-        for item in items:
-            if isinstance(item, NameExpr):
-                init = self.get_init(item.name)
-                if init:
-                    found = True
-                    if not sep and not self._indent and self._state not in (EMPTY, VAR):
-                        init = '\n' + init
-                        sep = True
-                    self.add(init)
-                    self.record_name(item.name)
-        if found:
+        foundl = []
+
+        for lvalue in o.lvalues:
+            if isinstance(lvalue, NameExpr) and self.is_namedtuple(o.rvalue):
+                self.process_namedtuple(lvalue, o.rvalue)
+                continue
+            if isinstance(lvalue, TupleExpr):
+                items = lvalue.items
+            elif isinstance(lvalue, ListExpr):
+                items = lvalue.items
+            else:
+                items = [lvalue]
+            sep = False
+            found = False
+            for item in items:
+                if isinstance(item, NameExpr):
+                    init = self.get_init(item.name)
+                    if init:
+                        found = True
+                        if not sep and not self._indent and \
+                           self._state not in (EMPTY, VAR):
+                            init = '\n' + init
+                            sep = True
+                        self.add(init)
+                        self.record_name(item.name)
+            foundl.append(found)
+
+        if all(foundl):
             self._state = VAR
 
     def is_namedtuple(self, expr: Node) -> bool:
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
index 46db522..ea47c3f 100644
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -3,7 +3,7 @@ from typing import cast, List, Dict, Callable
 from mypy.types import (
     Type, AnyType, UnboundType, TypeVisitor, ErrorType, Void, NoneTyp,
     Instance, TypeVarType, CallableType, TupleType, UnionType, Overloaded, ErasedType, TypeList,
-    PartialType, DeletedType, is_named_instance
+    PartialType, DeletedType, TypeType, is_named_instance
 )
 import mypy.applytype
 import mypy.constraints
@@ -145,6 +145,9 @@ class SubtypeVisitor(TypeVisitor[bool]):
                        for item in right.items())
         elif isinstance(right, Instance):
             return is_subtype(left.fallback, right)
+        elif isinstance(right, TypeType):
+            # This is unsound, we don't check the __init__ signature.
+            return left.is_type_obj() and is_subtype(left.ret_type, right.item)
         else:
             return False
 
@@ -198,6 +201,11 @@ class SubtypeVisitor(TypeVisitor[bool]):
             return True
         elif isinstance(right, UnboundType):
             return True
+        elif isinstance(right, TypeType):
+            # All the items must have the same type object status, so
+            # it's sufficient to query only (any) one of them.
+            # This is unsound, we don't check the __init__ signature.
+            return left.is_type_obj() and is_subtype(left.items()[0].ret_type, right.item)
         else:
             return False
 
@@ -209,6 +217,20 @@ class SubtypeVisitor(TypeVisitor[bool]):
         # This is indeterminate as we don't really know the complete type yet.
         raise RuntimeError
 
+    def visit_type_type(self, left: TypeType) -> bool:
+        right = self.right
+        if isinstance(right, TypeType):
+            return is_subtype(left.item, right.item)
+        if isinstance(right, CallableType):
+            # This is unsound, we don't check the __init__ signature.
+            return right.is_type_obj() and is_subtype(left.item, right.ret_type)
+        if (isinstance(right, Instance) and
+                right.type.fullname() in ('builtins.type', 'builtins.object')):
+            # Treat builtins.type the same as Type[Any];
+            # treat builtins.object the same as Any.
+            return True
+        return False
+
 
 def is_callable_subtype(left: CallableType, right: CallableType,
                         ignore_return: bool = False) -> bool:
diff --git a/mypy/traverser.py b/mypy/traverser.py
index d91c6e7..f49100a 100644
--- a/mypy/traverser.py
+++ b/mypy/traverser.py
@@ -7,7 +7,7 @@ from mypy.nodes import (
     Block, MypyFile, FuncItem, CallExpr, ClassDef, Decorator, FuncDef,
     ExpressionStmt, AssignmentStmt, OperatorAssignmentStmt, WhileStmt,
     ForStmt, ReturnStmt, AssertStmt, DelStmt, IfStmt, RaiseStmt,
-    TryStmt, WithStmt, MemberExpr, OpExpr, SliceExpr, CastExpr,
+    TryStmt, WithStmt, MemberExpr, OpExpr, SliceExpr, CastExpr, RevealTypeExpr,
     UnaryExpr, ListExpr, TupleExpr, DictExpr, SetExpr, IndexExpr,
     GeneratorExpr, ListComprehension, ConditionalExpr, TypeApplication,
     FuncExpr, ComparisonExpr, OverloadedFuncDef, YieldFromExpr,
@@ -21,10 +21,10 @@ T = TypeVar('T')
 class TraverserVisitor(NodeVisitor[T], Generic[T]):
     """A parse tree visitor that traverses the parse tree during visiting.
 
-    It does not peform any actions outside the travelsal. Subclasses
+    It does not peform any actions outside the traversal. Subclasses
     should override visit methods to perform actions during
-    travelsal. Calling the superclass method allows reusing the
-    travelsal implementation.
+    traversal. Calling the superclass method allows reusing the
+    traversal implementation.
     """
 
     # Visit methods
@@ -169,6 +169,9 @@ class TraverserVisitor(NodeVisitor[T], Generic[T]):
     def visit_cast_expr(self, o: CastExpr) -> T:
         o.expr.accept(self)
 
+    def visit_reveal_type_expr(self, o: RevealTypeExpr) -> T:
+        o.expr.accept(self)
+
     def visit_unary_expr(self, o: UnaryExpr) -> T:
         o.expr.accept(self)
 
diff --git a/mypy/treetransform.py b/mypy/treetransform.py
index 5ae8cc4..ed74064 100644
--- a/mypy/treetransform.py
+++ b/mypy/treetransform.py
@@ -11,7 +11,7 @@ from mypy.nodes import (
     OperatorAssignmentStmt, ExpressionStmt, AssignmentStmt, ReturnStmt,
     RaiseStmt, AssertStmt, DelStmt, BreakStmt, ContinueStmt,
     PassStmt, GlobalDecl, WhileStmt, ForStmt, IfStmt, TryStmt, WithStmt,
-    CastExpr, TupleExpr, GeneratorExpr, ListComprehension, ListExpr,
+    CastExpr, RevealTypeExpr, TupleExpr, GeneratorExpr, ListComprehension, ListExpr,
     ConditionalExpr, DictExpr, SetExpr, NameExpr, IntExpr, StrExpr, BytesExpr,
     UnicodeExpr, FloatExpr, CallExpr, SuperExpr, MemberExpr, IndexExpr,
     SliceExpr, OpExpr, UnaryExpr, FuncExpr, TypeApplication, PrintStmt,
@@ -363,6 +363,9 @@ class TransformVisitor(NodeVisitor[Node]):
         return CastExpr(self.node(node.expr),
                         self.type(node.type))
 
+    def visit_reveal_type_expr(self, node: RevealTypeExpr) -> Node:
+        return RevealTypeExpr(self.node(node.expr))
+
     def visit_super_expr(self, node: SuperExpr) -> Node:
         new = SuperExpr(node.name)
         new.info = node.info
diff --git a/mypy/typeanal.py b/mypy/typeanal.py
index 6de132d..6a7ef29 100644
--- a/mypy/typeanal.py
+++ b/mypy/typeanal.py
@@ -5,7 +5,7 @@ from typing import Callable, cast, List, Tuple
 from mypy.types import (
     Type, UnboundType, TypeVarType, TupleType, UnionType, Instance, AnyType, CallableType,
     Void, NoneTyp, DeletedType, TypeList, TypeVarDef, TypeVisitor, StarType, PartialType,
-    EllipsisType
+    EllipsisType, TypeType
 )
 from mypy.nodes import (
     BOUND_TVAR, TYPE_ALIAS, UNBOUND_IMPORTED,
@@ -18,7 +18,7 @@ from mypy.subtypes import satisfies_upper_bound
 from mypy import nodes
 
 
-type_constructors = ['typing.Tuple', 'typing.Union', 'typing.Callable']
+type_constructors = {'typing.Tuple', 'typing.Union', 'typing.Callable', 'typing.Type'}
 
 
 def analyze_type_alias(node: Node,
@@ -100,8 +100,7 @@ class TypeAnalyser(TypeVisitor[Type]):
                     node = self.lookup_fqn_func('builtins.tuple')
                     info = cast(TypeInfo, node.node)
                     return Instance(info, [t.args[0].accept(self)], t.line)
-                return TupleType(self.anal_array(t.args),
-                                 self.builtin_type('builtins.tuple'))
+                return self.tuple_type(self.anal_array(t.args))
             elif fullname == 'typing.Union':
                 items = self.anal_array(t.args)
                 items = [item for item in items if not isinstance(item, Void)]
@@ -109,11 +108,20 @@ class TypeAnalyser(TypeVisitor[Type]):
             elif fullname == 'typing.Optional':
                 if len(t.args) != 1:
                     self.fail('Optional[...] must have exactly one type argument', t)
+                    return AnyType()
                 items = self.anal_array(t.args)
                 # Currently Optional[t] is just an alias for t.
                 return items[0]
             elif fullname == 'typing.Callable':
                 return self.analyze_callable_type(t)
+            elif fullname == 'typing.Type':
+                if len(t.args) == 0:
+                    return TypeType(AnyType(), line=t.line)
+                if len(t.args) != 1:
+                    self.fail('Type[...] must have exactly one type argument', t)
+                items = self.anal_array(t.args)
+                item = items[0]
+                return TypeType(item, line=t.line)
             elif sym.kind == TYPE_ALIAS:
                 # TODO: Generic type aliases.
                 return sym.type_override
@@ -191,7 +199,7 @@ class TypeAnalyser(TypeVisitor[Type]):
         if star_count > 1:
             self.fail('At most one star type allowed in a tuple', t)
             return AnyType()
-        fallback = t.fallback if t.fallback else self.builtin_type('builtins.tuple')
+        fallback = t.fallback if t.fallback else self.builtin_type('builtins.tuple', [AnyType()])
         return TupleType(self.anal_array(t.items), fallback, t.line)
 
     def visit_star_type(self, t: StarType) -> Type:
@@ -207,15 +215,19 @@ class TypeAnalyser(TypeVisitor[Type]):
         self.fail("Unexpected '...'", t)
         return AnyType()
 
+    def visit_type_type(self, t: TypeType) -> Type:
+        return TypeType(t.item.accept(self), line=t.line)
+
     def analyze_callable_type(self, t: UnboundType) -> Type:
         fallback = self.builtin_type('builtins.function')
         if len(t.args) == 0:
-            # Callable (bare)
+            # Callable (bare). Treat as Callable[..., Any].
             return CallableType([AnyType(), AnyType()],
                                 [nodes.ARG_STAR, nodes.ARG_STAR2],
                                 [None, None],
                                 ret_type=AnyType(),
-                                fallback=fallback)
+                                fallback=fallback,
+                                is_ellipsis_args=True)
         elif len(t.args) == 2:
             ret_type = t.args[1].accept(self)
             if isinstance(t.args[0], TypeList):
@@ -256,10 +268,13 @@ class TypeAnalyser(TypeVisitor[Type]):
                                 vd.line))
         return a
 
-    def builtin_type(self, fully_qualified_name: str) -> Instance:
+    def builtin_type(self, fully_qualified_name: str, args: List[Type] = None) -> Instance:
         node = self.lookup_fqn_func(fully_qualified_name)
         info = cast(TypeInfo, node.node)
-        return Instance(info, [])
+        return Instance(info, args or [])
+
+    def tuple_type(self, items: List[Type]) -> TupleType:
+        return TupleType(items, fallback=self.builtin_type('builtins.tuple', [AnyType()]))
 
 
 class TypeAnalyserPass3(TypeVisitor[None]):
@@ -270,7 +285,7 @@ class TypeAnalyserPass3(TypeVisitor[None]):
     Perform these operations:
 
      * Report error for invalid type argument counts, such as List[x, y].
-     * Make implicit Any type argumenents explicit my modifying types
+     * Make implicit Any type arguments explicit my modifying types
        in-place. For example, modify Foo into Foo[Any] if Foo expects a single
        type argument.
      * If a type variable has a value restriction, ensure that the value is
@@ -380,3 +395,6 @@ class TypeAnalyserPass3(TypeVisitor[None]):
 
     def visit_partial_type(self, t: PartialType) -> None:
         pass
+
+    def visit_type_type(self, t: TypeType) -> None:
+        pass
diff --git a/mypy/typefixture.py b/mypy/typefixture.py
index ffd1e84..ec76cf8 100644
--- a/mypy/typefixture.py
+++ b/mypy/typefixture.py
@@ -6,7 +6,8 @@ It contains class TypeInfos and Type objects.
 from typing import List
 
 from mypy.types import (
-    TypeVarType, AnyType, Void, ErrorType, NoneTyp, Instance, CallableType, TypeVarDef
+    TypeVarType, AnyType, Void, ErrorType, NoneTyp, Instance, CallableType, TypeVarDef,
+    TypeType,
 )
 from mypy.nodes import (
     TypeInfo, ClassDef, Block, ARG_POS, ARG_OPT, ARG_STAR, SymbolTable,
@@ -140,6 +141,13 @@ class TypeFixture:
         self.lsta = Instance(self.std_listi, [self.a])  # List[A]
         self.lstb = Instance(self.std_listi, [self.b])  # List[B]
 
+        self.type_a = TypeType(self.a)
+        self.type_b = TypeType(self.b)
+        self.type_c = TypeType(self.c)
+        self.type_d = TypeType(self.d)
+        self.type_t = TypeType(self.t)
+        self.type_any = TypeType(self.anyt)
+
     # Helper methods
 
     def callable(self, *a):
diff --git a/mypy/types.py b/mypy/types.py
index 1d2c231..92b8659 100644
--- a/mypy/types.py
+++ b/mypy/types.py
@@ -783,6 +783,53 @@ class EllipsisType(Type):
         return EllipsisType()
 
 
+class TypeType(Type):
+    """For types like Type[User].
+
+    This annotates variables that are class objects, constrained by
+    the type argument.  See PEP 484 for more details.
+
+    We may encounter expressions whose values are specific classes;
+    those are represented as callables (possibly overloaded)
+    corresponding to the class's constructor's signature and returning
+    an instance of that class.  The difference with Type[C] is that
+    those callables always represent the exact class given as the
+    return type; Type[C] represents any class that's a subclass of C,
+    and C may also be a type variable or a union (or Any).
+
+    Many questions around subtype relationships between Type[C1] and
+    def(...) -> C2 are answered by looking at the subtype
+    relationships between C1 and C2, since Type[] is considered
+    covariant.
+
+    There's an unsolved problem with constructor signatures (also
+    unsolved in PEP 484): calling a variable whose type is Type[C]
+    assumes the constructor signature for C, even though a subclass of
+    C might completely change the constructor signature.  For now we
+    just assume that users of Type[C] are careful not to do that (in
+    the future we might detect when they are violating that
+    assumption).
+    """
+
+    # This can't be everything, but it can be a class reference,
+    # a generic class instance, a union, Any, a type variable...
+    item = None  # type: Type
+
+    def __init__(self, item: Type, *, line: int = -1) -> None:
+        super().__init__(line)
+        self.item = item
+
+    def accept(self, visitor: 'TypeVisitor[T]') -> T:
+        return visitor.visit_type_type(self)
+
+    def serialize(self) -> JsonDict:
+        return {'.class': 'TypeType', 'item': self.item.serialize()}
+
+    def deserialize(self, data: JsonDict) -> 'TypeType':
+        assert data['.class'] == 'TypeType'
+        return TypeType(Type.deserialize(data['item']))
+
+
 #
 # Visitor-related classes
 #
@@ -794,9 +841,9 @@ class TypeVisitor(Generic[T]):
     The parameter T is the return type of the visit methods.
     """
 
-    def _notimplemented_helper(self) -> NotImplementedError:
-        return NotImplementedError("Method visit_type_list not implemented in "
-                                   + "'{}'\n".format(type(self).__name__)
+    def _notimplemented_helper(self, name: str) -> NotImplementedError:
+        return NotImplementedError("Method {}.visit_{}() not implemented\n"
+                                   .format(type(self).__name__, name)
                                    + "This is a known bug, track development in "
                                    + "'https://github.com/JukkaL/mypy/issues/730'")
 
@@ -805,10 +852,10 @@ class TypeVisitor(Generic[T]):
         pass
 
     def visit_type_list(self, t: TypeList) -> T:
-        raise self._notimplemented_helper()
+        raise self._notimplemented_helper('type_list')
 
     def visit_error_type(self, t: ErrorType) -> T:
-        raise self._notimplemented_helper()
+        raise self._notimplemented_helper('error_type')
 
     @abstractmethod
     def visit_any(self, t: AnyType) -> T:
@@ -823,7 +870,7 @@ class TypeVisitor(Generic[T]):
         pass
 
     def visit_erased_type(self, t: ErasedType) -> T:
-        raise self._notimplemented_helper()
+        raise self._notimplemented_helper('erased_type')
 
     @abstractmethod
     def visit_deleted_type(self, t: DeletedType) -> T:
@@ -842,14 +889,14 @@ class TypeVisitor(Generic[T]):
         pass
 
     def visit_overloaded(self, t: Overloaded) -> T:
-        raise self._notimplemented_helper()
+        raise self._notimplemented_helper('overloaded')
 
     @abstractmethod
     def visit_tuple_type(self, t: TupleType) -> T:
         pass
 
     def visit_star_type(self, t: StarType) -> T:
-        raise self._notimplemented_helper()
+        raise self._notimplemented_helper('star_type')
 
     @abstractmethod
     def visit_union_type(self, t: UnionType) -> T:
@@ -860,7 +907,11 @@ class TypeVisitor(Generic[T]):
         pass
 
     def visit_ellipsis_type(self, t: EllipsisType) -> T:
-        raise self._notimplemented_helper()
+        raise self._notimplemented_helper('ellipsis_type')
+
+    @abstractmethod
+    def visit_type_type(self, t: TypeType) -> T:
+        pass
 
 
 class TypeTranslator(TypeVisitor[Type]):
@@ -939,6 +990,9 @@ class TypeTranslator(TypeVisitor[Type]):
                 raise RuntimeError('CallableType expectected, but got {}'.format(type(new)))
         return Overloaded(items=items)
 
+    def visit_type_type(self, t: TypeType) -> Type:
+        return TypeType(t.item.accept(self), line=t.line)
+
 
 class TypeStrVisitor(TypeVisitor[str]):
     """Visitor for pretty-printing types into strings.
@@ -1060,6 +1114,9 @@ class TypeStrVisitor(TypeVisitor[str]):
     def visit_ellipsis_type(self, t):
         return '...'
 
+    def visit_type_type(self, t):
+        return 'Type[{}]'.format(t.item.accept(self))
+
     def list_str(self, a):
         """Convert items of an array to strings (pretty-print types)
         and join the results with commas.
@@ -1149,6 +1206,9 @@ class TypeQuery(TypeVisitor[bool]):
     def visit_overloaded(self, t: Overloaded) -> bool:
         return self.query_types(t.items())
 
+    def visit_type_type(self, t: TypeType) -> bool:
+        return t.item.accept(self)
+
     def query_types(self, types: Sequence[Type]) -> bool:
         """Perform a query for a list of types.
 
diff --git a/mypy/version.py b/mypy/version.py
index f0ede3d..a987347 100644
--- a/mypy/version.py
+++ b/mypy/version.py
@@ -1 +1 @@
-__version__ = '0.4.1'
+__version__ = '0.4.2'
diff --git a/mypy/visitor.py b/mypy/visitor.py
index 717e004..b1e1b88 100644
--- a/mypy/visitor.py
+++ b/mypy/visitor.py
@@ -165,6 +165,9 @@ class NodeVisitor(Generic[T]):
     def visit_cast_expr(self, o: 'mypy.nodes.CastExpr') -> T:
         pass
 
+    def visit_reveal_type_expr(self, o: 'mypy.nodes.RevealTypeExpr') -> T:
+        pass
+
     def visit_super_expr(self, o: 'mypy.nodes.SuperExpr') -> T:
         pass
 
diff --git a/mypy/waiter.py b/mypy/waiter.py
index 50a949f..4bb6665 100644
--- a/mypy/waiter.py
+++ b/mypy/waiter.py
@@ -31,28 +31,12 @@ class LazySubprocess:
         self.end_time = None  # type: float
 
     def start(self) -> None:
-        self.outfile = tempfile.NamedTemporaryFile()
+        self.outfile = tempfile.TemporaryFile()
         self.start_time = time.time()
         self.process = Popen(self.args, cwd=self.cwd, env=self.env,
                              stdout=self.outfile, stderr=STDOUT)
         self.pid = self.process.pid
 
-    def handle_exit_status(self, status: int) -> None:
-        """Update process exit status received via an external os.waitpid() call."""
-        # Inlined subprocess._handle_exitstatus, it's not a public API.
-        # TODO(jukka): I'm not quite sure why this is implemented like this.
-        self.end_time = time.time()
-        process = self.process
-        assert process.returncode is None
-        if os.WIFSIGNALED(status):
-            process.returncode = -os.WTERMSIG(status)
-        elif os.WIFEXITED(status):
-            process.returncode = os.WEXITSTATUS(status)
-        else:
-            # Should never happen
-            raise RuntimeError("Unknown child exit status!")
-        assert process.returncode is not None
-
     def wait(self) -> int:
         return self.process.wait()
 
@@ -60,13 +44,10 @@ class LazySubprocess:
         return self.process.returncode
 
     def read_output(self) -> str:
-        with open(self.outfile.name, 'rb') as file:
-            # Assume it's ascii to avoid unicode headaches (and portability issues).
-            return file.read().decode('ascii')
-
-    def cleanup(self) -> None:
-        self.outfile.close()
-        assert not os.path.exists(self.outfile.name)
+        file = self.outfile
+        file.seek(0)
+        # Assume it's ascii to avoid unicode headaches (and portability issues).
+        return file.read().decode('ascii')
 
     @property
     def elapsed_time(self) -> float:
@@ -178,17 +159,25 @@ class Waiter:
         name2 = re.sub('( .*?) .*', r'\1', name)  # First two words.
         self.times2[name2] = elapsed_time + self.times2.get(name2, 0)
 
+    def _poll_current(self) -> Tuple[int, int]:
+        while True:
+            time.sleep(.25)
+            for pid in self.current:
+                cmd = self.current[pid][1]
+                code = cmd.process.poll()
+                if code is not None:
+                    cmd.end_time = time.time()
+                    return pid, code
+
     def _wait_next(self) -> Tuple[List[str], int, int]:
         """Wait for a single task to finish.
 
         Return tuple (list of failed tasks, number test cases, number of failed tests).
         """
-        pid, status = os.waitpid(-1, 0)
+        pid, status = self._poll_current()
         num, cmd = self.current.pop(pid)
         name = cmd.name
 
-        cmd.handle_exit_status(status)
-
         self._record_time(cmd.name, cmd.elapsed_time)
 
         rc = cmd.wait()
@@ -223,7 +212,6 @@ class Waiter:
 
         # Get task output.
         output = cmd.read_output()
-        cmd.cleanup()
         num_tests, num_tests_failed = parse_test_stats_from_output(output, fail_type)
 
         if fail_type is not None or self.verbosity >= 1:
diff --git a/scripts/pyxlslave.py~ b/scripts/pyxlslave.py~
deleted file mode 100644
index fe5c346..0000000
--- a/scripts/pyxlslave.py~
+++ /dev/null
@@ -1,24 +0,0 @@
-"""Python 2 process that can pyxl decode arbitary files.
-
-This is long-running process for better performance. It
-can process multiple files.
-
-Interface:
-
-- read lines of form 'input-file output-file\n' from stdin
-- process file and write 'ok\n' to stdout
-- repeat forever
-"""
-
-import subprocess
-import sys
-
-import pyxl.codec.register
-
-
-def main():
-    ...
-
-
-if __name__ == '__main__':
-    main()
diff --git a/setup.py b/setup.py
index 69cbfb2..10da829 100644
--- a/setup.py
+++ b/setup.py
@@ -5,14 +5,14 @@ import os
 import os.path
 import sys
 
-from distutils.core import setup
-from mypy.version import __version__
-from mypy import git
-
 if sys.version_info < (3, 2, 0):
     sys.stderr.write("ERROR: You need Python 3.2 or later to use mypy.\n")
     exit(1)
 
+from distutils.core import setup
+from mypy.version import __version__
+from mypy import git
+
 git.verify_git_integrity_or_abort(".")
 
 version = __version__
diff --git a/typeshed/stdlib/2.7/__builtin__.pyi b/typeshed/stdlib/2.7/__builtin__.pyi
index e09ebd9..c23c913 100644
--- a/typeshed/stdlib/2.7/__builtin__.pyi
+++ b/typeshed/stdlib/2.7/__builtin__.pyi
@@ -24,7 +24,6 @@ _T4 = TypeVar('_T4')
 
 staticmethod = object()  # Special, only valid as a decorator.
 classmethod = object()  # Special, only valid as a decorator.
-property = object()
 
 class object:
     __doc__ = ...  # type: str
@@ -40,6 +39,7 @@ class object:
     def __hash__(self) -> int: ...
 
 class type:
+    __bases__ = ...  # type: Tuple[type, ...]
     __name__ = ...  # type: str
     __module__ = ...  # type: str
     __dict__ = ...  # type: Dict[unicode, Any]
@@ -55,6 +55,13 @@ class type:
     def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ...
     def __call__(self, *args: Any, **kwds: Any) -> Any: ...
 
+    # Only new-style classes
+    __mro__ = ...  # type: Tuple[type, ...]
+    # Note: the documentation doesnt specify what the return type is, the standard
+    # implementation seems to be returning a list.
+    def mro(self) -> List[type]: ...
+    def __subclasses__(self) -> List[type]: ...
+
 class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
     @overload
     def __init__(self) -> None: ...
@@ -639,6 +646,17 @@ class module:
     __file__ = ...  # type: str
     __dict__ = ...  # type: Dict[unicode, Any]
 
+class property:
+    def __init__(self, fget: Callable[[Any], Any] = None,
+                 fset: Callable[[Any, Any], None] = None,
+                 fdel: Callable[[Any], None] = None, doc: str = None) -> None: ...
+    def getter(self, fget: Callable[[Any], Any]) -> property: ...
+    def setter(self, fset: Callable[[Any, Any], None]) -> property: ...
+    def deleter(self, fdel: Callable[[Any], None]) -> property: ...
+    def __get__(self, obj: Any, type: type=None) -> Any: ...
+    def __set__(self, obj: Any, value: Any) -> None: ...
+    def __delete__(self, obj: Any) -> None: ...
+
 long = int
 bytes = str
 
@@ -732,7 +750,7 @@ def reversed(object: Reversible[_T]) -> Iterator[_T]: ...
 def reversed(object: Sequence[_T]) -> Iterator[_T]: ...
 def repr(o: object) -> str: ...
 @overload
-def round(number: float) -> int: ...
+def round(number: float) -> float: ...
 @overload
 def round(number: float, ndigits: int) -> float: ...  # Always return a float if given ndigits.
 @overload
@@ -881,3 +899,8 @@ class file(BinaryIO):
     def write(self, data: str) -> None: ...
     def writelines(self, data: Iterable[str]) -> None: ...
     def truncate(self, pos: int = ...) -> int: ...
+
+# Very old builtins
+def apply(func: Callable[..., _T], args: Sequence[Any] = None, kwds: Mapping[str, Any] = None) -> _T: ...
+_N = TypeVar('_N', bool, int, float, complex)
+def coerce(x: _N, y: _N) -> Tuple[_N, _N]: ...
diff --git a/typeshed/stdlib/2.7/_socket.pyi b/typeshed/stdlib/2.7/_socket.pyi
index 6f72ba9..cfd615e 100644
--- a/typeshed/stdlib/2.7/_socket.pyi
+++ b/typeshed/stdlib/2.7/_socket.pyi
@@ -264,7 +264,7 @@ class SocketType(object):
     def fileno(self) -> int: ...
     def getpeername(self) -> tuple: ...
     def getsockname(self) -> tuple: ...
-    def getsockopt(self, level: int, option: str, buffersize: int = ...) -> str: ...
+    def getsockopt(self, level: int, option: int, buffersize: int = ...) -> str: ...
     def gettimeout(self) -> float: ...
     def listen(self, backlog: int) -> None:
         raise error
diff --git a/typeshed/stdlib/2.7/argparse.pyi b/typeshed/stdlib/2.7/argparse.pyi
index a0b6f80..890b4da 100644
--- a/typeshed/stdlib/2.7/argparse.pyi
+++ b/typeshed/stdlib/2.7/argparse.pyi
@@ -2,7 +2,7 @@
 #
 # NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any, Sequence, Union
+from typing import Any, Callable, Dict, List, IO, Iterable, Sequence, Union
 
 SUPPRESS = ... # type: Any
 OPTIONAL = ... # type: Any
@@ -52,8 +52,17 @@ class Action(_AttributeHolder):
     required = ... # type: Any
     help = ... # type: Any
     metavar = ... # type: Any
-    def __init__(self, option_strings, dest, nargs=..., const=..., default=..., type=...,
-                 choices=..., required=..., help=..., metavar=...): ...
+    def __init__(self,
+                 option_strings: List[str],
+                 dest = str,
+                 nargs: Union[int, str] = ...,
+                 const: Any = ...,
+                 default: Any = ...,
+                 type: Callable[[str], Any] = ...,
+                 choices: Iterable[Any] = ...,
+                 required: bool = ...,
+                 help: str = ...,
+                 metavar: str = ...) -> None: ...
     def __call__(self, parser, namespace, values, option_string=...): ...
 
 class _StoreAction(Action):
@@ -138,7 +147,7 @@ class _ActionsContainer:
         version: str = ...
     ) -> None: ...
     def add_argument_group(self, *args, **kwargs): ...
-    def add_mutually_exclusive_group(self, **kwargs): ...
+    def add_mutually_exclusive_group(self, **kwargs) -> _MutuallyExclusiveGroup: ...
 
 class _ArgumentGroup(_ActionsContainer):
     title = ... # type: Any
@@ -156,9 +165,19 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
     formatter_class = ... # type: Any
     fromfile_prefix_chars = ... # type: Any
     add_help = ... # type: Any
-    def __init__(self, prog=..., usage=..., description=..., epilog=..., version=...,
-                 parents=..., formatter_class=..., prefix_chars=..., fromfile_prefix_chars=...,
-                 argument_default=..., conflict_handler=..., add_help=...): ...
+    def __init__(self,
+                 prog: str = ...,
+                 usage: str = ...,
+                 description: str = ...,
+                 epilog: str = ...,
+                 version: None = ...,
+                 parents: Iterable[ArgumentParser] = ...,
+                 formatter_class: HelpFormatter = ...,
+                 prefix_chars: str = ...,
+                 fromfile_prefix_chars: str = ...,
+                 argument_default: str = ...,
+                 conflict_handler: str = ...,
+                 add_help: bool = ...) -> None: ...
     def add_subparsers(self, **kwargs): ...
     def parse_args(self, args: Sequence[str] = ..., namespace=...): ...
     def parse_known_args(self, args=..., namespace=...): ...
@@ -167,7 +186,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
     def format_help(self): ...
     def format_version(self): ...
     def print_usage(self, file=...): ...
-    def print_help(self, file=...): ...
+    def print_help(self, file: IO[Any] = None) -> None: ...
     def print_version(self, file=...): ...
     def exit(self, status=..., message=...): ...
     def error(self, message): ...
diff --git a/typeshed/stdlib/2.7/builtins.pyi b/typeshed/stdlib/2.7/builtins.pyi
index e09ebd9..c23c913 100644
--- a/typeshed/stdlib/2.7/builtins.pyi
+++ b/typeshed/stdlib/2.7/builtins.pyi
@@ -24,7 +24,6 @@ _T4 = TypeVar('_T4')
 
 staticmethod = object()  # Special, only valid as a decorator.
 classmethod = object()  # Special, only valid as a decorator.
-property = object()
 
 class object:
     __doc__ = ...  # type: str
@@ -40,6 +39,7 @@ class object:
     def __hash__(self) -> int: ...
 
 class type:
+    __bases__ = ...  # type: Tuple[type, ...]
     __name__ = ...  # type: str
     __module__ = ...  # type: str
     __dict__ = ...  # type: Dict[unicode, Any]
@@ -55,6 +55,13 @@ class type:
     def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ...
     def __call__(self, *args: Any, **kwds: Any) -> Any: ...
 
+    # Only new-style classes
+    __mro__ = ...  # type: Tuple[type, ...]
+    # Note: the documentation doesnt specify what the return type is, the standard
+    # implementation seems to be returning a list.
+    def mro(self) -> List[type]: ...
+    def __subclasses__(self) -> List[type]: ...
+
 class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
     @overload
     def __init__(self) -> None: ...
@@ -639,6 +646,17 @@ class module:
     __file__ = ...  # type: str
     __dict__ = ...  # type: Dict[unicode, Any]
 
+class property:
+    def __init__(self, fget: Callable[[Any], Any] = None,
+                 fset: Callable[[Any, Any], None] = None,
+                 fdel: Callable[[Any], None] = None, doc: str = None) -> None: ...
+    def getter(self, fget: Callable[[Any], Any]) -> property: ...
+    def setter(self, fset: Callable[[Any, Any], None]) -> property: ...
+    def deleter(self, fdel: Callable[[Any], None]) -> property: ...
+    def __get__(self, obj: Any, type: type=None) -> Any: ...
+    def __set__(self, obj: Any, value: Any) -> None: ...
+    def __delete__(self, obj: Any) -> None: ...
+
 long = int
 bytes = str
 
@@ -732,7 +750,7 @@ def reversed(object: Reversible[_T]) -> Iterator[_T]: ...
 def reversed(object: Sequence[_T]) -> Iterator[_T]: ...
 def repr(o: object) -> str: ...
 @overload
-def round(number: float) -> int: ...
+def round(number: float) -> float: ...
 @overload
 def round(number: float, ndigits: int) -> float: ...  # Always return a float if given ndigits.
 @overload
@@ -881,3 +899,8 @@ class file(BinaryIO):
     def write(self, data: str) -> None: ...
     def writelines(self, data: Iterable[str]) -> None: ...
     def truncate(self, pos: int = ...) -> int: ...
+
+# Very old builtins
+def apply(func: Callable[..., _T], args: Sequence[Any] = None, kwds: Mapping[str, Any] = None) -> _T: ...
+_N = TypeVar('_N', bool, int, float, complex)
+def coerce(x: _N, y: _N) -> Tuple[_N, _N]: ...
diff --git a/typeshed/stdlib/2.7/calendar.pyi b/typeshed/stdlib/2.7/calendar.pyi
index d5d1813..e5ee51b 100644
--- a/typeshed/stdlib/2.7/calendar.pyi
+++ b/typeshed/stdlib/2.7/calendar.pyi
@@ -72,4 +72,4 @@ c = ...  # type: TextCalendar
 def setfirstweekday(firstweekday: int) -> None: ...
 def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ...
 def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ...
-def timegm(tuple: Tuple[int]) -> int: ...
+def timegm(tuple: Tuple[int, ...]) -> int: ...
diff --git a/typeshed/stdlib/2.7/datetime.pyi b/typeshed/stdlib/2.7/datetime.pyi
index 44699f3..6d3ce65 100644
--- a/typeshed/stdlib/2.7/datetime.pyi
+++ b/typeshed/stdlib/2.7/datetime.pyi
@@ -10,8 +10,8 @@ MAXYEAR = 0
 
 class tzinfo(object):
     def tzname(self, dt: Optional[datetime]) -> str: ...
-    def utcoffset(self, dt: Optional[datetime]) -> int: ...
-    def dst(self, dt: Optional[datetime]) -> int: ...
+    def utcoffset(self, dt: Optional[datetime]) -> timedelta: ...
+    def dst(self, dt: Optional[datetime]) -> timedelta: ...
     def fromutc(self, dt: datetime) -> datetime: ...
 
 class timezone(tzinfo):
@@ -198,7 +198,7 @@ class datetime(object):
     def replace(self, year: int = ..., month: int = ..., day: int = ..., hour: int = ...,
                 minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo:
                 Union[_tzinfo, bool] = ...) -> datetime: ...
-    def astimezone(self, tz: timezone = ...) -> datetime: ...
+    def astimezone(self, tz: _tzinfo = ...) -> datetime: ...
     def ctime(self) -> str: ...
     def isoformat(self, sep: str = ...) -> str: ...
     @classmethod
diff --git a/typeshed/stdlib/2.7/getopt.pyi b/typeshed/stdlib/2.7/getopt.pyi
new file mode 100644
index 0000000..0a8fa0c
--- /dev/null
+++ b/typeshed/stdlib/2.7/getopt.pyi
@@ -0,0 +1,17 @@
+from typing import List, Tuple
+
+class GetoptError(Exception):
+    opt = ... # type: str
+    msg = ... # type: str
+    def __init__(self, msg: str, opt: str=...) -> None: ...
+    def __str__(self) -> str: ...
+
+error = GetoptError
+
+def getopt(args: List[str], shortopts: str,
+           longopts: List[str]=...) -> Tuple[List[Tuple[str, str]],
+                                             List[str]]: ...
+
+def gnu_getopt(args: List[str], shortopts: str,
+           longopts: List[str]=...) -> Tuple[List[Tuple[str,str]],
+                                             List[str]]: ...
diff --git a/typeshed/stdlib/2.7/gettext.pyi b/typeshed/stdlib/2.7/gettext.pyi
index 16a9651..7c30484 100644
--- a/typeshed/stdlib/2.7/gettext.pyi
+++ b/typeshed/stdlib/2.7/gettext.pyi
@@ -29,7 +29,8 @@ class Translations(object):
     def set_output_charset(self, charset: Any) -> None: ...
     def install(self, unicode: bool = ..., names: Any = ...) -> None: ...
 
-# TODO: NullTranslations, GNUTranslations
+class NullTranslations(Translations): ...
+class GNUTranslations(Translations): ...
 
 def find(domain: str, localedir: str = ..., languages: List[str] = ...,
          all: Any = ...) -> Optional[Union[str, List[str]]]: ...
diff --git a/typeshed/stdlib/2.7/json.pyi b/typeshed/stdlib/2.7/json.pyi
index f319371..d5b7106 100644
--- a/typeshed/stdlib/2.7/json.pyi
+++ b/typeshed/stdlib/2.7/json.pyi
@@ -1,4 +1,4 @@
-from typing import Any, IO, Optional, Tuple, Callable, Dict, List
+from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union, Text
 
 class JSONDecodeError(object):
     def dumps(self, obj: Any) -> str: ...
@@ -33,7 +33,7 @@ def dump(obj: Any,
     sort_keys: bool = ...,
     **kwds: Any) -> None: ...
 
-def loads(s: str,
+def loads(s: Union[Text, bytes],
     encoding: Any = ...,
     cls: Any = ...,
     object_hook: Callable[[Dict], Any] = ...,
diff --git a/typeshed/stdlib/2.7/logging/__init__.pyi b/typeshed/stdlib/2.7/logging/__init__.pyi
index 377e800..903fb89 100644
--- a/typeshed/stdlib/2.7/logging/__init__.pyi
+++ b/typeshed/stdlib/2.7/logging/__init__.pyi
@@ -4,14 +4,14 @@
 
 from typing import Any, Dict, Optional, Sequence, Tuple, overload, Union
 
-CRITICAL = 0
-FATAL = 0
-ERROR = 0
-WARNING = 0
-WARN = 0
-INFO = 0
-DEBUG = 0
-NOTSET = 0
+CRITICAL = ... # type: int
+FATAL = ... # type: int
+ERROR = ... # type: int
+WARNING = ... # type: int
+WARN = ... # type: int
+INFO = ... # type: int
+DEBUG = ... # type: int
+NOTSET = ... # type: int
 
 def getLevelName(level: int) -> str: ...
 def addLevelName(level: int, levelName: str) -> None: ...
@@ -47,22 +47,22 @@ class PercentStyle:
     asctime_format = ...  # type: Any
     asctime_search = ...  # type: Any
     def __init__(self, fmt) -> None: ...
-    def usesTime(self): ...
-    def format(self, record): ...
+    def usesTime(self) -> bool: ...
+    def format(self, record: LogRecord) -> str: ...
 
 class StrFormatStyle(PercentStyle):
     default_format = ...  # type: Any
     asctime_format = ...  # type: Any
     asctime_search = ...  # type: Any
-    def format(self, record): ...
+    def format(self, record: LogRecord) -> str: ...
 
 class StringTemplateStyle(PercentStyle):
     default_format = ...  # type: Any
     asctime_format = ...  # type: Any
     asctime_search = ...  # type: Any
     def __init__(self, fmt) -> None: ...
-    def usesTime(self): ...
-    def format(self, record): ...
+    def usesTime(self) -> bool: ...
+    def format(self, record: LogRecord) -> str: ...
 
 BASIC_FORMAT = ...  # type: Any
 
@@ -72,19 +72,19 @@ class Formatter:
     def __init__(self, fmt: str = ..., datefmt: str = ...) -> None: ...
     default_time_format = ...  # type: Any
     default_msec_format = ...  # type: Any
-    def formatTime(self, record, datefmt=...): ...
-    def formatException(self, ei): ...
-    def usesTime(self): ...
-    def formatMessage(self, record): ...
-    def formatStack(self, stack_info): ...
+    def formatTime(self, record: LogRecord, datefmt: str =...) -> str: ...
+    def formatException(self, ei) -> str: ...
+    def usesTime(self) -> bool: ...
+    def formatMessage(self, record: LogRecord) -> str: ...
+    def formatStack(self, stack_info) -> str: ...
     def format(self, record: LogRecord) -> str: ...
 
 class BufferingFormatter:
     linefmt = ...  # type: Any
-    def __init__(self, linefmt=...) -> None: ...
-    def formatHeader(self, records): ...
-    def formatFooter(self, records): ...
-    def format(self, records): ...
+    def __init__(self, linefmt: Formatter =...) -> None: ...
+    def formatHeader(self, records: list[LogRecord]) -> str: ...
+    def formatFooter(self, records: list[LogRecord]) -> str: ...
+    def format(self, records: list[LogRecord]) -> str: ...
 
 class Filter:
     name = ...  # type: Any
@@ -104,12 +104,12 @@ class Handler(Filterer):
     formatter = ...  # type: Any
     def __init__(self, level: int = ...) -> None: ...
     def get_name(self): ...
-    def set_name(self, name): ...
+    def set_name(self, name) -> None: ...
     name = ...  # type: Any
     lock = ...  # type: Any
-    def createLock(self): ...
-    def acquire(self): ...
-    def release(self): ...
+    def createLock(self) -> None: ...
+    def acquire(self) -> None: ...
+    def release(self) -> None: ...
     def setLevel(self, level: int) -> None: ...
     def format(self, record: LogRecord) -> str: ...
     def emit(self, record: LogRecord) -> None: ...
@@ -123,8 +123,8 @@ class StreamHandler(Handler):
     terminator = ...  # type: Any
     stream = ...  # type: Any
     def __init__(self, stream=...) -> None: ...
-    def flush(self): ...
-    def emit(self, record): ...
+    def flush(self) -> None: ...
+    def emit(self, record: LogRecord) -> None: ...
 
 class FileHandler(StreamHandler):
     baseFilename = ...  # type: Any
@@ -133,20 +133,20 @@ class FileHandler(StreamHandler):
     delay = ...  # type: Any
     stream = ...  # type: Any
     def __init__(self, filename: str, mode: str = ..., encoding: str = ..., delay: int = ...) -> None: ...
-    def close(self): ...
-    def emit(self, record): ...
+    def close(self) -> None: ...
+    def emit(self, record: LogRecord) -> None: ...
 
 class _StderrHandler(StreamHandler):
-    def __init__(self, level=...) -> None: ...
+    def __init__(self, level: int =...) -> None: ...
 
 lastResort = ...  # type: Any
 
 class PlaceHolder:
     loggerMap = ...  # type: Any
     def __init__(self, alogger) -> None: ...
-    def append(self, alogger): ...
+    def append(self, alogger) -> None: ...
 
-def setLoggerClass(klass): ...
+def setLoggerClass(klass) -> None: ...
 def getLoggerClass(): ...
 
 class Manager:
@@ -157,9 +157,9 @@ class Manager:
     loggerClass = ...  # type: Any
     logRecordFactory = ...  # type: Any
     def __init__(self, rootnode) -> None: ...
-    def getLogger(self, name): ...
-    def setLoggerClass(self, klass): ...
-    def setLogRecordFactory(self, factory): ...
+    def getLogger(self, name: unicode): ...
+    def setLoggerClass(self, klass) -> None: ...
+    def setLogRecordFactory(self, factory) -> None: ...
 
 class Logger(Filterer):
     name = ...  # type: Any
@@ -180,25 +180,25 @@ class Logger(Filterer):
     fatal = ...  # type: Any
     def log(self, level: int, msg: Union[str, unicode], *args, **kwargs) -> None: ...
     def findCaller(self) -> Tuple[str, int, str]: ...
-    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=..., extra=...,
-                   sinfo=...): ...
-    def handle(self, record): ...
+    def makeRecord(self, name, level: int, fn, lno, msg, args,
+                   exc_info, func=..., extra=..., sinfo=...) -> LogRecord: ...
+    def handle(self, record: LogRecord) -> None: ...
     def addHandler(self, hdlr: Handler) -> None: ...
     def removeHandler(self, hdlr: Handler) -> None: ...
-    def hasHandlers(self): ...
-    def callHandlers(self, record): ...
+    def hasHandlers(self) -> None: ...
+    def callHandlers(self, record: LogRecord) -> None: ...
     def getEffectiveLevel(self) -> int: ...
     def isEnabledFor(self, level: int) -> bool: ...
     def getChild(self, suffix: str) -> Logger: ...
 
 class RootLogger(Logger):
-    def __init__(self, level) -> None: ...
+    def __init__(self, level: int) -> None: ...
 
 class LoggerAdapter:
     logger = ...  # type: Any
     extra = ...  # type: Any
     def __init__(self, logger, extra) -> None: ...
-    def process(self, msg, kwargs): ...
+    def process(self, msg, kwargs) -> Tuple[Any,Any]: ... # Possible mistake: kwargs missing **
     def debug(self, msg: Union[str, unicode], *args, **kwargs) -> None: ...
     def info(self, msg: Union[str, unicode], *args, **kwargs) -> None: ...
     def warning(self, msg: Union[str, unicode], *args, **kwargs) -> None: ...
@@ -210,7 +210,7 @@ class LoggerAdapter:
     def isEnabledFor(self, level: int) -> bool: ...
     def setLevel(self, level: int) -> None: ...
     def getEffectiveLevel(self) -> int: ...
-    def hasHandlers(self): ...
+    def hasHandlers(self) -> bool: ...
 
 def basicConfig(**kwargs) -> None: ...
 def getLogger(name: str = ...) -> Logger: ...
@@ -231,8 +231,8 @@ def log(level: int, msg: Union[str, unicode], *args, **kwargs) -> None: ...
 def disable(level: int) -> None: ...
 
 class NullHandler(Handler):
-    def handle(self, record): ...
-    def emit(self, record): ...
+    def handle(self, record: LogRecord) -> None: ...
+    def emit(self, record: LogRecord) -> None: ...
     lock = ...  # type: Any
     def createLock(self): ...
 
diff --git a/typeshed/stdlib/2.7/logging/handlers.pyi b/typeshed/stdlib/2.7/logging/handlers.pyi
index 584d759..658c768 100644
--- a/typeshed/stdlib/2.7/logging/handlers.pyi
+++ b/typeshed/stdlib/2.7/logging/handlers.pyi
@@ -2,8 +2,10 @@
 #
 # NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
+from typing import Any, Union, Tuple
+from . import LogRecord
 import logging
+import socket
 
 threading = ...  # type: Any
 DEFAULT_TCP_LOGGING_PORT = ...  # type: Any
@@ -18,19 +20,19 @@ class BaseRotatingHandler(logging.FileHandler):
     encoding = ...  # type: Any
     namer = ...  # type: Any
     rotator = ...  # type: Any
-    def __init__(self, filename, mode, encoding=..., delay=...) -> None: ...
-    def emit(self, record): ...
-    def rotation_filename(self, default_name): ...
+    def __init__(self, filename: unicode, mode: unicode, encoding: unicode =..., delay: int =...) -> None: ...
+    def emit(self, record: LogRecord) -> None: ...
+    def rotation_filename(self, default_name: unicode): ...
     def rotate(self, source, dest): ...
 
 class RotatingFileHandler(BaseRotatingHandler):
     maxBytes = ...  # type: Any
     backupCount = ...  # type: Any
-    def __init__(self, filename: str, mode: str = ..., maxBytes: int = ..., backupCount:int = ...,
+    def __init__(self, filename: unicode, mode: unicode = ..., maxBytes: int = ..., backupCount:int = ...,
                  encoding: str = ..., delay: int = ...) -> None: ...
     stream = ...  # type: Any
-    def doRollover(self): ...
-    def shouldRollover(self, record): ...
+    def doRollover(self) -> None: ...
+    def shouldRollover(self, record: LogRecord) -> int: ...
 
 class TimedRotatingFileHandler(BaseRotatingHandler):
     when = ...  # type: Any
@@ -42,18 +44,18 @@ class TimedRotatingFileHandler(BaseRotatingHandler):
     extMatch = ...  # type: Any
     dayOfWeek = ...  # type: Any
     rolloverAt = ...  # type: Any
-    def __init__(self, filename, when=..., interval=..., backupCount=..., encoding=..., delay=...,
-                 utc=..., atTime=...): ...
-    def computeRollover(self, currentTime): ...
-    def shouldRollover(self, record): ...
-    def getFilesToDelete(self): ...
+    def __init__(self, filename: unicode, when: unicode =..., interval: int =..., backupCount: int =...,
+                 encoding: unicode =..., delay: bool =..., utc: bool =..., atTime=...) -> None: ...
+    def computeRollover(self, currentTime: int) -> int: ...
+    def shouldRollover(self, record: LogRecord) -> int: ...
+    def getFilesToDelete(self) -> list[str]: ...
     stream = ...  # type: Any
-    def doRollover(self): ...
+    def doRollover(self) -> None: ...
 
 class WatchedFileHandler(logging.FileHandler):
     def __init__(self, filename: str, mode: str = ..., encoding: str = ..., delay: int = ...) -> None: ...
     stream = ...  # type: Any
-    def emit(self, record): ...
+    def emit(self, record: LogRecord) -> None: ...
 
 class SocketHandler(logging.Handler):
     host = ...  # type: Any
@@ -66,20 +68,20 @@ class SocketHandler(logging.Handler):
     retryMax = ...  # type: Any
     retryFactor = ...  # type: Any
     def __init__(self, host, port) -> None: ...
-    def makeSocket(self, timeout=...): ...
+    def makeSocket(self, timeout: int =...): ...
     retryPeriod = ...  # type: Any
-    def createSocket(self): ...
-    def send(self, s): ...
-    def makePickle(self, record): ...
-    def handleError(self, record): ...
-    def emit(self, record): ...
-    def close(self): ...
+    def createSocket(self) -> None: ...
+    def send(self, s: str) -> None: ...
+    def makePickle(self, record: LogRecord) -> str: ...
+    def handleError(self, record: LogRecord) -> None: ...
+    def emit(self, record: LogRecord) -> None: ...
+    def close(self) -> None: ...
 
 class DatagramHandler(SocketHandler):
     closeOnError = ...  # type: Any
     def __init__(self, host, port) -> None: ...
-    def makeSocket(self, timeout=...): ... # TODO: Actually does not have the timeout argument.
-    def send(self, s): ...
+    def makeSocket(self, timeout: int =...) -> None: ...
+    def send(self, s: str) -> None: ...
 
 class SysLogHandler(logging.Handler):
     LOG_EMERG = ...  # type: Any
@@ -119,13 +121,13 @@ class SysLogHandler(logging.Handler):
     unixsocket = ...  # type: Any
     socket = ...  # type: Any
     formatter = ...  # type: Any
-    def __init__(self, address=..., facility=..., socktype=...) -> None: ...
-    def encodePriority(self, facility, priority): ...
-    def close(self): ...
-    def mapPriority(self, levelName): ...
+    def __init__(self, address: tuple[str,int] =..., facility: int =..., socktype: int =...) -> None: ...
+    def encodePriority(self, facility: int, priority: Union[basestring,int]) -> int: ...
+    def close(self) -> None: ...
+    def mapPriority(self, levelName: str) -> str: ...
     ident = ...  # type: Any
     append_nul = ...  # type: Any
-    def emit(self, record): ...
+    def emit(self, record: LogRecord) -> None: ...
 
 class SMTPHandler(logging.Handler):
     username = ...  # type: Any
@@ -134,10 +136,10 @@ class SMTPHandler(logging.Handler):
     subject = ...  # type: Any
     secure = ...  # type: Any
     timeout = ...  # type: Any
-    def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=..., secure=...,
-                 timeout=...): ...
-    def getSubject(self, record): ...
-    def emit(self, record): ...
+    def __init__(self, mailhost, fromaddr, toaddrs, subject: unicode, credentials: Tuple[Any,Any]=...,
+                 secure=...) -> None: ...
+    def getSubject(self, record: LogRecord) -> unicode: ...
+    def emit(self, record: LogRecord) -> None: ...
 
 class NTEventLogHandler(logging.Handler):
     appname = ...  # type: Any
@@ -145,12 +147,12 @@ class NTEventLogHandler(logging.Handler):
     logtype = ...  # type: Any
     deftype = ...  # type: Any
     typemap = ...  # type: Any
-    def __init__(self, appname, dllname=..., logtype=...) -> None: ...
-    def getMessageID(self, record): ...
-    def getEventCategory(self, record): ...
-    def getEventType(self, record): ...
-    def emit(self, record): ...
-    def close(self): ...
+    def __init__(self, appname, dllname=..., logtype: str =...) -> None: ...
+    def getMessageID(self, record: LogRecord) -> int: ...
+    def getEventCategory(self, record: LogRecord) -> int: ...
+    def getEventType(self, record: LogRecord): ...
+    def emit(self, record: LogRecord) -> None: ...
+    def close(self) -> None: ...
 
 class HTTPHandler(logging.Handler):
     host = ...  # type: Any
@@ -158,43 +160,43 @@ class HTTPHandler(logging.Handler):
     method = ...  # type: Any
     secure = ...  # type: Any
     credentials = ...  # type: Any
-    def __init__(self, host, url, method=..., secure=..., credentials=...) -> None: ...
-    def mapLogRecord(self, record): ...
-    def emit(self, record): ...
+    def __init__(self, host, url, method: str =..., secure=..., credentials=...) -> None: ...
+    def mapLogRecord(self, record: LogRecord) -> dict[Any,Any]: ...
+    def emit(self, record: LogRecord) -> None: ...
 
 class BufferingHandler(logging.Handler):
     capacity = ...  # type: Any
     buffer = ...  # type: Any
     def __init__(self, capacity: int) -> None: ...
-    def shouldFlush(self, record): ...
-    def emit(self, record): ...
-    def flush(self): ...
-    def close(self): ...
+    def shouldFlush(self, record: LogRecord) -> bool: ...
+    def emit(self, record: LogRecord) -> None: ...
+    def flush(self) -> None: ...
+    def close(self) -> None: ...
 
 class MemoryHandler(BufferingHandler):
     flushLevel = ...  # type: Any
     target = ...  # type: Any
-    def __init__(self, capacity, flushLevel=..., target=...) -> None: ...
-    def shouldFlush(self, record): ...
-    def setTarget(self, target): ...
+    def __init__(self, capacity: int, flushLevel: int =..., target=...) -> None: ...
+    def shouldFlush(self, record: LogRecord) -> bool: ...
+    def setTarget(self, target) -> None: ...
     buffer = ...  # type: Any
-    def flush(self): ...
-    def close(self): ...
+    def flush(self) -> None: ...
+    def close(self) -> None: ...
 
 class QueueHandler(logging.Handler):
     queue = ...  # type: Any
     def __init__(self, queue) -> None: ...
-    def enqueue(self, record): ...
-    def prepare(self, record): ...
-    def emit(self, record): ...
+    def enqueue(self, record: LogRecord): ...
+    def prepare(self, record: LogRecord): ...
+    def emit(self, record: LogRecord) -> None: ...
 
 class QueueListener:
     queue = ...  # type: Any
     handlers = ...  # type: Any
     def __init__(self, queue, *handlers) -> None: ...
     def dequeue(self, block): ...
-    def start(self): ...
-    def prepare(self, record): ...
-    def handle(self, record): ...
+    def start(self) -> None: ...
+    def prepare(self, record: LogRecord): ...
+    def handle(self, record: LogRecord): ...
     def enqueue_sentinel(self): ...
-    def stop(self): ...
+    def stop(self) -> None: ...
diff --git a/typeshed/stdlib/2.7/pprint.pyi b/typeshed/stdlib/2.7/pprint.pyi
index 4c9819a..5275d03 100644
--- a/typeshed/stdlib/2.7/pprint.pyi
+++ b/typeshed/stdlib/2.7/pprint.pyi
@@ -6,15 +6,18 @@ from typing import IO, Any
 
 def pprint(object: Any, stream: IO[str] = ..., indent: int = ..., width: int = ...,
            depth: int = ...) -> None: ...
-def pformat(object, indent=..., width=..., depth=...): ...
+def pformat(object: Any, indent: int =..., width: int =..., depth: int =...) -> str: ...
 def saferepr(object): ...
 def isreadable(object): ...
 def isrecursive(object): ...
 
 class PrettyPrinter:
-    def __init__(self, indent: int = ..., width: int = ..., depth: int = ...,
-                 stream: IO[str] = ...) -> None: ...
-    def pprint(self, object): ...
+    def __init__(self,
+                 indent: int = ...,
+                 width: int = ...,
+                 depth: int = ...,
+                 stream: IO[Any] = ...) -> None: ...
+    def pprint(self, object: Any) -> str: ...
     def pformat(self, object): ...
     def isrecursive(self, object): ...
     def isreadable(self, object): ...
diff --git a/typeshed/stdlib/2.7/re.pyi b/typeshed/stdlib/2.7/re.pyi
index 79b3a10..7c47bcd 100644
--- a/typeshed/stdlib/2.7/re.pyi
+++ b/typeshed/stdlib/2.7/re.pyi
@@ -28,22 +28,43 @@ TEMPLATE = 0
 
 class error(Exception): ...
 
+ at overload
 def compile(pattern: AnyStr, flags: int = ...) -> Pattern[AnyStr]: ...
-def search(pattern: AnyStr, string: AnyStr,
-           flags: int = ...) -> Match[AnyStr]: ...
-def match(pattern: AnyStr, string: AnyStr,
-          flags: int = ...) -> Match[AnyStr]: ...
-def split(pattern: AnyStr, string: AnyStr, maxsplit: int = ...,
-          flags: int = ...) -> List[AnyStr]: ...
-def findall(pattern: AnyStr, string: AnyStr,
-            flags: int = ...) -> List[AnyStr]: ...
+ at overload
+def compile(pattern: Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ...
+
+ at overload
+def search(pattern: AnyStr, string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+ at overload
+def search(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+
+ at overload
+def match(pattern: AnyStr, string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+ at overload
+def match(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+
+ at overload
+def split(pattern: AnyStr, string: AnyStr,
+          maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ...
+ at overload
+def split(pattern: Pattern[AnyStr], string: AnyStr,
+          maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ...
+
+ at overload
+def findall(pattern: AnyStr, string: AnyStr, flags: int = ...) -> List[AnyStr]: ...
+ at overload
+def findall(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> List[AnyStr]: ...
 
 # Return an iterator yielding match objects over all non-overlapping matches
 # for the RE pattern in string. The string is scanned left-to-right, and
 # matches are returned in the order found. Empty matches are included in the
 # result unless they touch the beginning of another match.
+ at overload
 def finditer(pattern: AnyStr, string: AnyStr,
              flags: int = ...) -> Iterator[Match[AnyStr]]: ...
+ at overload
+def finditer(pattern: Pattern[AnyStr], string: AnyStr,
+             flags: int = ...) -> Iterator[Match[AnyStr]]: ...
 
 @overload
 def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ...,
@@ -51,6 +72,12 @@ def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ...,
 @overload
 def sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr],
         string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ...
+ at overload
+def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ...,
+        flags: int = ...) -> AnyStr: ...
+ at overload
+def sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr],
+        string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ...
 
 @overload
 def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ...,
@@ -59,6 +86,13 @@ def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ...,
 def subn(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr],
          string: AnyStr, count: int = ...,
          flags: int = ...) -> Tuple[AnyStr, int]: ...
+ at overload
+def subn(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ...,
+         flags: int = ...) -> Tuple[AnyStr, int]: ...
+ at overload
+def subn(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr],
+         string: AnyStr, count: int = ...,
+         flags: int = ...) -> Tuple[AnyStr, int]: ...
 
 def escape(string: AnyStr) -> AnyStr: ...
 
diff --git a/typeshed/stdlib/2.7/socket.pyi b/typeshed/stdlib/2.7/socket.pyi
index 93864c3..5b71485 100644
--- a/typeshed/stdlib/2.7/socket.pyi
+++ b/typeshed/stdlib/2.7/socket.pyi
@@ -295,9 +295,9 @@ class socket:
     def getsockname(self) -> Any: ...
 
     @overload
-    def getsockopt(self, level: int, optname: str) -> int: ...
+    def getsockopt(self, level: int, optname: int) -> int: ...
     @overload
-    def getsockopt(self, level: int, optname: str, buflen: int) -> bytes: ...
+    def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...
 
     def gettimeout(self) -> float: ...
     def ioctl(self, control: object,
@@ -322,7 +322,7 @@ class socket:
     def sendto(self, data: str, address: Union[tuple, str], flags: int = ...) -> int: ...
     def setblocking(self, flag: bool) -> None: ...
     def settimeout(self, value: Union[float, None]) -> None: ...
-    def setsockopt(self, level: int, optname: str, value: Union[int, str]) -> None: ...
+    def setsockopt(self, level: int, optname: int, value: Union[int, str]) -> None: ...
     def shutdown(self, how: int) -> None: ...
 
 
diff --git a/typeshed/stdlib/2.7/subprocess.pyi b/typeshed/stdlib/2.7/subprocess.pyi
index 6053a4e..7a42eff 100644
--- a/typeshed/stdlib/2.7/subprocess.pyi
+++ b/typeshed/stdlib/2.7/subprocess.pyi
@@ -8,15 +8,15 @@ _FILE = Union[int, IO[Any]]
 
 # TODO force keyword arguments
 # TODO more keyword arguments (from Popen)
-def call(args: Sequence[str], *,
+def call(args: Union[str, Sequence[str]], *,
          stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ...,
          shell: bool = ..., env: Mapping[str, str] = ...,
          cwd: str = ...) -> int: ...
-def check_call(args: Sequence[str], *,
+def check_call(args: Union[str, Sequence[str]], *,
                stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ...,
                shell: bool = ..., env: Mapping[str, str] = ..., cwd: str = ...,
                close_fds: Sequence[_FILE] = ..., preexec_fn: Callable[[], Any] = ...) -> int: ...
-def check_output(args: Sequence[str], *,
+def check_output(args: Union[str, Sequence[str]], *,
                  stdin: _FILE = ..., stderr: _FILE = ...,
                  shell: bool = ..., universal_newlines: bool = ...,
                  env: Mapping[str, str] = ..., cwd: str = ...) -> str: ...
@@ -29,7 +29,7 @@ class CalledProcessError(Exception):
     cmd = ...  # type: str
     output = ...  # type: str # May be None
 
-    def __init__(self, returncode: int, cmd: str, output: str = ...) -> None: ...
+    def __init__(self, returncode: int, cmd: str, output: Optional[str] = ...) -> None: ...
 
 class Popen:
     stdin = ... # type: Optional[IO[Any]]
@@ -39,7 +39,7 @@ class Popen:
     returncode = 0
 
     def __init__(self,
-                 args: Sequence[str],
+                 args: Union[str, Sequence[str]],
                  bufsize: int = ...,
                  executable: str = ...,
                  stdin: _FILE = ...,
diff --git a/typeshed/stdlib/2.7/sys.pyi b/typeshed/stdlib/2.7/sys.pyi
index 8bd920f..a1c0247 100644
--- a/typeshed/stdlib/2.7/sys.pyi
+++ b/typeshed/stdlib/2.7/sys.pyi
@@ -116,7 +116,7 @@ def getcheckinterval() -> int: ...  # deprecated
 def getdefaultencoding() -> str: ...
 def getdlopenflags() -> int: ...
 def getfilesystemencoding() -> Union[str, None]: ...
-def getrefcount(object) -> int: ...
+def getrefcount(arg: Any) -> int: ...
 def getrecursionlimit() -> int: ...
 def getsizeof(obj: object, default: int = ...) -> int: ...
 def getprofile() -> None: ...
diff --git a/typeshed/stdlib/2.7/tempfile.pyi b/typeshed/stdlib/2.7/tempfile.pyi
index 42c19ad..7925392 100644
--- a/typeshed/stdlib/2.7/tempfile.pyi
+++ b/typeshed/stdlib/2.7/tempfile.pyi
@@ -4,39 +4,62 @@
 # based on http://docs.python.org/3.3/library/tempfile.html
 # Adapted for Python 2.7 by Michal Pokorny
 
-from typing import Tuple, IO
+# TODO: Don't use basestring. Use Union[str, bytes] or AnyStr for arguments.
+#       Avoid using Union[str, bytes] for return values, as it implies that
+#       an isinstance() check will often be required, which is inconvenient.
+
+from typing import Tuple, IO, Union, AnyStr, Any, overload
 
-# global variables
 tempdir = ...  # type: str
 template = ...  # type: str
 
 # TODO text files
 
-# function stubs
 def TemporaryFile(
-            mode: str = ..., bufsize: int = ..., suffix: str = ...,
-            prefix: str = ..., dir: str = ...) -> IO[str]: ...
+        mode: Union[bytes, unicode] = ...,
+        bufsize: int = ...,
+        suffix: Union[bytes, unicode] = ...,
+        prefix: Union[bytes, unicode] = ...,
+        dir: Union[bytes, unicode] = ...) -> IO[str]: ...
 def NamedTemporaryFile(
-            mode: str = ..., bufsize: int = ..., suffix: str = ...,
-            prefix: str = ..., dir: str = ..., delete: bool = ...
-            ) -> IO[str]: ...
+        mode: Union[bytes, unicode] = ...,
+        bufsize: int = ...,
+        suffix: Union[bytes, unicode] = ...,
+        prefix: Union[bytes, unicode] = ...,
+        dir: Union[bytes, unicode] = ...,
+        delete: bool = ...
+        ) -> IO[str]: ...
 def SpooledTemporaryFile(
-           max_size: int = ..., mode: str = ..., buffering: int = ...,
-           suffix: str = ..., prefix: str = ..., dir: str = ...) -> IO[str]:
+        max_size: int = ...,
+        mode: Union[bytes, unicode] = ...,
+        buffering: int = ...,
+        suffix: Union[bytes, unicode] = ...,
+        prefix: Union[bytes, unicode] = ...,
+        dir: Union[bytes, unicode] = ...) -> IO[str]:
     ...
 
 class TemporaryDirectory:
-    name = ...  # type: basestring
-    def __init__(self, suffix: basestring = ..., prefix: basestring = ...,
-                 dir: basestring = ...) -> None: ...
+    name = ...  # type: Any  # Can be str or unicode
+    def __init__(self,
+                 suffix: Union[bytes, unicode] = ...,
+                 prefix: Union[bytes, unicode] = ...,
+                 dir: Union[bytes, unicode] = ...) -> None: ...
     def cleanup(self) -> None: ...
-    def __enter__(self) -> basestring: ...
+    def __enter__(self) -> Any: ...  # Can be str or unicode
     def __exit__(self, type, value, traceback) -> bool: ...
 
-def mkstemp(suffix: basestring = ..., prefix: basestring = ..., dir: basestring = ...,
-            text: bool = ...) -> Tuple[int, basestring]: ...
-def mkdtemp(suffix: basestring = ..., prefix: basestring = ...,
-            dir: basestring = ...) -> basestring: ...
-def mktemp(suffix: basestring = ..., prefix: basestring = ..., dir: basestring = ...) -> basestring: ...
-def gettempdir() -> basestring: ...
-def gettempprefix() -> basestring: ...
+ at overload
+def mkstemp() -> Tuple[int, str]: ...
+ at overload
+def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr = ...,
+            text: bool = ...) -> Tuple[int, AnyStr]: ...
+ at overload
+def mkdtemp() -> str: ...
+ at overload
+def mkdtemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr = ...) -> AnyStr: ...
+ at overload
+def mktemp() -> str: ...
+ at overload
+def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr = ...) -> AnyStr: ...
+def gettempdir() -> str: ...
+def gettempprefix() -> str: ...
diff --git a/typeshed/stdlib/2.7/threading.pyi b/typeshed/stdlib/2.7/threading.pyi
index 791fa4d..3c0c78c 100644
--- a/typeshed/stdlib/2.7/threading.pyi
+++ b/typeshed/stdlib/2.7/threading.pyi
@@ -73,7 +73,7 @@ class Semaphore(object):
     def __enter__(self) -> bool: ...
     def __exit__(self, *args): ...
 
-class BoundedSemaphore(object):
+class BoundedSemaphore(Semaphore):
     def acquire(self, blocking: bool = ...) -> Optional[bool]: ...
     def release(self) -> None: ...
     def __init__(self, value: int = ...) -> None: ...
diff --git a/typeshed/stdlib/2.7/typing.pyi b/typeshed/stdlib/2.7/typing.pyi
index 77873df..9d74469 100644
--- a/typeshed/stdlib/2.7/typing.pyi
+++ b/typeshed/stdlib/2.7/typing.pyi
@@ -12,6 +12,7 @@ TypeVar = object()
 Generic = object()
 Tuple = object()
 Callable = object()
+Type = object()
 builtinclass = object()
 _promote = object()
 NamedTuple = object()
@@ -283,9 +284,9 @@ class Match(Generic[AnyStr]):
 
     def groups(self, default: AnyStr = ...) -> Sequence[AnyStr]: ...
     def groupdict(self, default: AnyStr = ...) -> dict[str, AnyStr]: ...
-    def start(self, group: int = ...) -> int: ...
-    def end(self, group: int = ...) -> int: ...
-    def span(self, group: int = ...) -> Tuple[int, int]: ...
+    def start(self, group: Union[int, str] = ...) -> int: ...
+    def end(self, group: Union[int, str] = ...) -> int: ...
+    def span(self, group: Union[int, str] = ...) -> Tuple[int, int]: ...
 
 class Pattern(Generic[AnyStr]):
     flags = 0
diff --git a/typeshed/stdlib/2.7/urlparse.pyi b/typeshed/stdlib/2.7/urlparse.pyi
index 2fe1951..aacc80b 100644
--- a/typeshed/stdlib/2.7/urlparse.pyi
+++ b/typeshed/stdlib/2.7/urlparse.pyi
@@ -1,6 +1,6 @@
 # Stubs for urlparse (Python 2)
 
-from typing import Dict, List, NamedTuple, Tuple, Sequence, overload
+from typing import Dict, List, NamedTuple, Tuple, Sequence, Union, overload
 
 uses_relative = []  # type: List[str]
 uses_netloc = []  # type: List[str]
@@ -34,8 +34,10 @@ class ParseResult(NamedTuple('ParseResult', [
     ]), ResultMixin):
     def geturl(self) -> str: ...
 
-def urlparse(url: str, scheme: str = ..., allow_fragments: bool = ...) -> ParseResult: ...
-def urlsplit(url: str, scheme: str = ..., allow_fragments: bool = ...) -> SplitResult: ...
+def urlparse(url: Union[str, unicode], scheme: str = ...,
+             allow_fragments: bool = ...) -> ParseResult: ...
+def urlsplit(url: Union[str, unicode], scheme: str = ...,
+             allow_fragments: bool = ...) -> SplitResult: ...
 @overload
 def urlunparse(data: Tuple[str, str, str, str, str, str]) -> str: ...
 @overload
@@ -44,8 +46,9 @@ def urlunparse(data: Sequence[str]) -> str: ...
 def urlunsplit(data: Tuple[str, str, str, str, str]) -> str: ...
 @overload
 def urlunsplit(data: Sequence[str]) -> str: ...
-def urljoin(base: str, url: str, allow_fragments: bool = ...) -> str: ...
-def urldefrag(url: str) -> str: ...
+def urljoin(base: Union[str, unicode], url: Union[str, unicode],
+            allow_fragments: bool = ...) -> str: ...
+def urldefrag(url: Union[str, unicode]) -> str: ...
 def unquote(s: str) -> str: ...
 def parse_qs(qs: str, keep_blank_values: bool = ...,
              strict_parsing: bool = ...) -> Dict[str, List[str]]: ...
diff --git a/typeshed/stdlib/3.3/xml/etree/ElementTree.pyi b/typeshed/stdlib/3.3/xml/etree/ElementTree.pyi
index 652322f..488d6a5 100644
--- a/typeshed/stdlib/3.3/xml/etree/ElementTree.pyi
+++ b/typeshed/stdlib/3.3/xml/etree/ElementTree.pyi
@@ -74,15 +74,6 @@ class ElementTree:
 
 def register_namespace(prefix: str, uri: str) -> None: ...
 def tostring(element: Element, encoding: str=..., method: str=...) -> str: ...
-
-class _ListDataStream(io.BufferedIOBase):
-    lst = ... # type: List[str]
-    def __init__(self, lst) -> None: ...
-    def writable(self) -> bool: ...
-    def seekable(self) -> bool: ...
-    def write(self, b: str) -> None: ...
-    def tell(self) -> int: ...
-
 def tostringlist(element: Element, encoding: str=..., method: str=...) -> List[str]: ...
 def dump(elem: Element) -> None: ...
 def parse(source: _file_or_filename, parser: 'XMLParser'=...) -> ElementTree: ...
diff --git a/typeshed/stdlib/3.4/xml/etree/ElementTree.pyi b/typeshed/stdlib/3.4/xml/etree/ElementTree.pyi
index 73b49df..8b2eecd 100644
--- a/typeshed/stdlib/3.4/xml/etree/ElementTree.pyi
+++ b/typeshed/stdlib/3.4/xml/etree/ElementTree.pyi
@@ -74,15 +74,6 @@ class ElementTree:
 
 def register_namespace(prefix: str, uri: str) -> None: ...
 def tostring(element: Element, encoding: str=..., method: str=..., *, short_empty_elements: bool=...) -> str: ...
-
-class _ListDataStream(io.BufferedIOBase):
-    lst = ... # type: List[str]
-    def __init__(self, lst) -> None: ...
-    def writable(self) -> bool: ...
-    def seekable(self) -> bool: ...
-    def write(self, b: str) -> None: ...
-    def tell(self) -> int: ...
-
 def tostringlist(element: Element, encoding: str=..., method: str=..., *, short_empty_elements: bool=...) -> List[str]: ...
 def dump(elem: Element) -> None: ...
 def parse(source: _file_or_filename, parser: 'XMLParser'=...) -> ElementTree: ...
diff --git a/typeshed/stdlib/3.5/xml/etree/ElementTree.pyi b/typeshed/stdlib/3.5/xml/etree/ElementTree.pyi
index 73b49df..8b2eecd 100644
--- a/typeshed/stdlib/3.5/xml/etree/ElementTree.pyi
+++ b/typeshed/stdlib/3.5/xml/etree/ElementTree.pyi
@@ -74,15 +74,6 @@ class ElementTree:
 
 def register_namespace(prefix: str, uri: str) -> None: ...
 def tostring(element: Element, encoding: str=..., method: str=..., *, short_empty_elements: bool=...) -> str: ...
-
-class _ListDataStream(io.BufferedIOBase):
-    lst = ... # type: List[str]
-    def __init__(self, lst) -> None: ...
-    def writable(self) -> bool: ...
-    def seekable(self) -> bool: ...
-    def write(self, b: str) -> None: ...
-    def tell(self) -> int: ...
-
 def tostringlist(element: Element, encoding: str=..., method: str=..., *, short_empty_elements: bool=...) -> List[str]: ...
 def dump(elem: Element) -> None: ...
 def parse(source: _file_or_filename, parser: 'XMLParser'=...) -> ElementTree: ...
diff --git a/typeshed/stdlib/3/__future__.pyi b/typeshed/stdlib/3/__future__.pyi
index 2414069..f59753c 100644
--- a/typeshed/stdlib/3/__future__.pyi
+++ b/typeshed/stdlib/3/__future__.pyi
@@ -1,8 +1,8 @@
-from sys import _version_info
+import sys
 
 class _Feature:
-    def getOptionalRelease(self) -> _version_info: ...
-    def getMandatoryRelease(self) -> _version_info: ...
+    def getOptionalRelease(self) -> sys._version_info: ...
+    def getMandatoryRelease(self) -> sys._version_info: ...
 
 absolute_import = ...  # type: _Feature
 division = ...  # type: _Feature
@@ -11,3 +11,6 @@ nested_scopes = ...  # type: _Feature
 print_function = ...  # type: _Feature
 unicode_literals = ...  # type: _Feature
 with_statement = ...  # type: _Feature
+
+if sys.version_info[:2] >= (3, 5):
+    generator_stop = ...  # type: _Feature
diff --git a/typeshed/stdlib/3/_ast.pyi b/typeshed/stdlib/3/_ast.pyi
index 23bf799..0c39156 100644
--- a/typeshed/stdlib/3/_ast.pyi
+++ b/typeshed/stdlib/3/_ast.pyi
@@ -9,7 +9,7 @@ identifier = str
 class AST:
     _attributes = ... # type: typing.Tuple[str, ...]
     _fields = ... # type: typing.Tuple[str, ...]
-    def __init__(self, *args, **kwargs) -> None: ...
+    def __init__(self, *args: Any, **kwargs: Any) -> None: ...
 
 class mod(AST):
     ...
diff --git a/typeshed/stdlib/3/_io.pyi b/typeshed/stdlib/3/_io.pyi
deleted file mode 100644
index f67f989..0000000
--- a/typeshed/stdlib/3/_io.pyi
+++ /dev/null
@@ -1,48 +0,0 @@
-# Stubs for _io (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-class _IOBase:
-    def __init__(self, *args, **kwargs) -> None: ...
-    @property
-    def closed(self): ...
-    def close(self): ...
-    def fileno(self): ...
-    def flush(self): ...
-    def isatty(self): ...
-    def readable(self): ...
-    def readline(self, size: int = ...): ...
-    def readlines(self, hint: int = ...): ...
-    def seek(self, offset, whence=...): ...
-    def seekable(self): ...
-    def tell(self): ...
-    def truncate(self, size: int = ...) -> int: ...
-    def writable(self): ...
-    def writelines(self, lines): ...
-    def __del__(self): ...
-    def __enter__(self): ...
-    def __exit__(self, exc_type, exc_val, exc_tb): ...
-    def __iter__(self): ...
-    def __next__(self): ...
-
-class _BufferedIOBase(_IOBase):
-    def detach(self): ...
-    def read(self, size: int = ...): ...
-    def read1(self, size: int = ...): ...
-    def readinto(self, b): ...
-    def write(self, b): ...
-
-class _RawIOBase(_IOBase):
-    def read(self, size: int = ...): ...
-    def readall(self): ...
-
-class _TextIOBase(_IOBase):
-    encoding = ...  # type: Any
-    errors = ...  # type: Any
-    newlines = ...  # type: Any
-    def detach(self): ...
-    def read(self, size: int = ...): ...
-    def readline(self, size: int = ...): ...
-    def write(self, b): ...
diff --git a/typeshed/stdlib/3/builtins.pyi b/typeshed/stdlib/3/builtins.pyi
index f7e8562..e0c4189 100644
--- a/typeshed/stdlib/3/builtins.pyi
+++ b/typeshed/stdlib/3/builtins.pyi
@@ -23,7 +23,6 @@ _T4 = TypeVar('_T4')
 
 staticmethod = object() # Only valid as a decorator.
 classmethod = object() # Only valid as a decorator.
-property = object()
 
 class object:
     __doc__ = ...  # type: str
@@ -40,10 +39,12 @@ class object:
     def __hash__(self) -> int: ...
 
 class type:
+    __bases__ = ...  # type: Tuple[type, ...]
     __name__ = ...  # type: str
     __qualname__ = ...  # type: str
     __module__ = ...  # type: str
     __dict__ = ...  # type: Dict[str, Any]
+    __mro__ = ...  # type: Tuple[type, ...]
 
     @overload
     def __init__(self, o: object) -> None: ...
@@ -54,6 +55,10 @@ class type:
     @overload
     def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ...
     def __call__(self, *args: Any, **kwds: Any) -> Any: ...
+    def __subclasses__(self) -> List[type]: ...
+    # Note: the documentation doesnt specify what the return type is, the standard
+    # implementation seems to be returning a list.
+    def mro(self) -> List[type]: ...
 
 class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
     def __init__(self, x: Union[SupportsInt, str, bytes] = None, base: int = None) -> None: ...
@@ -616,6 +621,17 @@ class module:
     __file__ = ...  # type: str
     __dict__ = ...  # type: Dict[str, Any]
 
+class property:
+    def __init__(self, fget: Callable[[Any], Any] = None,
+                 fset: Callable[[Any, Any], None] = None,
+                 fdel: Callable[[Any], None] = None, doc: str = None) -> None: ...
+    def getter(self, fget: Callable[[Any], Any]) -> property: ...
+    def setter(self, fset: Callable[[Any, Any], None]) -> property: ...
+    def deleter(self, fdel: Callable[[Any], None]) -> property: ...
+    def __get__(self, obj: Any, type: type=None) -> Any: ...
+    def __set__(self, obj: Any, value: Any) -> None: ...
+    def __delete__(self, obj: Any) -> None: ...
+
 NotImplemented = ...  # type: Any
 
 def abs(n: SupportsAbs[_T]) -> _T: ...
diff --git a/typeshed/stdlib/3/calendar.pyi b/typeshed/stdlib/3/calendar.pyi
index b5de564..632ef2b 100644
--- a/typeshed/stdlib/3/calendar.pyi
+++ b/typeshed/stdlib/3/calendar.pyi
@@ -72,4 +72,4 @@ c = ...  # type: TextCalendar
 def setfirstweekday(firstweekday: int) -> None: ...
 def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ...
 def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ...
-def timegm(tuple: Tuple[int]) -> int: ...
+def timegm(tuple: Tuple[int, ...]) -> int: ...
diff --git a/typeshed/stdlib/3/codecs.pyi b/typeshed/stdlib/3/codecs.pyi
index 94b33dd..3f1a546 100644
--- a/typeshed/stdlib/3/codecs.pyi
+++ b/typeshed/stdlib/3/codecs.pyi
@@ -68,7 +68,7 @@ def register(search_function: Callable[[str], CodecInfo]) -> None:
 def open(filename: str, mode: str = ..., encoding: str = ..., errors: str = ..., buffering: int = ...) -> StreamReaderWriter:
     ...
 
-def EncodedFile(file: BinaryIO, data_encoding: str, file_encoding: str = ..., errors = ...) -> 'StreamRecoder':
+def EncodedFile(file: BinaryIO, data_encoding: str, file_encoding: str = ..., errors: str = ...) -> 'StreamRecoder':
     ...
 
 def iterencode(iterator: Iterable[_decoded], encoding: str, errors: str = ...) -> Iterator[_encoded]:
diff --git a/typeshed/stdlib/3/datetime.pyi b/typeshed/stdlib/3/datetime.pyi
index 4d8efb8..c0ee98b 100644
--- a/typeshed/stdlib/3/datetime.pyi
+++ b/typeshed/stdlib/3/datetime.pyi
@@ -198,7 +198,7 @@ class datetime:
     def replace(self, year: int = ..., month: int = ..., day: int = ..., hour: int = ...,
                 minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo:
                 Union[_tzinfo, bool] = ...) -> datetime: ...
-    def astimezone(self, tz: timezone = ...) -> datetime: ...
+    def astimezone(self, tz: _tzinfo = ...) -> datetime: ...
     def ctime(self) -> str: ...
     def isoformat(self, sep: str = ...) -> str: ...
     @classmethod
diff --git a/typeshed/stdlib/3/email/__init__.pyi b/typeshed/stdlib/3/email/__init__.pyi
index 6cf5a07..8962ed5 100644
--- a/typeshed/stdlib/3/email/__init__.pyi
+++ b/typeshed/stdlib/3/email/__init__.pyi
@@ -1,11 +1,32 @@
 # Stubs for email (Python 3.4)
 
-from typing import IO, Any
+from typing import Callable, Optional, BinaryIO, TextIO
+import sys
+from email.message import Message, Policy
 
-def message_from_string(s: str, *args, **kwargs): ...
-def message_from_bytes(s: bytes, *args, **kwargs): ...
-def message_from_file(fp: IO[str], *args, **kwargs): ...
-def message_from_binary_file(fp: IO[bytes], *args, **kwargs): ...
+if sys.version_info >= (3, 3):
+    def message_from_string(s: str, _class: Callable[[], Message] = ..., *,
+                            policy: Policy = ...) -> Message: ...
+    def message_from_bytes(s: bytes, _class: Callable[[], Message] = ..., *,
+                           policy: Policy = ...) -> Message: ...
+    def message_from_file(fp: TextIO, _class: Callable[[], Message] = ..., *,
+                           policy: Policy = ...) -> Message: ...
+    def message_from_binary_file(fp: BinaryIO,
+                                 _class: Callable[[], Message] = ..., *,
+                                 policy: Policy = ...) -> Message: ...
+elif sys.version_info >= (3, 2):
+    def message_from_string(s: str,  # type: ignore
+                            _class: Callable[[], Message] = ..., *,
+                            strict: Optional[bool] = ...) -> Message: ...
+    def message_from_bytes(s: bytes,  # type: ignore
+                           _class: Callable[[], Message] = ..., *,
+                           strict: Optional[bool] = ...) -> Message: ...
+    def message_from_file(fp: TextIO,  # type: ignore
+                          _class: Callable[[], Message] = ..., *,
+                          strict: Optional[bool] = ...) -> Message: ...
+    def message_from_binary_file(fp: BinaryIO,  # type: ignore
+                                 _class: Callable[[], Message] = ..., *,
+                                 strict: Optional[bool] = ...) -> Message: ...
 
 # Names in __all__ with no definition:
 #   base64mime
diff --git a/typeshed/stdlib/3/email/_policybase.pyi b/typeshed/stdlib/3/email/_policybase.pyi
deleted file mode 100644
index 49af14c..0000000
--- a/typeshed/stdlib/3/email/_policybase.pyi
+++ /dev/null
@@ -1,34 +0,0 @@
-# Stubs for email._policybase (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-class _PolicyBase:
-    def __init__(self, **kw) -> None: ...
-    def clone(self, **kw): ...
-    def __setattr__(self, name, value): ...
-    def __add__(self, other): ...
-
-class Policy(_PolicyBase):
-    raise_on_defect = ...  # type: Any
-    linesep = ...  # type: Any
-    cte_type = ...  # type: Any
-    max_line_length = ...  # type: Any
-    def handle_defect(self, obj, defect): ...
-    def register_defect(self, obj, defect): ...
-    def header_max_count(self, name): ...
-    def header_source_parse(self, sourcelines): ...
-    def header_store_parse(self, name, value): ...
-    def header_fetch_parse(self, name, value): ...
-    def fold(self, name, value): ...
-    def fold_binary(self, name, value): ...
-
-class Compat32(Policy):
-    def header_source_parse(self, sourcelines): ...
-    def header_store_parse(self, name, value): ...
-    def header_fetch_parse(self, name, value): ...
-    def fold(self, name, value): ...
-    def fold_binary(self, name, value): ...
-
-compat32 = ...  # type: Any
diff --git a/typeshed/stdlib/3/email/charset.pyi b/typeshed/stdlib/3/email/charset.pyi
index 07f7ccb..cd6b6a5 100644
--- a/typeshed/stdlib/3/email/charset.pyi
+++ b/typeshed/stdlib/3/email/charset.pyi
@@ -1,25 +1,27 @@
 # Stubs for email.charset (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
-
-def add_charset(charset, header_enc=..., body_enc=..., output_charset=...): ...
-def add_alias(alias, canonical): ...
-def add_codec(charset, codecname): ...
+from typing import Optional, Iterator, Any
 
 class Charset:
-    input_charset = ...  # type: Any
-    header_encoding = ...  # type: Any
-    body_encoding = ...  # type: Any
-    output_charset = ...  # type: Any
-    input_codec = ...  # type: Any
-    output_codec = ...  # type: Any
-    def __init__(self, input_charset=...) -> None: ...
-    def __eq__(self, other): ...
-    def __ne__(self, other): ...
-    def get_body_encoding(self): ...
-    def get_output_charset(self): ...
-    def header_encode(self, string): ...
-    def header_encode_lines(self, string, maxlengths): ...
-    def body_encode(self, string): ...
+    input_charset = ...  # type: str
+    header_encoding = ...  # type: int
+    body_encoding = ...  # type: int
+    output_charset = ...  # type: Optional[str]
+    input_codec = ...  # type: Optional[str]
+    output_codec = ...  # type: Optional[str]
+    def __init__(self, input_charset: str = ...) -> None: ...
+    def get_body_encoding(self) -> str: ...
+    def get_output_charset(self) -> Optional[str]: ...
+    def header_encode(self, string: str) -> str: ...
+    def header_encode_lines(self, string: str,
+                            maxlengths: Iterator[int]) -> List[str]: ...
+    def body_encode(self, string: str) -> str: ...
+    def __str__(self) -> str: ...
+    def __eq__(self, other: Any) -> bool: ...
+    def __ne__(self, other: Any) -> bool: ...
+
+def add_charset(charset: Charset, header_enc: Optional[int] = ...,
+                body_enc: Optional[int] = ...,
+                output_charset: Optional[str] = ...) -> None: ...
+def add_alias(alias: str, canonical: str) -> None: ...
+def add_codec(charset: str, codecname: str) -> None: ...
diff --git a/typeshed/stdlib/3/email/contentmanager.pyi b/typeshed/stdlib/3/email/contentmanager.pyi
index d738689..6f37fba 100644
--- a/typeshed/stdlib/3/email/contentmanager.pyi
+++ b/typeshed/stdlib/3/email/contentmanager.pyi
@@ -1,27 +1,22 @@
 # Stubs for email.contentmanager (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
+from typing import Any, Callable
+import sys
+import email.message
+from email.message import Message
 
-class ContentManager:
-    get_handlers = ...  # type: Any
-    set_handlers = ...  # type: Any
-    def __init__(self) -> None: ...
-    def add_get_handler(self, key, handler): ...
-    def get_content(self, msg, *args, **kw): ...
-    def add_set_handler(self, typekey, handler): ...
-    def set_content(self, msg, obj, *args, **kw): ...
+if sys.version_info >= (3, 4):
 
-raw_data_manager = ...  # type: Any
+    EmailMessage = email.message.EmailMessage
+    MIMEPart = email.message.MIMEPart
 
-def get_text_content(msg, errors=...): ...
-def get_non_text_content(msg): ...
-def get_message_content(msg): ...
-def get_and_fixup_unknown_message_content(msg): ...
-def set_text_content(msg, string, subtype=..., charset=..., cte=..., disposition=...,
-                     filename=..., cid=..., params=..., headers=...): ...
-def set_message_content(msg, message, subtype=..., cte=..., disposition=..., filename=...,
-                        cid=..., params=..., headers=...): ...
-def set_bytes_content(msg, data, maintype, subtype, cte=..., disposition=..., filename=...,
-                      cid=..., params=..., headers=...): ...
+    class ContentManager:
+        def __init__(self) -> None: ...
+        def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ...
+        def set_content(self, msg: Message, obj: Any, *args: Any,
+                        **kw: Any) -> Any: ...
+        def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ...
+        def add_set_handler(self, typekey: type,
+                            handler: Callable[..., Any]) -> None: ...
+
+    raw_data_manager = ...  # type: ContentManager
diff --git a/typeshed/stdlib/3/email/errors.pyi b/typeshed/stdlib/3/email/errors.pyi
index 2f95126..b51d7d3 100644
--- a/typeshed/stdlib/3/email/errors.pyi
+++ b/typeshed/stdlib/3/email/errors.pyi
@@ -1,44 +1,22 @@
 # Stubs for email.errors (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
+import sys
 
 class MessageError(Exception): ...
 class MessageParseError(MessageError): ...
 class HeaderParseError(MessageParseError): ...
 class BoundaryError(MessageParseError): ...
 class MultipartConversionError(MessageError, TypeError): ...
-class CharsetError(MessageError): ...
-
-class MessageDefect(ValueError):
-    line = ...  # type: Any
-    def __init__(self, line=...) -> None: ...
 
+class MessageDefect(ValueError): ...
 class NoBoundaryInMultipartDefect(MessageDefect): ...
 class StartBoundaryNotFoundDefect(MessageDefect): ...
-class CloseBoundaryNotFoundDefect(MessageDefect): ...
 class FirstHeaderLineIsContinuationDefect(MessageDefect): ...
 class MisplacedEnvelopeHeaderDefect(MessageDefect): ...
-class MissingHeaderBodySeparatorDefect(MessageDefect): ...
-
-MalformedHeaderDefect = ...  # type: Any
-
+class MalformedHeaderDefect(MessageDefect): ...
 class MultipartInvariantViolationDefect(MessageDefect): ...
-class InvalidMultipartContentTransferEncodingDefect(MessageDefect): ...
-class UndecodableBytesDefect(MessageDefect): ...
 class InvalidBase64PaddingDefect(MessageDefect): ...
 class InvalidBase64CharactersDefect(MessageDefect): ...
-
-class HeaderDefect(MessageDefect):
-    def __init__(self, *args, **kw) -> None: ...
-
-class InvalidHeaderDefect(HeaderDefect): ...
-class HeaderMissingRequiredValue(HeaderDefect): ...
-
-class NonPrintableDefect(HeaderDefect):
-    non_printables = ...  # type: Any
-    def __init__(self, non_printables) -> None: ...
-
-class ObsoleteHeaderDefect(HeaderDefect): ...
-class NonASCIILocalPartDefect(HeaderDefect): ...
+if sys.version_info >= (3, 3):
+    class CloseBoundaryNotFoundDefect(MessageDefect): ...
+    class MissingHeaderBodySeparatorDefect(MessageDefect): ...
diff --git a/typeshed/stdlib/3/email/feedparser.pyi b/typeshed/stdlib/3/email/feedparser.pyi
index 135a9f8..4950fa8 100644
--- a/typeshed/stdlib/3/email/feedparser.pyi
+++ b/typeshed/stdlib/3/email/feedparser.pyi
@@ -1,26 +1,27 @@
 # Stubs for email.feedparser (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
-
-class BufferedSubFile:
-    def __init__(self) -> None: ...
-    def push_eof_matcher(self, pred): ...
-    def pop_eof_matcher(self): ...
-    def close(self): ...
-    def readline(self): ...
-    def unreadline(self, line): ...
-    def push(self, data): ...
-    def pushlines(self, lines): ...
-    def __iter__(self): ...
-    def __next__(self): ...
+from typing import Callable
+import sys
+from email.message import Message
+from email.policy import Policy
 
 class FeedParser:
-    policy = ...  # type: Any
-    def __init__(self, _factory=..., *, policy=...) -> None: ...
-    def feed(self, data): ...
-    def close(self): ...
+    if sys.version_info >= (3, 3):
+        def __init__(self, _factory: Callable[[], Message] = ..., *,
+                     policy: Policy = ...) -> None: ...
+    else:
+        def __init__(self,  # type: ignore
+                     _factory: Callable[[], Message] = ...) -> None: ...
+    def feed(self, data: str) -> None: ...
+    def close(self) -> Message: ...
 
-class BytesFeedParser(FeedParser):
-    def feed(self, data): ...
+if sys.version_info >= (3, 2):
+    class BytesFeedParser:
+        if sys.version_info >= (3, 3):
+            def __init__(self, _factory: Callable[[], Message] = ..., *,
+                         policy: Policy = ...) -> None: ...
+        else:
+            def __init__(self,  # type: ignore
+                         _factory: Callable[[], Message] = ...) -> None: ...
+        def feed(self, data: str) -> None: ...
+        def close(self) -> Message: ...
diff --git a/typeshed/stdlib/3/email/generator.pyi b/typeshed/stdlib/3/email/generator.pyi
index a8ac7b4..eb8552c 100644
--- a/typeshed/stdlib/3/email/generator.pyi
+++ b/typeshed/stdlib/3/email/generator.pyi
@@ -1,19 +1,44 @@
 # Stubs for email.generator (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
+from typing import TextIO, Optional
+import sys
+from email.policy import Policy
+from email.message import Message
 
 class Generator:
-    maxheaderlen = ...  # type: Any
-    policy = ...  # type: Any
-    def __init__(self, outfp, mangle_from_=..., maxheaderlen=..., *, policy=...) -> None: ...
-    def write(self, s): ...
-    def flatten(self, msg, unixfrom=..., linesep=...): ...
-    def clone(self, fp): ...
+    def clone(self, fp: TextIO) -> 'Generator': ...
+    def write(self, s: str) -> None: ...
+    if sys.version_info >= (3, 3):
+        def __init__(self, outfp: TextIO, mangle_from_: bool = ...,
+                     maxheaderlen: int = ..., *,
+                     policy: Policy = ...) -> None: ...
+    else:
+        def __init__(self, outfp: TextIO,  # type: ignore
+                     mangle_from_: bool = ...,
+                     maxheaderlen: int = ...) -> None: ...
+    if sys.version_info >= (3, 2):
+        def flatten(self, msg: Message, unixfrom: bool = ...,
+                    linesep: Optional[str] =...) -> None: ...
+    else:
+        def flatten(self, msg: Message,  # type: ignore
+                    unixfrom: bool = ...) -> None: ...
 
-class BytesGenerator(Generator):
-    def write(self, s): ...
+if sys.version_info >= (3, 2):
+    class BytesGenerator:
+        def clone(self, fp: TextIO) -> 'Generator': ...
+        def write(self, s: str) -> None: ...
+        if sys.version_info >= (3, 3):
+            def __init__(self, outfp: TextIO, mangle_from_: bool = ...,
+                         maxheaderlen: int = ..., *,
+                         policy: Policy = ...) -> None: ...
+        else:
+            def __init__(self, outfp: TextIO,  # type: ignore
+                         mangle_from_: bool = ...,
+                         maxheaderlen: int = ...) -> None: ...
+        def flatten(self, msg: Message, unixfrom: bool = ...,
+                    linesep: Optional[str] =...) -> None: ...
 
 class DecodedGenerator(Generator):
-    def __init__(self, outfp, mangle_from_=..., maxheaderlen=..., fmt=...) -> None: ...
+    # TODO `fmt` is positional
+    def __init__(self, outfp: TextIO, mangle_from_: bool = ...,
+                 maxheaderlen: int = ..., *, fmt: Optional[str]) -> None: ...
diff --git a/typeshed/stdlib/3/email/header.pyi b/typeshed/stdlib/3/email/header.pyi
index 7665017..051e575 100644
--- a/typeshed/stdlib/3/email/header.pyi
+++ b/typeshed/stdlib/3/email/header.pyi
@@ -1,29 +1,25 @@
 # Stubs for email.header (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-def decode_header(header): ...
-def make_header(decoded_seq, maxlinelen=..., header_name=..., continuation_ws=...): ...
+from typing import Union, Optional, Any, List, Tuple
+from email.charset import Charset
 
 class Header:
-    def __init__(self, s=..., charset=..., maxlinelen=..., header_name=...,
-                 continuation_ws=..., errors=...): ...
-    def __eq__(self, other): ...
-    def __ne__(self, other): ...
-    def append(self, s, charset=..., errors=...): ...
-    def encode(self, splitchars=..., maxlinelen=..., linesep=...): ...
+    def __init__(self, s: Union[bytes, str, None] = ...,
+                 charset: Union[Charset, str, None] = ...,
+                 maxlinelen: Optional[int] = ...,
+                 header_name: Optional[str] = ..., continuation_ws: str = ...,
+                 errors: str = ...) -> None: ...
+    def append(self, s: Union[bytes, str],
+               charset: Union[Charset, str, None] = ...,
+               errors: str = ...) -> None: ...
+    def encode(self, splitchars: str = ..., maxlinelen: Optional[int] = ...,
+               linesep: str = ...) -> str: ...
+    def __str__(self) -> str: ...
+    def __eq__(self, other: Any) -> bool: ...
+    def __ne__(self, other: Any) -> bool: ...
 
-class _ValueFormatter:
-    def __init__(self, headerlen, maxlen, continuation_ws, splitchars) -> None: ...
-    def newline(self): ...
-    def add_transition(self): ...
-    def feed(self, fws, string, charset): ...
-
-class _Accumulator(list):
-    def __init__(self, initial_size=...) -> None: ...
-    def push(self, fws, string): ...
-    def pop_from(self, i=...): ...
-    def __len__(self): ...
-    def reset(self, startval=...): ...
-    def is_onlyws(self): ...
-    def part_count(self): ...
+def decode_header(header: Header) -> List[Tuple[bytes, Optional[str]]]: ...
+def make_header(decoded_seq: List[Tuple[bytes, Optional[str]]],
+                maxlinelen: Optional[int] =...,
+                header_name: Optional[str] = ...,
+                continuation_ws: str = ...) -> Header: ...
diff --git a/typeshed/stdlib/3/email/headerregistry.pyi b/typeshed/stdlib/3/email/headerregistry.pyi
index 41123fa..078c65d 100644
--- a/typeshed/stdlib/3/email/headerregistry.pyi
+++ b/typeshed/stdlib/3/email/headerregistry.pyi
@@ -1,133 +1,101 @@
 # Stubs for email.headerregistry (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-class Address:
-    def __init__(self, display_name=..., username=..., domain=..., addr_spec=...) -> None: ...
-    @property
-    def display_name(self): ...
-    @property
-    def username(self): ...
-    @property
-    def domain(self): ...
-    @property
-    def addr_spec(self): ...
-    def __eq__(self, other): ...
-
-class Group:
-    def __init__(self, display_name=..., addresses=...) -> None: ...
-    @property
-    def display_name(self): ...
-    @property
-    def addresses(self): ...
-    def __eq__(self, other): ...
-
-class BaseHeader(str):
-    def __new__(cls, name, value): ...
-    def init(self, name, parse_tree, defects): ...
-    @property
-    def name(self): ...
-    @property
-    def defects(self): ...
-    def __reduce__(self): ...
-    def fold(self, policy): ...
-
-class UnstructuredHeader:
-    max_count = ...  # type: Any
-    value_parser = ...  # type: Any
-    @classmethod
-    def parse(cls, value, kwds): ...
-
-class UniqueUnstructuredHeader(UnstructuredHeader):
-    max_count = ...  # type: Any
-
-class DateHeader:
-    max_count = ...  # type: Any
-    value_parser = ...  # type: Any
-    @classmethod
-    def parse(cls, value, kwds): ...
-    def init(self, *args, **kw): ...
-    @property
-    def datetime(self): ...
-
-class UniqueDateHeader(DateHeader):
-    max_count = ...  # type: Any
-
-class AddressHeader:
-    max_count = ...  # type: Any
-    @staticmethod
-    def value_parser(value): ...
-    @classmethod
-    def parse(cls, value, kwds): ...
-    def init(self, *args, **kw): ...
-    @property
-    def groups(self): ...
-    @property
-    def addresses(self): ...
-
-class UniqueAddressHeader(AddressHeader):
-    max_count = ...  # type: Any
-
-class SingleAddressHeader(AddressHeader):
-    @property
-    def address(self): ...
-
-class UniqueSingleAddressHeader(SingleAddressHeader):
-    max_count = ...  # type: Any
-
-class MIMEVersionHeader:
-    max_count = ...  # type: Any
-    value_parser = ...  # type: Any
-    @classmethod
-    def parse(cls, value, kwds): ...
-    def init(self, *args, **kw): ...
-    @property
-    def major(self): ...
-    @property
-    def minor(self): ...
-    @property
-    def version(self): ...
-
-class ParameterizedMIMEHeader:
-    max_count = ...  # type: Any
-    @classmethod
-    def parse(cls, value, kwds): ...
-    def init(self, *args, **kw): ...
-    @property
-    def params(self): ...
-
-class ContentTypeHeader(ParameterizedMIMEHeader):
-    value_parser = ...  # type: Any
-    def init(self, *args, **kw): ...
-    @property
-    def maintype(self): ...
-    @property
-    def subtype(self): ...
-    @property
-    def content_type(self): ...
-
-class ContentDispositionHeader(ParameterizedMIMEHeader):
-    value_parser = ...  # type: Any
-    def init(self, *args, **kw): ...
-    @property
-    def content_disposition(self): ...
-
-class ContentTransferEncodingHeader:
-    max_count = ...  # type: Any
-    value_parser = ...  # type: Any
-    @classmethod
-    def parse(cls, value, kwds): ...
-    def init(self, *args, **kw): ...
-    @property
-    def cte(self): ...
-
-class HeaderRegistry:
-    registry = ...  # type: Any
-    base_class = ...  # type: Any
-    default_class = ...  # type: Any
-    def __init__(self, base_class=..., default_class=..., use_default_map=...) -> None: ...
-    def map_to_type(self, name, cls): ...
-    def __getitem__(self, name): ...
-    def __call__(self, name, value): ...
+
+from typing import Tuple, Optional, Any, Union, Mapping
+import sys
+from email.errors import MessageDefect
+from email.policy import Policy
+import datetime as dt
+
+if sys.version_info >= (3, 3):
+
+    class BaseHeader(str):
+        @property
+        def name(self) -> str: ...
+        @property
+        def defects(self) -> Tuple[MessageDefect, ...]: ...
+        @property
+        def max_count(self) -> Optional[int]: ...
+        def __new__(cls, name: str, value: Any) -> 'BaseHeader': ...
+        def init(self, *args: Any, **kw: Any) -> None: ...
+        def fold(self, *, policy: Policy) -> str: ...
+
+    class UnstructuredHeader:
+        @classmethod
+        def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ...
+
+    class UniqueUnstructuredHeader(UnstructuredHeader): ...
+
+    class DateHeader:
+        datetime = ...  # type: dt.datetime
+        @classmethod
+        def parse(cls, string: Union[str, dt.datetime],
+                  kwds: Dict[str, Any]) -> None: ...
+
+    class UniqueDateHeader(DateHeader): ...
+
+    class AddressHeader:
+        groups = ...  # type: Tuple[Group, ...]
+        addresses = ...  # type: Tuple[Address, ...]
+        @classmethod
+        def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ...
+
+    class UniqueAddressHeader(AddressHeader): ...
+
+    class SingleAddressHeader(AddressHeader):
+        @property
+        def address(self) -> Address: ...
+
+    class UniqueSingleAddressHeader(SingleAddressHeader): ...
+
+    class MIMEVersionHeader:
+        version = ...  # type: Optional[str]
+        major = ...  # type: Optional[int]
+        minor = ...  # type: Optional[int]
+        @classmethod
+        def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ...
+
+    class ParameterizedMIMEHeader:
+        params = ...  # type: Mapping[str, Any]
+        @classmethod
+        def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ...
+
+    class ContentTypeHeader(ParameterizedMIMEHeader):
+        content_type = ...  # type: str
+        maintype = ...  # type: str
+        subtype = ...  # type: str
+
+    class ContentDispositionHeader(ParameterizedMIMEHeader):
+        content_disposition = ...  # type: str
+
+    class ContentTransferEncoding:
+        cte = ...  # type: str
+        @classmethod
+        def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ...
+
+    class HeaderRegistry:
+        def __init__(self, base_class: BaseHeader = ...,
+                     default_class: BaseHeader = ...,
+                     use_default_map: bool = ...) -> None: ...
+        def map_to_type(self, name: str, cls: BaseHeader) -> None: ...
+        def __getitem__(self, name: str) -> BaseHeader: ...
+        def __call__(self, name: str, value: Any) -> BaseHeader: ...
+
+    class Address:
+        display_name = ...  # type: str
+        username = ...  # type: str
+        domain = ...  # type: str
+        @property
+        def addr_spec(self) -> str: ...
+        def __init__(self, display_name: str = ...,
+                     username: Optional[str] = ...,
+                     domain: Optional[str] = ...,
+                     addr_spec: Optional[str]=...) -> None: ...
+        def __str__(self) -> str: ...
+
+    class Group:
+        display_name = ...  # type: Optional[str]
+        addresses = ...  # type: Tuple[Address, ...]
+        def __init__(self, display_name: Optional[str] = ...,
+                     addresses: Optional[Tuple[Address, ...]] = ...) \
+                     -> None: ...
+        def __str__(self) -> str: ...
diff --git a/typeshed/stdlib/3/email/message.pyi b/typeshed/stdlib/3/email/message.pyi
index 57d9631..d44a77f 100644
--- a/typeshed/stdlib/3/email/message.pyi
+++ b/typeshed/stdlib/3/email/message.pyi
@@ -1,74 +1,149 @@
 # Stubs for email.message (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
+from typing import (
+        Optional, Union, Tuple, TypeVar, Generator, Sequence, Iterator, Any
+    )
+import sys
+from email.charset import Charset
+from email.errors import MessageDefect
+from email.policy import Policy
+from email.contentmanager import ContentManager
+
+_T = TypeVar('_T')
+
+_PayloadType = Union[List[Message], str]
+_CharsetType = Union[Charset, str, None]
+_ParamsType = Union[str, None, Tuple[str, Optional[str], str]]
+_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]]
 
 class Message:
-    policy = ...  # type: Any
-    preamble = ...  # type: Any
-    defects = ...  # type: Any
-    def __init__(self, policy=...) -> None: ...
-    def as_string(self, unixfrom=..., maxheaderlen=..., policy=...): ...
-    def __bytes__(self): ...
-    def as_bytes(self, unixfrom=..., policy=...): ...
-    def is_multipart(self): ...
-    def set_unixfrom(self, unixfrom): ...
-    def get_unixfrom(self): ...
-    def attach(self, payload): ...
-    def get_payload(self, i=..., decode=...): ...
-    def set_payload(self, payload, charset=...): ...
-    def set_charset(self, charset): ...
-    def get_charset(self): ...
-    def __len__(self): ...
-    def __getitem__(self, name): ...
-    def __setitem__(self, name, val): ...
-    def __delitem__(self, name): ...
-    def __contains__(self, name): ...
-    def __iter__(self): ...
-    def keys(self): ...
-    def values(self): ...
-    def items(self): ...
-    def get(self, name, failobj=...): ...
-    def set_raw(self, name, value): ...
-    def raw_items(self): ...
-    def get_all(self, name, failobj=...): ...
-    def add_header(self, _name, _value, **_params): ...
-    def replace_header(self, _name, _value): ...
-    def get_content_type(self): ...
-    def get_content_maintype(self): ...
-    def get_content_subtype(self): ...
-    def get_default_type(self): ...
-    def set_default_type(self, ctype): ...
-    def get_params(self, failobj=..., header=..., unquote=...): ...
-    def get_param(self, param, failobj=..., header=..., unquote=...): ...
-    def set_param(self, param, value, header=..., requote=..., charset=..., language=...,
-                  replace=...): ...
-    def del_param(self, param, header=..., requote=...): ...
-    def set_type(self, type, header=..., requote=...): ...
-    def get_filename(self, failobj=...): ...
-    def get_boundary(self, failobj=...): ...
-    def set_boundary(self, boundary): ...
-    def get_content_charset(self, failobj=...): ...
-    def get_charsets(self, failobj=...): ...
+    preamble = ...  # type: Optional[str]
+    epilogue = ...  # type: Optional[str]
+    defects = ...  # type: List[MessageDefect]
+    def __str__(self) -> str: ...
+    def is_multipart(self) -> bool: ...
+    def set_unixfrom(self, unixfrom: str) -> None: ...
+    def get_unixfrom(self) -> Optional[str]: ...
+    def attach(self, payload: 'Message') -> None: ...
+    def get_payload(self, i: int = ..., decode: bool = ...) -> _PayloadType: ...
+    def set_payload(self, payload: _PayloadType,
+                    charset: _CharsetType = ...) -> None: ...
+    def set_charset(self, charset: _CharsetType) -> None: ...
+    def get_charset(self) -> _CharsetType: ...
+    def __len__(self) -> int: ...
+    def __contains__(self, name: str) -> bool: ...
+    def __getitem__(self, name: str) -> Optional[str]: ...
+    def __setitem__(self, name: str, val: str) -> None: ...
+    def __delitem__(self, name: str) -> None: ...
+    def keys(self) -> List[str]: ...
+    def values(self) -> List[str]: ...
+    def items(self) -> List[Tuple[str, str]]: ...
+    def get(self, name: str, failobj: _T = ...) -> Union[str, _T]: ...
+    def get_all(self, name: str, failobj: _T = ...) -> Union[List[str], _T]: ...
+    def add_header(self, _name: str, _value: str, **_params: _ParamsType) \
+                   -> None: ...
+    def replace_header(self, _name: str, _value: str) -> None: ...
+    def get_content_type(self) -> str: ...
+    def get_content_maintype(self) -> str: ...
+    def get_content_subtype(self) -> str: ...
+    def get_default_type(self) -> str: ...
+    def set_default_type(self, ctype: str) -> None: ...
+    def get_params(self, failobj: _T = ..., header: str = ...,
+                   unquote: bool = ...) -> Union[List[Tuple[str, str]], _T]: ...
+    def get_param(self, param: str, failobj: _T = ..., header: str = ...,
+                  unquote: bool = ...) -> Union[_T, _ParamType]: ...
+    def del_param(self, param: str, header: str = ...,
+                  requote: bool = ...) -> None: ...
+    def set_type(self, type: str, header: str = ...,
+                 requote: bool = ...) -> None: ...
+    def get_filename(self, failobj: _T = ...) -> Union[_T, str]: ...
+    def get_boundary(self, failobj: _T = ...) -> Union[_T, str]: ...
+    def set_boundary(self, boundary: str) -> None: ...
+    def get_content_charset(self, failobj: _T = ...) -> Union[_T, str]: ...
+    def get_charsets(self, failobj: _T = ...) -> Union[_T, List[str]]: ...
+    def walk(self) -> Generator['Message', None, None]: ...
+    if sys.version_info >= (3, 5):
+        def get_content_disposition(self) -> Optional[str]: ...
+    if sys.version_info >= (3, 4):
+        def as_string(self, unixfrom: bool = ..., maxheaderlen: int = ...,
+                      policy: Optional[Policy] = ...) -> str: ...
+        def as_bytes(self, unixfrom: bool = ...,
+                     policy: Optional[Policy] = ...) -> bytes: ...
+        def __bytes__(self) -> bytes: ...
+        def set_param(self, param: str, value: str, header: str = ...,
+                      requote: bool = ..., charset: str = ...,
+                      language: str = ..., replace: bool = ...) -> None: ...
+    else:
+        def as_string(self, unixfrom: bool = ...,  # type: ignore
+                      maxheaderlen: int = ...) -> str: ...
+        def set_param(self, param: str, value: str,  # type: ignore
+                      header: str = ..., requote: bool = ...,
+                      charset: str = ..., language: str = ...) -> None: ...
+    if sys.version_info >= (3, 3):
+        def __init__(self, policy: Policy = ...) -> None: ...
+    else:
+        def __init__(self) -> None: ...  # type: ignore
 
-class MIMEPart(Message):
-    def __init__(self, policy=...) -> None: ...
-    @property
-    def is_attachment(self): ...
-    def get_body(self, preferencelist=...): ...
-    def iter_attachments(self): ...
-    def iter_parts(self): ...
-    def get_content(self, *args, content_manager=..., **kw): ...
-    def set_content(self, *args, content_manager=..., **kw): ...
-    def make_related(self, boundary=...): ...
-    def make_alternative(self, boundary=...): ...
-    def make_mixed(self, boundary=...): ...
-    def add_related(self, *args, **kw): ...
-    def add_alternative(self, *args, **kw): ...
-    def add_attachment(self, *args, **kw): ...
-    def clear(self): ...
-    def clear_content(self): ...
+class EmailMessage:
+    def __init__(self, policy: Policy = ...) -> None: ...
+    def get_body(self,
+                 preferencelist: Sequence[str] = ...) -> Optional[Message]: ...
+    def iter_attachments(self) -> Iterator[Message]: ...
+    def iter_parts(self) -> Iterator[Message]: ...
+    def get_content(self, *args: Any,
+                    content_manager: Optional[ContentManager] = ...,
+                    **kw: Any) -> Any: ...
+    def set_content(self, *args: Any,
+                    content_manager: Optional[ContentManager] = ...,
+                    **kw: Any) -> None: ...
+    def make_related(self, boundary: Optional[str] = ...) -> None: ...
+    def make_alternative(self, boundary: Optional[str] = ...) -> None: ...
+    def make_mixed(self, boundary: Optional[str] = ...) -> None: ...
+    def add_related(self, *args: Any,
+                    content_manager: Optional[ContentManager] = ...,
+                    **kw: Any) -> None: ...
+    def add_alternative(self, *args: Any,
+                        content_manager: Optional[ContentManager] = ...,
+                        **kw: Any) -> None: ...
+    def add_attachement(self, *args: Any,
+                        content_manager: Optional[ContentManager] = ...,
+                        **kw: Any) -> None: ...
+    def clear(self) -> None: ...
+    def clear_content(self) -> None: ...
+    if sys.version_info >= (3, 4, 2):
+        def is_attachment(self) -> bool: ...
+    else:
+        @property
+        def is_attachment(self) -> bool: ...
 
-class EmailMessage(MIMEPart):
-    def set_content(self, *args, **kw): ...
+class MIMEPart:
+    def __init__(self, policy: Policy = ...) -> None: ...
+    def get_body(self,
+                 preferencelist: Sequence[str] = ...) -> Optional[Message]: ...
+    def iter_attachments(self) -> Iterator[Message]: ...
+    def iter_parts(self) -> Iterator[Message]: ...
+    def get_content(self, *args: Any,
+                    content_manager: Optional[ContentManager] = ...,
+                    **kw: Any) -> Any: ...
+    def set_content(self, *args: Any,
+                    content_manager: Optional[ContentManager] = ...,
+                    **kw: Any) -> None: ...
+    def make_related(self, boundary: Optional[str] = ...) -> None: ...
+    def make_alternative(self, boundary: Optional[str] = ...) -> None: ...
+    def make_mixed(self, boundary: Optional[str] = ...) -> None: ...
+    def add_related(self, *args: Any,
+                    content_manager: Optional[ContentManager] = ...,
+                    **kw: Any) -> None: ...
+    def add_alternative(self, *args: Any,
+                        content_manager: Optional[ContentManager] = ...,
+                        **kw: Any) -> None: ...
+    def add_attachement(self, *args: Any,
+                        content_manager: Optional[ContentManager] = ...,
+                        **kw: Any) -> None: ...
+    def clear(self) -> None: ...
+    def clear_content(self) -> None: ...
+    if sys.version_info >= (3, 4, 2):
+        def is_attachment(self) -> bool: ...
+    else:
+        @property
+        def is_attachment(self) -> bool: ...
diff --git a/typeshed/stdlib/3/email/parser.pyi b/typeshed/stdlib/3/email/parser.pyi
index b8fc6ab..d5e7348 100644
--- a/typeshed/stdlib/3/email/parser.pyi
+++ b/typeshed/stdlib/3/email/parser.pyi
@@ -1,29 +1,61 @@
 # Stubs for email.parser (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
+from typing import Callable, Optional, TextIO, BinaryIO
 import email.feedparser
+from email.message import Message
+from email.policy import Policy
+import sys
 
 FeedParser = email.feedparser.FeedParser
 BytesFeedParser = email.feedparser.BytesFeedParser
 
 class Parser:
-    policy = ...  # type: Any
-    def __init__(self, _class=..., *, policy=...) -> None: ...
-    def parse(self, fp, headersonly=...): ...
-    def parsestr(self, text, headersonly=...): ...
+    if sys.version_info >= (3, 3):
+        def __init__(self, _class: Callable[[], Message] = ..., *,
+                     policy: Policy = ...) -> None: ...
+    else:
+        # TODO `strict` is positional
+        def __init__(self,  # type: ignore
+                     _class: Callable[[], Message] = ..., *,
+                     strict: Optional[bool]) -> None: ...
+    def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ...
+    def parsestr(self, text: str, headersonly: bool = ...) -> Message: ...
 
 class HeaderParser(Parser):
-    def parse(self, fp, headersonly=...): ...
-    def parsestr(self, text, headersonly=...): ...
+    if sys.version_info >= (3, 3):
+        def __init__(self, _class: Callable[[], Message] = ..., *,
+                     policy: Policy = ...) -> None: ...
+    else:
+        # TODO `strict` is positional
+        def __init__(self,  # type: ignore
+                     _class: Callable[[], Message] = ..., *,
+                     strict: Optional[bool]) -> None: ...
+    def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ...
+    def parsestr(self, text: str, headersonly: bool = ...) -> Message: ...
 
-class BytesParser:
-    parser = ...  # type: Any
-    def __init__(self, *args, **kw) -> None: ...
-    def parse(self, fp, headersonly=...): ...
-    def parsebytes(self, text, headersonly=...): ...
+if sys.version_info >= (3, 3):
+    class BytesHeaderParser(BytesParser):
+        if sys.version_info >= (3, 3):
+            def __init__(self, _class: Callable[[], Message] = ..., *,
+                         policy: Policy = ...) -> None: ...
+        else:
+            # TODO `strict` is positional
+            def __init__(self,  # type: ignore
+                         _class: Callable[[], Message] = ..., *,
+                         strict: Optional[bool]) -> None: ...
+        def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ...
+        def parsestr(self, text: str, headersonly: bool = ...) -> Message: ...
+
+if sys.version_info >= (3, 2):
+    class BytesParser:
+        if sys.version_info >= (3, 3):
+            def __init__(self, _class: Callable[[], Message] = ..., *,
+                         policy: Policy = ...) -> None: ...
+        else:
+            # TODO `strict` is positional
+            def __init__(self,  # type: ignore
+                         _class: Callable[[], Message] = ..., *,
+                         strict: Optional[bool]) -> None: ...
+        def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ...
+        def parsestr(self, text: str, headersonly: bool = ...) -> Message: ...
 
-class BytesHeaderParser(BytesParser):
-    def parse(self, fp, headersonly=...): ...
-    def parsebytes(self, text, headersonly=...): ...
diff --git a/typeshed/stdlib/3/email/policy.pyi b/typeshed/stdlib/3/email/policy.pyi
index 26c5dc3..28f72bd 100644
--- a/typeshed/stdlib/3/email/policy.pyi
+++ b/typeshed/stdlib/3/email/policy.pyi
@@ -1,26 +1,68 @@
 # Stubs for email.policy (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
-import email._policybase
+from typing import Any, Optional, Tuple, Union, Callable
+import sys
+from email.message import Message
+from email.errors import MessageDefect
+from email.header import Header
+from email.contentmanager import ContentManager
+from abc import abstractmethod
 
-Policy = email._policybase.Policy
-Compat32 = email._policybase.Compat32
+if sys.version_info >= (3, 3):
 
-class EmailPolicy(Policy):
-    refold_source = ...  # type: Any
-    header_factory = ...  # type: Any
-    content_manager = ...  # type: Any
-    def __init__(self, **kw) -> None: ...
-    def header_max_count(self, name): ...
-    def header_source_parse(self, sourcelines): ...
-    def header_store_parse(self, name, value): ...
-    def header_fetch_parse(self, name, value): ...
-    def fold(self, name, value): ...
-    def fold_binary(self, name, value): ...
+    class Policy:
+        max_line_length = ...  # type: Optional[int]
+        linesep = ...  # type: str
+        cte_type = ...  # type: str
+        raise_on_defect = ...  # type: bool
+        if sys.version_info >= (3, 5):
+            mange_from = ...  # type: bool
+        def __init__(**kw: Any) -> None: ...
+        def clone(**kw: Any) -> 'Policy': ...
+        def handle_defect(self, obj: Message,
+                          defect: MessageDefect) -> None: ...
+        def register_defect(self, obj: Message,
+                            defect: MessageDefect) -> None: ...
+        def header_max_count(self, name: str) -> Optional[int]: ...
+        @abstractmethod
+        def header_source_parse(self, sourcelines: List[str]) -> str: ...
+        @abstractmethod
+        def header_store_parse(self, name: str,
+                               value: str) -> Tuple[str, str]: ...
+        @abstractmethod
+        def header_fetch_parse(self, name: str,
+                               value: str) -> str: ...
+        @abstractmethod
+        def fold(self, name: str, value: str) -> str: ...
+        @abstractmethod
+        def fold_binary(self, name: str, value: str) -> bytes: ...
 
-default = ...  # type: Any
-strict = ...  # type: Any
-SMTP = ...  # type: Any
-HTTP = ...  # type: Any
+    class Compat32(Policy):
+        def header_source_parse(self, sourcelines: List[str]) -> str: ...
+        def header_store_parse(self, name: str,
+                               value: str) -> Tuple[str, str]: ...
+        def header_fetch_parse(self, name: str,  # type: ignore
+                               value: str) -> Union[str, Header]: ...
+        def fold(self, name: str, value: str) -> str: ...
+        def fold_binary(self, name: str, value: str) -> bytes: ...
+
+    compat32 = ...  # type: Compat32
+
+    class EmailPolicy(Policy):
+        utf8 = ...  # type: bool
+        refold_source = ...  # type: str
+        header_factory = ...  # type: Callable[[str, str], str]
+        if sys.version_info >= (3, 4):
+            content_manager = ...  # type: ContentManager
+        def header_source_parse(self, sourcelines: List[str]) -> str: ...
+        def header_store_parse(self, name: str,
+                               value: str) -> Tuple[str, str]: ...
+        def header_fetch_parse(self, name: str, value: str) -> str: ...
+        def fold(self, name: str, value: str) -> str: ...
+        def fold_binary(self, name: str, value: str) -> bytes: ...
+
+    default = ...  # type: EmailPolicy
+    SMTP = ...  # type: EmailPolicy
+    SMTPUTF8 = ...  # type: EmailPolicy
+    HTTP = ...  # type: EmailPolicy
+    strict = ...  # type: EmailPolicy
diff --git a/typeshed/stdlib/3/getopt.pyi b/typeshed/stdlib/3/getopt.pyi
index 169c4e1..dc75699 100644
--- a/typeshed/stdlib/3/getopt.pyi
+++ b/typeshed/stdlib/3/getopt.pyi
@@ -5,12 +5,12 @@
 from typing import List, Tuple
 
 def getopt(args: List[str], shortopts: str,
-           longopts: List[str]) -> Tuple[List[Tuple[str, str]],
-                                         List[str]]: ...
+           longopts: List[str]=...) -> Tuple[List[Tuple[str, str]],
+                                             List[str]]: ...
 
 def gnu_getopt(args: List[str], shortopts: str,
-               longopts: List[str]) -> Tuple[List[Tuple[str, str]],
-                                             List[str]]: ...
+               longopts: List[str]=...) -> Tuple[List[Tuple[str, str]],
+                                                 List[str]]: ...
 
 class GetoptError(Exception):
     msg = ...  # type: str
diff --git a/typeshed/stdlib/3/getpass.pyi b/typeshed/stdlib/3/getpass.pyi
index 96c5428..73c0cb9 100644
--- a/typeshed/stdlib/3/getpass.pyi
+++ b/typeshed/stdlib/3/getpass.pyi
@@ -3,7 +3,7 @@
 from typing import TextIO
 
 
-def getpass(prompt: str = ..., stream: TextIO = None): ...
+def getpass(prompt: str = ..., stream: TextIO = None) -> str: ...
 
 
 def getuser() -> str: ...
diff --git a/typeshed/stdlib/3/gettext.pyi b/typeshed/stdlib/3/gettext.pyi
index 339f8a9..fef481a 100644
--- a/typeshed/stdlib/3/gettext.pyi
+++ b/typeshed/stdlib/3/gettext.pyi
@@ -1,39 +1,44 @@
 # Stubs for gettext (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
 
-from typing import Any
+from typing import Any, IO, List, Optional, Union, Callable
 
 class NullTranslations:
-    def __init__(self, fp=...) -> None: ...
-    def add_fallback(self, fallback): ...
-    def gettext(self, message): ...
-    def lgettext(self, message): ...
-    def ngettext(self, msgid1, msgid2, n): ...
-    def lngettext(self, msgid1, msgid2, n): ...
-    def info(self): ...
-    def charset(self): ...
-    def output_charset(self): ...
-    def set_output_charset(self, charset): ...
-    def install(self, names=...): ...
+    def __init__(self, fp: IO[str] = ...) -> None: ...
+    def add_fallback(self, fallback: NullTranslations) -> None: ...
+    def gettext(self, message: str) -> str: ...
+    def lgettext(self, message: str) -> str: ...
+    def ngettext(self, singular: str, plural: str, n: int) -> str: ...
+    def lngettext(self, singular: str, plural: str, n: int) -> str: ...
+    def info(self) -> Any: ...
+    def charset(self) -> Any: ...
+    def output_charset(self) -> Any: ...
+    def set_output_charset(self, charset: Any) -> None: ...
+    def install(self, names: List[str] = ...) -> None: ...
 
 class GNUTranslations(NullTranslations):
-    LE_MAGIC = ...  # type: Any
-    BE_MAGIC = ...  # type: Any
-    def lgettext(self, message): ...
-    def lngettext(self, msgid1, msgid2, n): ...
-    def gettext(self, message): ...
-    def ngettext(self, msgid1, msgid2, n): ...
-
-def find(domain, localedir=..., languages=..., all=...): ...
-def translation(domain, localedir=..., languages=..., class_=..., fallback=...,
-                codeset=...): ...
-def install(domain, localedir=..., codeset=..., names=...): ...
-def textdomain(domain=...): ...
-def bindtextdomain(domain, localedir=...): ...
-def dgettext(domain, message): ...
-def dngettext(domain, msgid1, msgid2, n): ...
-def gettext(message): ...
-def ngettext(msgid1, msgid2, n): ...
-
-Catalog = ...  # type: Any
+    LE_MAGIC = ...  # type: int
+    BE_MAGIC = ...  # type: int
+
+def find(domain: str, localedir: str = ..., languages: List[str] = ...,
+         all: bool = ...): ...
+
+def translation(domain: str, localedir: str = ..., languages: List[str] = ...,
+                class_: Callable[[IO[str]], NullTranslations] = ...,
+                fallback: bool =... , codeset: Any = ...) -> NullTranslations: ...
+
+def install(domain: str, localedir: str = ..., codeset: Any = ...,
+            names: List[str] = ...): ...
+
+def textdomain(domain: str = ...) -> str: ...
+def bindtextdomain(domain: str, localedir: str = ...) -> str: ...
+def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ...
+def dgettext(domain: str, message: str) -> str: ...
+def ldgettext(domain: str, message: str) -> str: ...
+def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ...
+def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ...
+def gettext(message: str) -> str: ...
+def lgettext(message: str) -> str: ...
+def ngettext(singular: str, plural: str, n: int) -> str: ...
+def lngettext(singular: str, plural: str, n: int) -> str: ...
+
+Catalog = translation
diff --git a/typeshed/stdlib/3/html/__init__.pyi b/typeshed/stdlib/3/html/__init__.pyi
index c8577ea..af2a800 100644
--- a/typeshed/stdlib/3/html/__init__.pyi
+++ b/typeshed/stdlib/3/html/__init__.pyi
@@ -1,4 +1,4 @@
 from typing import AnyStr
 
-def escape(s: AnyStr, quote: bool) -> AnyStr: ...
+def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ...
 def unescape(s: AnyStr) -> AnyStr: ...
diff --git a/typeshed/stdlib/3/html/parser.pyi b/typeshed/stdlib/3/html/parser.pyi
index 4328f3f..f49627d 100644
--- a/typeshed/stdlib/3/html/parser.pyi
+++ b/typeshed/stdlib/3/html/parser.pyi
@@ -1,28 +1,33 @@
-from typing import AnyStr, List, Tuple
+from typing import List, Tuple
 from _markupbase import ParserBase
+import sys
 
 class HTMLParser(ParserBase):
-    def __init__(self, *args, convert_charrefs: bool) -> None: ...
-    def feed(self, feed: AnyStr) -> None: ...
+    if sys.version_info >= (3, 5):
+        def __init__(self, *, convert_charrefs: bool = ...) -> None: ...
+    elif sys.version_info >= (3, 4):
+        def __init__(self, strict: bool = ..., *,  # type: ignore
+                     convert_charrefs: bool = ...) -> None: ...
+    else:
+        def __init__(self, strict: bool = ...) -> None: ...  # type: ignore
+    def feed(self, feed: str) -> None: ...
     def close(self) -> None: ...
     def reset(self) -> None: ...
+    def getpos(self) -> Tuple[int, int]: ...
+    def get_starttag_text(self) -> str: ...
 
-    def get_starttag_text(self) -> AnyStr: ...
-    def set_cdata_mode(self, AnyStr) -> None: ...
-    def clear_cdata_mode(self) -> None: ...
+    def handle_starttag(self, tag: str,
+                        attrs: List[Tuple[str, str]]) -> None: ...
+    def handle_endtag(self, tag: str) -> None: ...
+    def handle_startendtag(self, tag: str,
+                           attrs: List[Tuple[str, str]]) -> None: ...
+    def handle_data(self, data: str) -> None: ...
+    def handle_entityref(self, name: str) -> None: ...
+    def handle_charref(self, name: str) -> None: ...
+    def handle_comment(self, data: str) -> None: ...
+    def handle_decl(self, decl: str) -> None: ...
+    def handle_pi(self, data: str) -> None: ...
+    def unknown_decl(self, data: str) -> None: ...
 
-    def handle_startendtag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ...
-    def handle_starttag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ...
-    def handle_endtag(self, tag: AnyStr): ...
-    def handle_charref(self, name: AnyStr): ...
-    def handle_entityref(self, name: AnyStr): ...
-    def handle_data(self, data: AnyStr): ...
-    def handle_comment(self, data: AnyStr): ...
-    def handle_decl(self, decl: AnyStr): ...
-    def handle_pi(self, data: AnyStr): ...
-
-    def unknown_decl(self, data: AnyStr): ...
-
-    def unescape(self, s: AnyStr) -> AnyStr: ...
-
-class HTMLParseError(Exception): ...
+if sys.version_info < (3, 5):
+    class HTMLParseError(Exception): ...
diff --git a/typeshed/stdlib/3/io.pyi b/typeshed/stdlib/3/io.pyi
index 2cc7ee9..8a41482 100644
--- a/typeshed/stdlib/3/io.pyi
+++ b/typeshed/stdlib/3/io.pyi
@@ -1,150 +1,251 @@
 # Stubs for io
 
-# Based on http://docs.python.org/3.2/library/io.html
-
-from typing import List, BinaryIO, TextIO, IO, overload, Iterator, Iterable, Any
+from typing import (
+    List, BinaryIO, TextIO, Iterator, Union, Optional, Callable, Tuple, Any, IO
+)
 import builtins
 import codecs
-import _io
+import sys
+from types import TracebackType
+
+DEFAULT_BUFFER_SIZE = ...  # type: int
 
-DEFAULT_BUFFER_SIZE = 0  # type: int
 SEEK_SET = ...  # type: int
 SEEK_CUR = ...  # type: int
 SEEK_END = ...  # type: int
 
 open = builtins.open
 
-class BlockingIOError(OSError): ...
-class UnsupportedOperation(ValueError, OSError): ...
-
-class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
-    newlines = ...  # type: Any
-    def __init__(self, *args, **kwargs) -> None: ...
-    def decode(self, input, final=...): ...
-    def getstate(self): ...
-    def reset(self): ...
-    def setstate(self, state): ...
-
-class IOBase(_io._IOBase): ...
-class RawIOBase(_io._RawIOBase, IOBase): ...
-class BufferedIOBase(_io._BufferedIOBase, IOBase): ...
-class TextIOBase(_io._TextIOBase, IOBase): ...
-
-class FileIO(_io._RawIOBase):
-    closefd = ...  # type: Any
-    mode = ...  # type: Any
-    def __init__(self, name, mode=..., closefd=..., opener=...) -> None: ...
-    def readinto(self, b): ...
-    def write(self, b): ...
-
-class BufferedReader(_io._BufferedIOBase):
-    mode = ...  # type: Any
-    name = ...  # type: Any
-    raw = ...  # type: Any
-    def __init__(self, raw, buffer_size=...) -> None: ...
-    def peek(self, size: int = ...): ...
-
-class BufferedWriter(_io._BufferedIOBase):
-    mode = ...  # type: Any
-    name = ...  # type: Any
-    raw = ...  # type: Any
-    def __init__(self, raw, buffer_size=...) -> None: ...
-
-class BufferedRWPair(_io._BufferedIOBase):
-    def __init__(self, reader, writer, buffer_size=...) -> None: ...
-    def peek(self, size: int = ...): ...
-
-class BufferedRandom(_io._BufferedIOBase):
-    mode = ...  # type: Any
-    name = ...  # type: Any
-    raw = ...  # type: Any
-    def __init__(self, raw, buffer_size=...) -> None: ...
-    def peek(self, size: int = ...): ...
-
-class BytesIO(BinaryIO):
-    def __init__(self, initial_bytes: bytes = ...) -> None: ...
-    # TODO getbuffer
-    # TODO see comments in BinaryIO for missing functionality
+# FIXME when mypy handle condtional, we can uncomment the next block and remove
+# the temporary fix
+#if sys.version_info >= (3, 3):
+#    BlockingIOError = BlockingIOError
+#    class UnsupportedOperation(OSError, ValueError): ...
+#else:
+#    class BlockingIOError(IOError):
+#        characters_written = ...  # type: int
+#    class UnsupportedOperation(IOError, ValueError): ...
+class BlockingIOError(OSError):
+    characters_written = ...  # type: int
+class UnsupportedOperation(OSError, ValueError): ...
+
+
+class IOBase:
+    def __iter__(self) -> Iterator[bytes]: ...
+    def __next__(self) -> bytes: ...
+    def __enter__(self) -> 'IOBase': ...
+    def __exit__(self, exc_type: Optional[type], exc_val: Optional[Exception],
+                 exc_tb: Optional[TracebackType]) -> bool: ...
     def close(self) -> None: ...
-    @property
-    def closed(self) -> bool: ...
     def fileno(self) -> int: ...
     def flush(self) -> None: ...
     def isatty(self) -> bool: ...
-    def read(self, n: int = ...) -> bytes: ...
     def readable(self) -> bool: ...
-    def readline(self, limit: int = ...) -> bytes: ...
     def readlines(self, hint: int = ...) -> List[bytes]: ...
     def seek(self, offset: int, whence: int = ...) -> int: ...
     def seekable(self) -> bool: ...
     def tell(self) -> int: ...
-    def truncate(self, size: int = ...) -> int: ...
+    def truncate(self, size: Optional[int] = ...) -> int: ...
     def writable(self) -> bool: ...
-    @overload
-    def write(self, s: bytes) -> int: ...
-    @overload
-    def write(self, s: bytearray) -> int: ...
-    def writelines(self, lines: Iterable[bytes]) -> None: ...
+    def writelines(self, lines: List[Union[bytes, bytearray]]) -> None: ...
+    if sys.version_info >= (3, 4):
+        def readline(self, size: int = ...) -> bytes: ...
+        def __del__(self) -> None: ...
+    else:
+        def readline(self, limit: int = ...) -> bytes: ...  # type: ignore
+    if sys.version_info >= (3, 2):
+        closed = ...  # type: bool
+    else:
+        def closed(self) -> bool: ...  # type: ignore
+
+class RawIOBase(IOBase):
+    def readall(self) -> bytes: ...
+    def readinto(self, b: bytearray) -> Optional[int]: ...
+    def write(self, b: Union[bytes, bytearray]) -> Optional[int]: ...
+    if sys.version_info >= (3, 4):
+        def read(self, size: int = ...) -> Optional[bytes]: ...
+    else:
+        def read(self, n: int = ...) -> Optional[bytes]: ...  # type: ignore
+
+class BufferedIOBase(IOBase):
+    def detach(self) -> RawIOBase: ...
+    def readinto(self, b: bytearray) -> int: ...
+    def write(self, b: Union[bytes, bytearray]) -> int: ...
+    if sys.version_info >= (3, 5):
+        def readinto1(self, b: bytearray) -> int: ...
+    if sys.version_info >= (3, 4):
+        def read(self, size: Optional[int] = ...) -> bytes: ...
+        def read1(self, size: int = ...) -> bytes: ...
+    else:
+        def read(self, n: Optional[int] = ...) -> bytes: ...  # type: ignore
+        def read1(self, n: int = ...) -> bytes: ...  # type: ignore
+
+
+class FileIO(RawIOBase):
+    mode = ...  # type: str
+    name = ...  # type: Union[int, str]
+    if sys.version_info >= (3, 3):
+        def __init__(self, name: Union[str, bytes, int], mode: str = ...,
+                     closefd: bool = ...,
+                     opener: Optional[
+                         Callable[[Union[int, str], str], int]] = ...) \
+                     -> None: ...
+    else:
+        def __init__(self, name: Union[str, bytes, int],  # type: ignore
+                     mode: str = ..., closefd: bool = ...) -> None: ...
+
+# TODO should extend from BufferedIOBase
+class BytesIO(BinaryIO):
+    def __init__(self, initial_bytes: bytes = ...) -> None: ...
     def getvalue(self) -> bytes: ...
-    def read1(self) -> str: ...
-
+    if sys.version_info >= (3, 2):
+        def getbuffer(self) -> memoryview: ...
+    # copied from IOBase
     def __iter__(self) -> Iterator[bytes]: ...
+    def __next__(self) -> bytes: ...
     def __enter__(self) -> 'BytesIO': ...
-    def __exit__(self, t: type = None, value: BaseException = None, traceback: Any = None) -> bool: ...
-
-class StringIO(TextIO):
-    def __init__(self, initial_value: str = ...,
-                 newline: str = ...) -> None: ...
-    # TODO see comments in BinaryIO for missing functionality
+    def __exit__(self, t: type = None, value: BaseException = None,
+                 traceback: Any = None) -> bool: ...
     def close(self) -> None: ...
-    @property
-    def closed(self) -> bool: ...
     def fileno(self) -> int: ...
     def flush(self) -> None: ...
     def isatty(self) -> bool: ...
-    def read(self, n: int = ...) -> str: ...
     def readable(self) -> bool: ...
-    def readline(self, limit: int = ...) -> str: ...
-    def readlines(self, hint: int = ...) -> List[str]: ...
+    def readlines(self, hint: int = ...) -> List[bytes]: ...
     def seek(self, offset: int, whence: int = ...) -> int: ...
     def seekable(self) -> bool: ...
     def tell(self) -> int: ...
-    def truncate(self, size: int = ...) -> int: ...
+    def truncate(self, size: Optional[int] = ...) -> int: ...
     def writable(self) -> bool: ...
-    def write(self, s: str) -> int: ...
-    def writelines(self, lines: Iterable[str]) -> None: ...
-    def getvalue(self) -> str: ...
+    # TODO should be the next line instead
+    # def writelines(self, lines: List[Union[bytes, bytearray]]) -> None: ...
+    def writelines(self, lines: Any) -> None: ...
+    if sys.version_info >= (3, 4):
+        def readline(self, size: int = ...) -> bytes: ...
+        def __del__(self) -> None: ...
+    else:
+        def readline(self, limit: int = ...): ...  # type: ignore
+    if sys.version_info >= (3, 2):
+        closed = ...  # type: bool
+    else:
+        def closed(self) -> bool: ...  # type: ignore
+    # copied from BufferedIOBase
+    def detach(self) -> RawIOBase: ...
+    def readinto(self, b: bytearray) -> int: ...
+    def write(self, b: Union[bytes, bytearray]) -> Optional[int]: ...
+    if sys.version_info >= (3, 5):
+        def readinto1(self, b: bytearray) -> int: ...
+    if sys.version_info >= (3, 4):
+        def read(self, size: Optional[int] = ...) -> bytes: ...
+        def read1(self, size: int = ...) -> bytes: ...
+    else:
+        def read(self, n: Optional[int] = ...) -> bytes: ...  # type: ignore
+        def read1(self, n: int = ...) -> bytes: ...  # type: ignore
+
+class BufferedReader(BufferedIOBase):
+    def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ...
+    if sys.version_info >= (3, 4):
+        def peek(self, size: int = ...) -> bytes: ...
+    else:
+        def peek(self, n: int = ...) -> bytes: ...  # type: ignore
+
+class BufferedWriter(BufferedIOBase):
+    def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ...
+    def flush(self) -> None: ...
+    def write(self, b: Union[bytes, bytearray]) -> int: ...
+
+class BufferedRandom(BufferedReader, BufferedWriter):
+    def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ...
+    def seek(self, offset: int, whence: int = ...) -> int: ...
+    def tell(self) -> int: ...
 
-    def __iter__(self) -> Iterator[str]: ...
-    def __enter__(self) -> 'StringIO': ...
-    def __exit__(self, t: type = None, value: BaseException = None, traceback: Any = None) -> bool: ...
+class BufferedRWPair(BufferedIOBase):
+    def __init__(self, reader: RawIOBase, writer: RawIOBase,
+                 buffer_size: int = ...) -> None: ...
 
+
+class TextIOBase(IOBase):
+    encoding = ...  # type: str
+    errors = ...  # type: Optional[str]
+    newlines = ...  # type: Union[str, Tuple[str, ...], None]
+    def __iter__(self) -> Iterator[str]: ...  # type: ignore
+    def __next__(self) -> str: ...  # type: ignore
+    def __enter__(self) -> 'TextIOBase': ...
+    def detach(self) -> IOBase: ...
+    def write(self, s: str) -> int: ...
+    if sys.version_info >= (3, 4):
+        def readline(self, size: int = ...) -> str: ...  # type: ignore
+        def read(self, size: Optional[int] = ...) -> str: ...
+    elif sys.version_info >= (3, 2):
+        def readline(self, limit: int = ...) -> str: ...  # type: ignore
+    else:
+        def readline(self) -> str: ...  # type: ignore
+    if sys.version_info >= (3, 2):
+        def seek(self, offset: int, whence: int = ...) -> int: ...
+        def tell(self) -> int: ...
+
+# TODO should extend from TextIOBase
 class TextIOWrapper(TextIO):
-    # TODO: This is actually a base class of _io._TextIOBase.
-    # write_through is undocumented but used by subprocess
+    line_buffering = ...  # type: bool
+    # TODO uncomment after fixing mypy about using write_through
+    #if sys.version_info >= (3, 3):
+    #    def __init__(self, buffer: IO[bytes], encoding: str = ...,
+    #                 errors: Optional[str] = ..., newline: Optional[str] = ...,
+    #                 line_buffering: bool = ..., write_through: bool = ...) \
+    #                 -> None: ...
+    #else:
+    #    def __init__(self, buffer: IO[bytes],  # type: ignore
+    #                 encoding: str = ..., errors: Optional[str] = ...,
+    #                 newline: Optional[str] = ..., line_buffering: bool = ...) \
+    #                 -> None: ...
     def __init__(self, buffer: IO[bytes], encoding: str = ...,
-                 errors: str = ..., newline: str = ...,
-                 line_buffering: bool = ...,
-                 write_through: bool = ...) -> None: ...
-    # TODO see comments in BinaryIO for missing functionality
+                 errors: Optional[str] = ..., newline: Optional[str] = ...,
+                 line_buffering: bool = ..., write_through: bool = ...) \
+                 -> None: ...
+    # copied from IOBase
+    def __exit__(self, t: type = None, value: BaseException = None,
+                 traceback: Any = None) -> bool: ...
     def close(self) -> None: ...
-    @property
-    def closed(self) -> bool: ...
     def fileno(self) -> int: ...
     def flush(self) -> None: ...
     def isatty(self) -> bool: ...
-    def read(self, n: int = ...) -> str: ...
     def readable(self) -> bool: ...
-    def readline(self, limit: int = ...) -> str: ...
     def readlines(self, hint: int = ...) -> List[str]: ...
-    def seek(self, offset: int, whence: int = ...) -> int: ...
     def seekable(self) -> bool: ...
-    def tell(self) -> int: ...
-    def truncate(self, size: int = ...) -> int: ...
+    def truncate(self, size: Optional[int] = ...) -> int: ...
     def writable(self) -> bool: ...
+    # TODO should be the next line instead
+    # def writelines(self, lines: List[str]) -> None: ...
+    def writelines(self, lines: Any) -> None: ...
+    if sys.version_info >= (3, 4):
+        def __del__(self) -> None: ...
+    if sys.version_info >= (3, 2):
+        closed = ...  # type: bool
+    else:
+        def closed(self) -> bool: ...  # type: ignore
+    # copied from TextIOBase
+    encoding = ...  # type: str
+    errors = ...  # type: Optional[str]
+    newlines = ...  # type: Union[str, Tuple[str, ...], None]
+    def __iter__(self) -> Iterator[str]: ...  # type: ignore
+    def __next__(self) -> str: ...  # type: ignore
+    def __enter__(self) -> 'TextIO': ...
+    def detach(self) -> IOBase: ...
     def write(self, s: str) -> int: ...
-    def writelines(self, lines: Iterable[str]) -> None: ...
+    if sys.version_info >= (3, 4):
+        def readline(self, size: int = ...) -> str: ...  # type: ignore
+        def read(self, size: Optional[int] = ...) -> str: ...
+    elif sys.version_info >= (3, 2):
+        def readline(self, limit: int = ...) -> str: ...  # type: ignore
+    else:
+        def readline(self) -> str: ...  # type: ignore
+    if sys.version_info >= (3, 2):
+        def seek(self, offset: int, whence: int = ...) -> int: ...
+        def tell(self) -> int: ...
+
+class StringIO(TextIOWrapper):
+    def __init__(self, initial_value: str = ...,
+                 newline: Optional[str] = ...) -> None: ...
+    def getvalue(self) -> str: ...
 
-    def __iter__(self) -> Iterator[str]: ...
-    def __enter__(self) -> StringIO: ...
-    def __exit__(self, t: type = None, value: BaseException = None, traceback: Any = None) -> bool: ...
+class IncrementalNewlineDecoder(codecs.IncrementalDecoder): ...
diff --git a/typeshed/stdlib/3/os/__init__.pyi b/typeshed/stdlib/3/os/__init__.pyi
index 4352a12..fdda65f 100644
--- a/typeshed/stdlib/3/os/__init__.pyi
+++ b/typeshed/stdlib/3/os/__init__.pyi
@@ -7,6 +7,7 @@ from typing import (
     Mapping, MutableMapping, Dict, List, Any, Tuple, Iterator, overload, Union, AnyStr,
     Optional, Generic, Set
 )
+import sys
 from builtins import OSError as error
 import os.path as path
 
@@ -254,6 +255,8 @@ def remove(path: AnyStr) -> None: ...
 def removedirs(path: AnyStr) -> None: ...
 def rename(src: AnyStr, dst: AnyStr) -> None: ...
 def renames(old: AnyStr, new: AnyStr) -> None: ...
+if sys.version_info >= (3, 3):
+    def replace(src: AnyStr, dst: AnyStr) -> None: ...
 def rmdir(path: AnyStr) -> None: ...
 def stat(path: AnyStr) -> stat_result: ...
 def stat_float_times(newvalue: Union[bool, None] = ...) -> bool: ...
diff --git a/typeshed/stdlib/3/re.pyi b/typeshed/stdlib/3/re.pyi
index 8cd8bba..8369133 100644
--- a/typeshed/stdlib/3/re.pyi
+++ b/typeshed/stdlib/3/re.pyi
@@ -6,7 +6,7 @@
 # and http://hg.python.org/cpython/file/618ea5612e83/Lib/re.py
 
 from typing import (
-    List, Iterator, Callable, Tuple, Sequence, Dict, Union,
+    List, Iterator, overload, Callable, Tuple, Sequence, Dict,
     Generic, AnyStr, Match, Pattern
 )
 
@@ -29,29 +29,71 @@ UNICODE = 0
 
 class error(Exception): ...
 
+ at overload
 def compile(pattern: AnyStr, flags: int = ...) -> Pattern[AnyStr]: ...
-def search(pattern: AnyStr, string: AnyStr,
-           flags: int = ...) -> Match[AnyStr]: ...
-def match(pattern: AnyStr, string: AnyStr,
-          flags: int = ...) -> Match[AnyStr]: ...
-def split(pattern: AnyStr, string: AnyStr, maxsplit: int = ...,
-          flags: int = ...) -> List[AnyStr]: ...
-def findall(pattern: AnyStr, string: AnyStr,
-            flags: int = ...) -> List[AnyStr]: ...
+ at overload
+def compile(pattern: Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ...
+
+ at overload
+def search(pattern: AnyStr, string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+ at overload
+def search(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+
+ at overload
+def match(pattern: AnyStr, string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+ at overload
+def match(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+
+ at overload
+def split(pattern: AnyStr, string: AnyStr,
+          maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ...
+ at overload
+def split(pattern: Pattern[AnyStr], string: AnyStr,
+          maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ...
+
+ at overload
+def findall(pattern: AnyStr, string: AnyStr, flags: int = ...) -> List[AnyStr]: ...
+ at overload
+def findall(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> List[AnyStr]: ...
 
 # Return an iterator yielding match objects over all non-overlapping matches
 # for the RE pattern in string. The string is scanned left-to-right, and
 # matches are returned in the order found. Empty matches are included in the
 # result unless they touch the beginning of another match.
+ at overload
 def finditer(pattern: AnyStr, string: AnyStr,
              flags: int = ...) -> Iterator[Match[AnyStr]]: ...
+ at overload
+def finditer(pattern: Pattern[AnyStr], string: AnyStr,
+             flags: int = ...) -> Iterator[Match[AnyStr]]: ...
 
-def sub(pattern: AnyStr, repl: Union[AnyStr, Callable[[Match[AnyStr]], AnyStr]],
+ at overload
+def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ...,
+        flags: int = ...) -> AnyStr: ...
+ at overload
+def sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr],
+        string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ...
+ at overload
+def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ...,
+        flags: int = ...) -> AnyStr: ...
+ at overload
+def sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr],
         string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ...
 
-def subn(pattern: AnyStr, repl: Union[AnyStr, Callable[[Match[AnyStr]], AnyStr]],
-         string: AnyStr, count: int = ..., flags: int = ...) -> Tuple[AnyStr, int]:
-    ...
+ at overload
+def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ...,
+         flags: int = ...) -> Tuple[AnyStr, int]: ...
+ at overload
+def subn(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr],
+         string: AnyStr, count: int = ...,
+         flags: int = ...) -> Tuple[AnyStr, int]: ...
+ at overload
+def subn(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ...,
+         flags: int = ...) -> Tuple[AnyStr, int]: ...
+ at overload
+def subn(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr],
+         string: AnyStr, count: int = ...,
+         flags: int = ...) -> Tuple[AnyStr, int]: ...
 
 def escape(string: AnyStr) -> AnyStr: ...
 
diff --git a/typeshed/stdlib/3/socket.pyi b/typeshed/stdlib/3/socket.pyi
index dba7b52..cd2f3d5 100644
--- a/typeshed/stdlib/3/socket.pyi
+++ b/typeshed/stdlib/3/socket.pyi
@@ -294,9 +294,9 @@ class socket:
     def getsockname(self) -> Any: ...
 
     @overload
-    def getsockopt(self, level: int, optname: str) -> int: ...
+    def getsockopt(self, level: int, optname: int) -> int: ...
     @overload
-    def getsockopt(self, level: int, optname: str, buflen: int) -> bytes: ...
+    def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...
 
     def gettimeout(self) -> float: ...
     def ioctl(self, control: object,
@@ -315,13 +315,13 @@ class socket:
                       flags: int = ...) -> Any: ...
     def recv_into(self, buffer: bytes, nbytes: int,
                   flags: int = ...) -> Any: ...
-    def send(self, data: bytes, flags=...) -> int: ...
-    def sendall(self, data: bytes, flags=...) -> Any:
+    def send(self, data: bytes, flags: int = ...) -> int: ...
+    def sendall(self, data: bytes, flags: int =...) -> None:
         ... # return type: None on success
     def sendto(self, data: bytes, address: Union[tuple, str], flags: int = ...) -> int: ...
     def setblocking(self, flag: bool) -> None: ...
     def settimeout(self, value: Union[float, None]) -> None: ...
-    def setsockopt(self, level: int, optname: str, value: Union[int, bytes]) -> None: ...
+    def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ...
     def shutdown(self, how: int) -> None: ...
 
 
diff --git a/typeshed/stdlib/3/socketserver.pyi b/typeshed/stdlib/3/socketserver.pyi
index b92e01f..56c5973 100644
--- a/typeshed/stdlib/3/socketserver.pyi
+++ b/typeshed/stdlib/3/socketserver.pyi
@@ -1,15 +1,77 @@
-# Stubs for socketserver
+# Stubs for socketserver (Python 3.4)
 
-# NOTE: These are incomplete!
+from typing import Optional, Tuple
+from socket import SocketType
+import sys
+import types
 
-from typing import Tuple
+class BaseServer:
+    address_family = ...  # type: int
+    RequestHandlerClass = ...  # type: type
+    server_address = ...  # type: Tuple[str, int]
+    socket = ...  # type: SocketType
+    allow_reuse_address = ...  # type: bool
+    request_queue_size = ...  # type: int
+    socket_type = ...  # type: int
+    timeout = ...  # type: Optional[float]
+    def __init__(self, server_address: Tuple[str, int],
+                 RequestHandlerClass: type) -> None: ...
+    def fileno(self) -> int: ...
+    def handle_request(self) -> None: ...
+    def serve_forever(self, poll_interval: float = ...) -> None: ...
+    def shutdown(self) -> None: ...
+    def server_close(self) -> None: ...
+    def finish_request(self) -> None: ...
+    def get_request(self) -> None: ...
+    def handle_error(self, request: bytes,
+                     client_address: Tuple[str, int]) -> None: ...
+    def handle_timeout(self) -> None: ...
+    def process_request(self, request: bytes,
+                        client_address: Tuple[str, int]) -> None: ...
+    def server_activate(self) -> None: ...
+    def server_bind(self) -> None: ...
+    def verify_request(self, request: bytes,
+                       client_address: Tuple[str, int]) -> bool: ...
+    if sys.version_info >= (3, 6):
+        def __enter__(self) -> 'BaseServer': ...
+        def __exit__(self, exc_type: Optional[type],
+                     exc_val: Optional[Exception],
+                     exc_tb: Optional[types.TracebackType]) -> bool: ...
+    if sys.version_info >= (3, 3):
+        def service_actions(self) -> None: ...
 
-class BaseRequestHandler(): ...
+class TCPServer(BaseServer):
+    def __init__(self, server_address: Tuple[str, int],
+                 RequestHandlerClass: type,
+                 bind_and_activate: bool = ...) -> None: ...
 
-class TCPServer():
-    def __init__(
-        self,
-        server_address: Tuple[str, int],
-        request_handler: BaseRequestHandler,
-        bind_and_activate: bool = ...,
-    ) -> None: ...
+class UDPServer(BaseServer):
+    def __init__(self, server_address: Tuple[str, int],
+                 RequestHandlerClass: type,
+                 bind_and_activate: bool = ...) -> None: ...
+
+class UnixStreamServer(BaseServer):
+    def __init__(self, server_address: Tuple[str, int],
+                 RequestHandlerClass: type,
+                 bind_and_activate: bool = ...) -> None: ...
+
+class UnixDatagramServer(BaseServer):
+    def __init__(self, server_address: Tuple[str, int],
+                 RequestHandlerClass: type,
+                 bind_and_activate: bool = ...) -> None: ...
+
+class ForkingMixIn: ...
+class ThreadingMixIn: ...
+
+class ForkingTCPServer(ForkingMixIn, TCPServer): ...
+class ForkingUDPServer(ForkingMixIn, UDPServer): ...
+class ThreadingTCPServer(ThreadingMixIn, TCPServer): ...
+class ThreadingUDPServer(ThreadingMixIn, UDPServer): ...
+
+class BaseRequestHandler:
+    def setup(self) -> None: ...
+    def handle(self) -> None: ...
+    def finish(self) -> None: ...
+
+class StreamRequestHandler(BaseRequestHandler): ...
+class DatagramRequestHandler(BaseRequestHandler): ...
diff --git a/typeshed/stdlib/3/ssl.pyi b/typeshed/stdlib/3/ssl.pyi
index 7d6beda..cee0978 100644
--- a/typeshed/stdlib/3/ssl.pyi
+++ b/typeshed/stdlib/3/ssl.pyi
@@ -1,202 +1,252 @@
 # Stubs for ssl (Python 3.4)
 
-from typing import Any
-from enum import Enum as _Enum
-from socket import socket
-from collections import namedtuple
-
-class SSLError(OSError): ...
-class SSLEOFError(SSLError): ...
-class SSLSyscallError(SSLError): ...
+from typing import (
+    Any, Dict, Callable, List, NamedTuple, Optional, Set, Tuple, Union,
+)
+import socket
+import sys
+
+_PCTRTT = Tuple[Tuple[str, str], ...]
+_PCTRTTT = Tuple[_PCTRTT, ...]
+_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]]
+_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None]
+_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]]
+_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes]
+
+
+if sys.version_info >= (3, 5):
+    _SC1ArgT = Union['SSLSocket', 'SSLObject']
+else:
+    _SC1ArgT = 'SSLSocket'
+_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], 'SSLSocket'], Optional[int]]
+
+class SSLError(OSError):
+    library = ...  # type: str
+    reason = ...  # type: str
+class SSLZeroReturnError(SSLError): ...
 class SSLWantReadError(SSLError): ...
 class SSLWantWriteError(SSLError): ...
-class SSLZeroReturnError(SSLError): ...
+class SSLSyscallError(SSLError): ...
+class SSLEOFError(SSLError): ...
+class CertificateError(Exception): ...
 
-OPENSSL_VERSION = ... # type: str
-OPENSSL_VERSION_INFO = ... # type: Any
-OPENSSL_VERSION_NUMBER = ... # type: int
 
-VERIFY_CRL_CHECK_CHAIN = ... # type: int
-VERIFY_CRL_CHECK_LEAF = ... # type: int
-VERIFY_DEFAULT = ... # type: int
-VERIFY_X509_STRICT = ... # type: int
-
-ALERT_DESCRIPTION_ACCESS_DENIED = ... # type: int
-ALERT_DESCRIPTION_BAD_CERTIFICATE = ... # type: int
-ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = ... # type: int
-ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = ... # type: int
-ALERT_DESCRIPTION_BAD_RECORD_MAC = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_REVOKED = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = ... # type: int
-ALERT_DESCRIPTION_CLOSE_NOTIFY = ... # type: int
-ALERT_DESCRIPTION_DECODE_ERROR = ... # type: int
-ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = ... # type: int
-ALERT_DESCRIPTION_DECRYPT_ERROR = ... # type: int
-ALERT_DESCRIPTION_HANDSHAKE_FAILURE = ... # type: int
-ALERT_DESCRIPTION_ILLEGAL_PARAMETER = ... # type: int
-ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = ... # type: int
-ALERT_DESCRIPTION_INTERNAL_ERROR = ... # type: int
-ALERT_DESCRIPTION_NO_RENEGOTIATION = ... # type: int
-ALERT_DESCRIPTION_PROTOCOL_VERSION = ... # type: int
-ALERT_DESCRIPTION_RECORD_OVERFLOW = ... # type: int
-ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = ... # type: int
-ALERT_DESCRIPTION_UNKNOWN_CA = ... # type: int
-ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = ... # type: int
-ALERT_DESCRIPTION_UNRECOGNIZED_NAME = ... # type: int
-ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = ... # type: int
-ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = ... # type: int
-ALERT_DESCRIPTION_USER_CANCELLED = ... # type: int
+def wrap_socket(sock: socket.socket, keyfile: Optional[str] = ...,
+                certfile: Optional[str] = ..., server_side: bool = ...,
+                cert_reqs: int = ..., ssl_version: int = ...,
+                ca_certs: Optional[str] = ...,
+                do_handshake_on_connect: bool = ...,
+                suppress_ragged_eofs: bool = ...,
+                ciphers: Optional[str] = ...) -> 'SSLSocket': ...
+
+
+if sys.version_info >= (3, 4):
+    def create_default_context(purpose: Any = ..., *,
+                               cafile: Optional[str] = ...,
+                               capath: Optional[str] = ...,
+                               cadata: Optional[str] = ...) -> 'SSLContext': ...
 
-OP_ALL = ... # type: int
-OP_CIPHER_SERVER_PREFERENCE = ... # type: int
-OP_NO_COMPRESSION = ... # type: int
-OP_NO_SSLv2 = ... # type: int
-OP_NO_SSLv3 = ... # type: int
-OP_NO_TLSv1 = ... # type: int
-OP_NO_TLSv1_1 = ... # type: int
-OP_NO_TLSv1_2 = ... # type: int
-OP_SINGLE_DH_USE = ... # type: int
-OP_SINGLE_ECDH_USE = ... # type: int
 
-SSL_ERROR_EOF = ... # type: int
-SSL_ERROR_INVALID_ERROR_CODE = ... # type: int
-SSL_ERROR_SSL = ... # type: int
-SSL_ERROR_SYSCALL = ... # type: int
-SSL_ERROR_WANT_CONNECT = ... # type: int
-SSL_ERROR_WANT_READ = ... # type: int
-SSL_ERROR_WANT_WRITE = ... # type: int
-SSL_ERROR_WANT_X509_LOOKUP = ... # type: int
-SSL_ERROR_ZERO_RETURN = ... # type: int
+def RAND_bytes(num: int) -> bytes: ...
+def RAND_pseudo_bytes(num: int) -> Tuple[bytes, bool]: ...
+def RAND_status() -> bool: ...
+def RAND_egd(path: str) -> None: ...
+def RAND_add(bytes: bytes, entropy: float) -> None: ...
+
+
+def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ...
+def cert_time_to_seconds(cert_time: str) -> int: ...
+def get_server_certificate(addr: Tuple[str, int], ssl_version: int = ...,
+                           ca_certs: Optional[str] = ...) -> str: ...
+def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ...
+def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ...
+if sys.version_info >= (3, 4):
+    DefaultVerifyPaths = NamedTuple('DefaultVerifyPaths',
+                                    [('cafile', str), ('capath', str),
+                                     ('openssl_cafile_env', str),
+                                     ('openssl_cafile', str),
+                                     ('openssl_capath_env', str),
+                                     ('openssl_capath', str)])
+    def get_default_verify_paths() -> DefaultVerifyPaths: ...
+
+if sys.version_info >= (3, 4) and sys.platform == 'win32':
+    def enum_certificates(store_name: str) -> _EnumRetType: ...
+    def enum_crls(store_name: str) -> _EnumRetType: ...
+
 
 CERT_NONE = ... # type: int
 CERT_OPTIONAL = ... # type: int
 CERT_REQUIRED = ... # type: int
 
+if sys.version_info >= (3, 4):
+    VERIFY_DEFAULT = ... # type: int
+    VERIFY_CRL_CHECK_LEAF = ... # type: int
+    VERIFY_CRL_CHECK_CHAIN = ... # type: int
+    VERIFY_X509_STRICT = ... # type: int
+if sys.version_info >= (3, 4, 4):
+    VERIFY_X509_TRUSTED_FIRST = ... # type: int
+
 PROTOCOL_SSLv23 = ... # type: int
+PROTOCOL_SSLv2 = ... # type: int
 PROTOCOL_SSLv3 = ... # type: int
 PROTOCOL_TLSv1 = ... # type: int
-PROTOCOL_TLSv1_1 = ... # type: int
-PROTOCOL_TLSv1_2 = ... # type: int
+if sys.version_info >= (3, 4):
+    PROTOCOL_TLSv1_1 = ... # type: int
+    PROTOCOL_TLSv1_2 = ... # type: int
 
+OP_ALL = ... # type: int
+OP_NO_SSLv2 = ... # type: int
+OP_NO_SSLv3 = ... # type: int
+OP_NO_TLSv1 = ... # type: int
+if sys.version_info >= (3, 4):
+    OP_NO_TLSv1_1 = ... # type: int
+    OP_NO_TLSv1_2 = ... # type: int
+OP_CIPHER_SERVER_PREFERENCE = ... # type: int
+OP_SINGLE_DH_USE = ... # type: int
+OP_SINGLE_ECDH_USE = ... # type: int
+OP_NO_COMPRESSION = ... # type: int
+
+if sys.version_info >= (3, 5):
+    HAS_ALPN = ...  # type: int
 HAS_ECDH = ... # type: bool
-HAS_NPN = ... # type: bool
 HAS_SNI = ... # type: bool
+HAS_NPN = ... # type: bool
+CHANNEL_BINDING_TYPES = ... # type: List[str]
+
+OPENSSL_VERSION = ... # type: str
+OPENSSL_VERSION_INFO = ... # type: Tuple[int, int, int, int, int]
+OPENSSL_VERSION_NUMBER = ... # type: int
 
-def RAND_add(string, entropy): ...
-def RAND_bytes(n): ...
-def RAND_egd(path): ...
-def RAND_pseudo_bytes(n): ...
-def RAND_status(): ...
-
-socket_error = OSError
-
-CHANNEL_BINDING_TYPES = ... # type: Any
-
-class CertificateError(ValueError): ...
-
-def match_hostname(cert, hostname): ...
-
-DefaultVerifyPaths = namedtuple(
-    'DefaultVerifyPaths',
-    'cafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capath')
-
-def get_default_verify_paths(): ...
-
-class _ASN1Object:
-    def __new__(cls, oid): ...
-    @classmethod
-    def fromnid(cls, nid): ...
-    @classmethod
-    def fromname(cls, name): ...
-
-class Purpose(_ASN1Object, _Enum):
-    SERVER_AUTH = ... # type: Any
-    CLIENT_AUTH = ... # type: Any
-
-class _SSLContext:
-    check_hostname = ... # type: Any
-    options = ... # type: Any
-    verify_flags = ... # type: Any
-    verify_mode = ... # type: Any
-    def __init__(self, *args, **kwargs) -> None: ...
-    def _set_npn_protocols(self, *args, **kwargs): ...
-    def _wrap_socket(self, *args, **kwargs): ...
-    def cert_store_stats(self): ...
-    def get_ca_certs(self, binary_form=...): ...
-    def load_cert_chain(self, *args, **kwargs): ...
-    def load_dh_params(self, *args, **kwargs): ...
-    def load_verify_locations(self, *args, **kwargs): ...
-    def session_stats(self, *args, **kwargs): ...
-    def set_ciphers(self, *args, **kwargs): ...
-    def set_default_verify_paths(self, *args, **kwargs): ...
-    def set_ecdh_curve(self, *args, **kwargs): ...
-    def set_servername_callback(self, method): ...
-
-class SSLContext(_SSLContext):
-    def __new__(cls, protocol, *args, **kwargs): ...
-    protocol = ... # type: Any
-    def __init__(self, protocol) -> None: ...
-    def wrap_socket(self, sock, server_side=..., do_handshake_on_connect=...,
-                    suppress_ragged_eofs=..., server_hostname=...): ...
-    def set_npn_protocols(self, npn_protocols): ...
-    def load_default_certs(self, purpose=...): ...
-
-def create_default_context(purpose=..., *, cafile=..., capath=..., cadata=...): ...
-
-class SSLSocket(socket):
-    keyfile = ... # type: Any
-    certfile = ... # type: Any
-    cert_reqs = ... # type: Any
-    ssl_version = ... # type: Any
-    ca_certs = ... # type: Any
-    ciphers = ... # type: Any
-    server_side = ... # type: Any
-    server_hostname = ... # type: Any
-    do_handshake_on_connect = ... # type: Any
-    suppress_ragged_eofs = ... # type: Any
-    context = ... # type: Any  # TODO: This should be a property.
-    def __init__(self, sock=..., keyfile=..., certfile=..., server_side=...,
-                 cert_reqs=..., ssl_version=..., ca_certs=...,
-                 do_handshake_on_connect=..., family=..., type=..., proto=...,
-                 fileno=..., suppress_ragged_eofs=..., npn_protocols=..., ciphers=...,
-                 server_hostname=..., _context=...): ...
-    def dup(self): ...
-    def read(self, len=..., buffer=...): ...
-    def write(self, data): ...
-    def getpeercert(self, binary_form=...): ...
-    def selected_npn_protocol(self): ...
-    def cipher(self): ...
-    def compression(self): ...
-    def send(self, data, flags=...): ...
-    def sendto(self, data, flags_or_addr, addr=...): ...
-    def sendmsg(self, *args, **kwargs): ...
-    def sendall(self, data, flags=...): ...
-    def recv(self, buflen=..., flags=...): ...
-    def recv_into(self, buffer, nbytes=..., flags=...): ...
-    def recvfrom(self, buflen=..., flags=...): ...
-    def recvfrom_into(self, buffer, nbytes=..., flags=...): ...
-    def recvmsg(self, *args, **kwargs): ...
-    def recvmsg_into(self, *args, **kwargs): ...
-    def pending(self): ...
-    def shutdown(self, how): ...
-    def unwrap(self): ...
-    def do_handshake(self, block=...): ...
-    def connect(self, addr): ...
-    def connect_ex(self, addr): ...
-    def accept(self): ...
-    def get_channel_binding(self, cb_type=...): ...
-
-def wrap_socket(sock, keyfile=..., certfile=..., server_side=..., cert_reqs=...,
-                ssl_version=..., ca_certs=..., do_handshake_on_connect=...,
-                suppress_ragged_eofs=..., ciphers=...): ...
-def cert_time_to_seconds(cert_time): ...
-
-PEM_HEADER = ... # type: Any
-PEM_FOOTER = ... # type: Any
-
-def DER_cert_to_PEM_cert(der_cert_bytes): ...
-def PEM_cert_to_DER_cert(pem_cert_string): ...
-def get_server_certificate(addr, ssl_version=..., ca_certs=...): ...
-def get_protocol_name(protocol_code): ...
+if sys.version_info >= (3, 4):
+    ALERT_DESCRIPTION_HANDSHAKE_FAILURE = ... # type: int
+    ALERT_DESCRIPTION_INTERNAL_ERROR = ... # type: int
+    ALERT_DESCRIPTION_ACCESS_DENIED = ...  # type: int
+    ALERT_DESCRIPTION_BAD_CERTIFICATE = ...  # type: int
+    ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = ...  # type: int
+    ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = ...  # type: int
+    ALERT_DESCRIPTION_BAD_RECORD_MAC = ...  # type: int
+    ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = ...  # type: int
+    ALERT_DESCRIPTION_CERTIFICATE_REVOKED = ...  # type: int
+    ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = ...  # type: int
+    ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = ...  # type: int
+    ALERT_DESCRIPTION_CLOSE_NOTIFY = ...  # type: int
+    ALERT_DESCRIPTION_DECODE_ERROR = ...  # type: int
+    ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = ...  # type: int
+    ALERT_DESCRIPTION_DECRYPT_ERROR = ...  # type: int
+    ALERT_DESCRIPTION_ILLEGAL_PARAMETER = ...  # type: int
+    ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = ...  # type: int
+    ALERT_DESCRIPTION_NO_RENEGOTIATION = ...  # type: int
+    ALERT_DESCRIPTION_PROTOCOL_VERSION = ...  # type: int
+    ALERT_DESCRIPTION_RECORD_OVERFLOW = ...  # type: int
+    ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = ...  # type: int
+    ALERT_DESCRIPTION_UNKNOWN_CA = ...  # type: int
+    ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = ...  # type: int
+    ALERT_DESCRIPTION_UNRECOGNIZED_NAME = ...  # type: int
+    ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = ...  # type: int
+    ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = ...  # type: int
+    ALERT_DESCRIPTION_USER_CANCELLED = ...  # type: int
+
+if sys.version_info >= (3, 4):
+    _PurposeType = NamedTuple('_PurposeType',
+                             [('nid', int), ('shortname', str),
+                              ('longname', str), ('oid', str)])
+    class Purpose:
+        SERVER_AUTH = ... # type: _PurposeType
+        CLIENT_AUTH = ... # type: _PurposeType
+
+
+class SSLSocket(socket.socket):
+    context = ... # type: SSLContext
+    server_side = ... # type: bool
+    server_hostname = ... # type: Optional[str]
+    def read(self, len: int = ...,
+             buffer: Optional[bytearray] = ...) -> bytes: ...
+    def write(self, buf: bytes) -> int: ...
+    def do_handshake(self) -> None: ...
+    def getpeercert(self, binary_form: bool = ...) -> _PeerCertRetType: ...
+    def cipher(self) -> Tuple[str, int, int]: ...
+    if sys.version_info >= (3, 5):
+        def shared_cipher(self) -> Optional[List[Tuple[str, int, int]]]: ...
+    def compression(self) -> Optional[str]: ...
+    def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ...
+    if sys.version_info >= (3, 5):
+        def selected_alpn_protocol(self) -> Optional[str]: ...
+    def selected_npn_protocol(self) -> Optional[str]: ...
+    def unwrap(self) -> socket.socket: ...
+    if sys.version_info >= (3, 5):
+        def version(self) -> Optional[str]: ...
+    def pending(self) -> int: ...
+
+
+class SSLContext:
+    if sys.version_info >= (3, 4):
+        check_hostname = ... # type: bool
+    options = ... # type: int
+    @property
+    def protocol(self) -> int: ...
+    if sys.version_info >= (3, 4):
+        verify_flags = ... # type: int
+    verify_mode = ... # type: int
+    def __init__(self, protocol: int) -> None: ...
+    if sys.version_info >= (3, 4):
+        def cert_store_stats(self) -> Dict[str, int]: ...
+    def load_cert_chain(self, certfile: str, keyfile: Optional[str] = ...,
+                        password: _PasswordType = ...) -> None: ...
+    if sys.version_info >= (3, 4):
+        def load_default_certs(self, purpose: _PurposeType = ...) -> None: ...
+        def load_verify_locations(self, cafile: Optional[str] = ...,
+                                  capath: Optional[str] = ...,
+                                  cadata: Union[str, bytes, None] = ...) \
+                                  -> None: ...
+        def get_ca_certs(self,
+                         binary_form: bool = ...) \
+                         -> Union[List[_PeerCertRetDictType], List[bytes]]: ...
+    else:
+        def load_verify_locations(self,  # type: ignore
+                                  cafile: Optional[str] = ...,
+                                  capath: Optional[str] = ...) -> None: ...
+    def set_default_verify_paths(self) -> None: ...
+    def set_ciphers(self, ciphers: str) -> None: ...
+    if sys.version_info >= (3, 5):
+        def set_alpn_protocols(protocols: List[str]) -> None: ...
+    def set_npn_protocols(protocols: List[str]) -> None: ...
+    def set_servername_callback(self,
+                                server_name_callback: Optional[_SrvnmeCbType]) \
+                                -> None: ...
+    def load_dh_params(self, dhfile: str) -> None: ...
+    def set_ecdh_curve(self, curve_name: str) -> None: ...
+    def wrap_socket(self, sock: socket.socket, server_side: bool = ...,
+                    do_handshake_on_connect: bool = ...,
+                    suppress_ragged_eofs: bool = ...,
+                    server_hostname: Optional[str] = ...) -> 'SSLContext': ...
+    if sys.version_info >= (3, 5):
+        def wrap_bio(incoming: 'MemoryBIO', outgoing: 'MemoryBIO',
+                     server_side: bool = ...,
+                     server_hostname: Optional[str] = ...) -> 'SSLObject': ...
+    def session_stats(self) -> Dict[str, int]: ...
+
+
+if sys.version_info >= (3, 5):
+    class SSLObject:
+        context = ... # type: SSLContext
+        server_side = ... # type: bool
+        server_hostname = ... # type: Optional[str]
+        def read(self, len: int = ...,
+                 buffer: Optional[bytearray] = ...) -> bytes: ...
+        def write(self, buf: bytes) -> int: ...
+        def getpeercert(self, binary_form: bool = ...) -> _PeerCertRetType: ...
+        def selected_npn_protocol(self) -> Optional[str]: ...
+        def cipher(self) -> Tuple[str, int, int]: ...
+        def shared_cipher(self) -> Optional[List[Tuple[str, int, int]]]: ...
+        def compression(self) -> Optional[str]: ...
+        def pending(self) -> int: ...
+        def do_handshake(self) -> None: ...
+        def unwrap(self) -> None: ...
+        def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ...
+
+    class MemoryBIO:
+        pending = ...  # type: int
+        eof = ...  # type: bool
+        def read(self, n: int = ...) -> bytes: ...
+        def write(self, buf: bytes) -> int: ...
+        def write_eof(self) -> None: ...
diff --git a/typeshed/stdlib/3/subprocess.pyi b/typeshed/stdlib/3/subprocess.pyi
index c606c33..83d62cf 100644
--- a/typeshed/stdlib/3/subprocess.pyi
+++ b/typeshed/stdlib/3/subprocess.pyi
@@ -2,20 +2,20 @@
 
 # Based on http://docs.python.org/3.2/library/subprocess.html
 
-from typing import Sequence, Any, Mapping, Callable, Tuple, IO
+from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Optional, Union
 
 # TODO force keyword arguments
 # TODO more keyword arguments
-def call(args: Sequence[str], *, stdin: Any = ..., stdout: Any = ...,
+def call(args: Union[str, Sequence[str]], *, stdin: Any = ..., stdout: Any = ...,
          stderr: Any = ..., shell: bool = ...,
          env: Mapping[str, str] = ...,
          cwd: str = ...) -> int: ...
-def check_call(args: Sequence[str], *, stdin: Any = ..., stdout: Any = ...,
+def check_call(args: Union[str, Sequence[str]], *, stdin: Any = ..., stdout: Any = ...,
                stderr: Any = ..., shell: bool = ...,
                env: Mapping[str, str] = ...,
                cwd: str = ...) -> int: ...
 # Return str/bytes
-def check_output(args: Sequence[str], *, stdin: Any = ..., stderr: Any = ...,
+def check_output(args: Union[str, Sequence[str]], *, stdin: Any = ..., stderr: Any = ...,
                  shell: bool = ..., universal_newlines: bool = ...,
                  env: Mapping[str, str] = ...,
                  cwd: str = ...) -> Any: ...
@@ -29,7 +29,8 @@ class CalledProcessError(Exception):
     cmd = ...  # type: str
     output = b'' # May be None
 
-    def __init__(self, returncode: int, cmd: str, output: str = ...) -> None: ...
+    def __init__(self, returncode: int, cmd: str, output: Optional[str],
+                 stderr: Optional[str] = ...) -> None: ...
 
 class Popen:
     stdin = ... # type: IO[Any]
@@ -39,7 +40,7 @@ class Popen:
     returncode = 0
 
     def __init__(self,
-                  args: Sequence[str],
+                  args: Union[str, Sequence[str]],
                   bufsize: int = ...,
                   executable: str = ...,
                   stdin: Any = ...,
diff --git a/typeshed/stdlib/3/sys.pyi b/typeshed/stdlib/3/sys.pyi
index e533204..accaadf 100644
--- a/typeshed/stdlib/3/sys.pyi
+++ b/typeshed/stdlib/3/sys.pyi
@@ -4,10 +4,13 @@
 # based on http://docs.python.org/3.2/library/sys.html
 
 from typing import (
-    List, Sequence, Any, Dict, Tuple, TextIO, overload, Optional, Union
+    List, Sequence, Any, Dict, Tuple, TextIO, overload, Optional, Union,
+    TypeVar, Callable
 )
 from types import TracebackType
 
+_T = TypeVar('_T')
+
 # ----- sys variables -----
 abiflags = ...  # type: str
 argv = ... # type: List[str]
@@ -108,7 +111,7 @@ version_info = ... # type: _version_info
 
 
 # ----- sys function stubs -----
-def call_tracing(fn: Any, args: Any) -> object: ...
+def call_tracing(fn: Callable[..., _T], args: Any) -> _T: ...
 def _clear_type_cache() -> None: ...
 def _current_frames() -> Dict[int, Any]: ...
 def displayhook(value: Optional[int]) -> None: ...
@@ -122,7 +125,7 @@ def getcheckinterval() -> int: ...  # deprecated
 def getdefaultencoding() -> str: ...
 def getdlopenflags() -> int: ...  # Unix only
 def getfilesystemencoding() -> str: ...  # cannot return None
-def getrefcount(object) -> int: ...
+def getrefcount(arg: Any) -> int: ...
 def getrecursionlimit() -> int: ...
 
 @overload
diff --git a/typeshed/stdlib/3/tkinter/__init__.pyi b/typeshed/stdlib/3/tkinter/__init__.pyi
new file mode 100644
index 0000000..782932d
--- /dev/null
+++ b/typeshed/stdlib/3/tkinter/__init__.pyi
@@ -0,0 +1,660 @@
+# Stubs for tkinter (Python 3.5)
+#
+# NOTE: This dynamically typed stub was automatically generated by stubgen.
+
+from typing import Any
+from tkinter.constants import *
+
+TclError = ...  # type: Any
+wantobjects = ...  # type: Any
+TkVersion = ...  # type: Any
+TclVersion = ...  # type: Any
+READABLE = ...  # type: Any
+WRITABLE = ...  # type: Any
+EXCEPTION = ...  # type: Any
+
+class Event: ...
+
+def NoDefaultRoot(): ...
+
+class Variable:
+    def __init__(self, master=None, value=None, name=None): ...
+    def __del__(self): ...
+    def set(self, value): ...
+    initialize = ...  # type: Any
+    def get(self): ...
+    def trace_variable(self, mode, callback): ...
+    trace = ...  # type: Any
+    def trace_vdelete(self, mode, cbname): ...
+    def trace_vinfo(self): ...
+    def __eq__(self, other): ...
+
+class StringVar(Variable):
+    def __init__(self, master=None, value=None, name=None): ...
+    def get(self): ...
+
+class IntVar(Variable):
+    def __init__(self, master=None, value=None, name=None): ...
+    def get(self): ...
+
+class DoubleVar(Variable):
+    def __init__(self, master=None, value=None, name=None): ...
+    def get(self): ...
+
+class BooleanVar(Variable):
+    def __init__(self, master=None, value=None, name=None): ...
+    def set(self, value): ...
+    initialize = ...  # type: Any
+    def get(self): ...
+
+def mainloop(n=0): ...
+
+getint = ...  # type: Any
+getdouble = ...  # type: Any
+
+def getboolean(s): ...
+
+class Misc:
+    def destroy(self): ...
+    def deletecommand(self, name): ...
+    def tk_strictMotif(self, boolean=None): ...
+    def tk_bisque(self): ...
+    def tk_setPalette(self, *args, **kw): ...
+    def tk_menuBar(self, *args): ...
+    def wait_variable(self, name=''): ...
+    waitvar = ...  # type: Any
+    def wait_window(self, window=None): ...
+    def wait_visibility(self, window=None): ...
+    def setvar(self, name='', value=''): ...
+    def getvar(self, name=''): ...
+    def getint(self, s): ...
+    def getdouble(self, s): ...
+    def getboolean(self, s): ...
+    def focus_set(self): ...
+    focus = ...  # type: Any
+    def focus_force(self): ...
+    def focus_get(self): ...
+    def focus_displayof(self): ...
+    def focus_lastfor(self): ...
+    def tk_focusFollowsMouse(self): ...
+    def tk_focusNext(self): ...
+    def tk_focusPrev(self): ...
+    def after(self, ms, func=None, *args): ...
+    def after_idle(self, func, *args): ...
+    def after_cancel(self, id): ...
+    def bell(self, displayof=0): ...
+    def clipboard_get(self, **kw): ...
+    def clipboard_clear(self, **kw): ...
+    def clipboard_append(self, string, **kw): ...
+    def grab_current(self): ...
+    def grab_release(self): ...
+    def grab_set(self): ...
+    def grab_set_global(self): ...
+    def grab_status(self): ...
+    def option_add(self, pattern, value, priority=None): ...
+    def option_clear(self): ...
+    def option_get(self, name, className): ...
+    def option_readfile(self, fileName, priority=None): ...
+    def selection_clear(self, **kw): ...
+    def selection_get(self, **kw): ...
+    def selection_handle(self, command, **kw): ...
+    def selection_own(self, **kw): ...
+    def selection_own_get(self, **kw): ...
+    def send(self, interp, cmd, *args): ...
+    def lower(self, belowThis=None): ...
+    def tkraise(self, aboveThis=None): ...
+    lift = ...  # type: Any
+    def winfo_atom(self, name, displayof=0): ...
+    def winfo_atomname(self, id, displayof=0): ...
+    def winfo_cells(self): ...
+    def winfo_children(self): ...
+    def winfo_class(self): ...
+    def winfo_colormapfull(self): ...
+    def winfo_containing(self, rootX, rootY, displayof=0): ...
+    def winfo_depth(self): ...
+    def winfo_exists(self): ...
+    def winfo_fpixels(self, number): ...
+    def winfo_geometry(self): ...
+    def winfo_height(self): ...
+    def winfo_id(self): ...
+    def winfo_interps(self, displayof=0): ...
+    def winfo_ismapped(self): ...
+    def winfo_manager(self): ...
+    def winfo_name(self): ...
+    def winfo_parent(self): ...
+    def winfo_pathname(self, id, displayof=0): ...
+    def winfo_pixels(self, number): ...
+    def winfo_pointerx(self): ...
+    def winfo_pointerxy(self): ...
+    def winfo_pointery(self): ...
+    def winfo_reqheight(self): ...
+    def winfo_reqwidth(self): ...
+    def winfo_rgb(self, color): ...
+    def winfo_rootx(self): ...
+    def winfo_rooty(self): ...
+    def winfo_screen(self): ...
+    def winfo_screencells(self): ...
+    def winfo_screendepth(self): ...
+    def winfo_screenheight(self): ...
+    def winfo_screenmmheight(self): ...
+    def winfo_screenmmwidth(self): ...
+    def winfo_screenvisual(self): ...
+    def winfo_screenwidth(self): ...
+    def winfo_server(self): ...
+    def winfo_toplevel(self): ...
+    def winfo_viewable(self): ...
+    def winfo_visual(self): ...
+    def winfo_visualid(self): ...
+    def winfo_visualsavailable(self, includeids=0): ...
+    def winfo_vrootheight(self): ...
+    def winfo_vrootwidth(self): ...
+    def winfo_vrootx(self): ...
+    def winfo_vrooty(self): ...
+    def winfo_width(self): ...
+    def winfo_x(self): ...
+    def winfo_y(self): ...
+    def update(self): ...
+    def update_idletasks(self): ...
+    def bindtags(self, tagList=None): ...
+    def bind(self, sequence=None, func=None, add=None): ...
+    def unbind(self, sequence, funcid=None): ...
+    def bind_all(self, sequence=None, func=None, add=None): ...
+    def unbind_all(self, sequence): ...
+    def bind_class(self, className, sequence=None, func=None, add=None): ...
+    def unbind_class(self, className, sequence): ...
+    def mainloop(self, n=0): ...
+    def quit(self): ...
+    def nametowidget(self, name): ...
+    register = ...  # type: Any
+    def configure(self, cnf=None, **kw): ...
+    config = ...  # type: Any
+    def cget(self, key): ...
+    __getitem__ = ...  # type: Any
+    def __setitem__(self, key, value): ...
+    def keys(self): ...
+    def pack_propagate(self, flag=...): ...
+    propagate = ...  # type: Any
+    def pack_slaves(self): ...
+    slaves = ...  # type: Any
+    def place_slaves(self): ...
+    def grid_anchor(self, anchor=None): ...
+    anchor = ...  # type: Any
+    def grid_bbox(self, column=None, row=None, col2=None, row2=None): ...
+    bbox = ...  # type: Any
+    def grid_columnconfigure(self, index, cnf=..., **kw): ...
+    columnconfigure = ...  # type: Any
+    def grid_location(self, x, y): ...
+    def grid_propagate(self, flag=...): ...
+    def grid_rowconfigure(self, index, cnf=..., **kw): ...
+    rowconfigure = ...  # type: Any
+    def grid_size(self): ...
+    size = ...  # type: Any
+    def grid_slaves(self, row=None, column=None): ...
+    def event_add(self, virtual, *sequences): ...
+    def event_delete(self, virtual, *sequences): ...
+    def event_generate(self, sequence, **kw): ...
+    def event_info(self, virtual=None): ...
+    def image_names(self): ...
+    def image_types(self): ...
+
+class CallWrapper:
+    func = ...  # type: Any
+    subst = ...  # type: Any
+    widget = ...  # type: Any
+    def __init__(self, func, subst, widget): ...
+    def __call__(self, *args): ...
+
+class XView:
+    def xview(self, *args): ...
+    def xview_moveto(self, fraction): ...
+    def xview_scroll(self, number, what): ...
+
+class YView:
+    def yview(self, *args): ...
+    def yview_moveto(self, fraction): ...
+    def yview_scroll(self, number, what): ...
+
+class Wm:
+    def wm_aspect(self, minNumer=None, minDenom=None, maxNumer=None, maxDenom=None): ...
+    aspect = ...  # type: Any
+    def wm_attributes(self, *args): ...
+    attributes = ...  # type: Any
+    def wm_client(self, name=None): ...
+    client = ...  # type: Any
+    def wm_colormapwindows(self, *wlist): ...
+    colormapwindows = ...  # type: Any
+    def wm_command(self, value=None): ...
+    command = ...  # type: Any
+    def wm_deiconify(self): ...
+    deiconify = ...  # type: Any
+    def wm_focusmodel(self, model=None): ...
+    focusmodel = ...  # type: Any
+    def wm_forget(self, window): ...
+    forget = ...  # type: Any
+    def wm_frame(self): ...
+    frame = ...  # type: Any
+    def wm_geometry(self, newGeometry=None): ...
+    geometry = ...  # type: Any
+    def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): ...
+    grid = ...  # type: Any
+    def wm_group(self, pathName=None): ...
+    group = ...  # type: Any
+    def wm_iconbitmap(self, bitmap=None, default=None): ...
+    iconbitmap = ...  # type: Any
+    def wm_iconify(self): ...
+    iconify = ...  # type: Any
+    def wm_iconmask(self, bitmap=None): ...
+    iconmask = ...  # type: Any
+    def wm_iconname(self, newName=None): ...
+    iconname = ...  # type: Any
+    def wm_iconphoto(self, default=False, *args): ...
+    iconphoto = ...  # type: Any
+    def wm_iconposition(self, x=None, y=None): ...
+    iconposition = ...  # type: Any
+    def wm_iconwindow(self, pathName=None): ...
+    iconwindow = ...  # type: Any
+    def wm_manage(self, widget): ...
+    manage = ...  # type: Any
+    def wm_maxsize(self, width=None, height=None): ...
+    maxsize = ...  # type: Any
+    def wm_minsize(self, width=None, height=None): ...
+    minsize = ...  # type: Any
+    def wm_overrideredirect(self, boolean=None): ...
+    overrideredirect = ...  # type: Any
+    def wm_positionfrom(self, who=None): ...
+    positionfrom = ...  # type: Any
+    def wm_protocol(self, name=None, func=None): ...
+    protocol = ...  # type: Any
+    def wm_resizable(self, width=None, height=None): ...
+    resizable = ...  # type: Any
+    def wm_sizefrom(self, who=None): ...
+    sizefrom = ...  # type: Any
+    def wm_state(self, newstate=None): ...
+    state = ...  # type: Any
+    def wm_title(self, string=None): ...
+    title = ...  # type: Any
+    def wm_transient(self, master=None): ...
+    transient = ...  # type: Any
+    def wm_withdraw(self): ...
+    withdraw = ...  # type: Any
+
+class Tk(Misc, Wm):
+    master = ...  # type: Any
+    children = ...  # type: Any
+    tk = ...  # type: Any
+    def __init__(self, screenName=None, baseName=None, className='', useTk=1, sync=0, use=None): ...
+    def loadtk(self): ...
+    def destroy(self): ...
+    def readprofile(self, baseName, className): ...
+    def report_callback_exception(self, exc, val, tb): ...
+    def __getattr__(self, attr): ...
+
+def Tcl(screenName=None, baseName=None, className='', useTk=0): ...
+
+class Pack:
+    def pack_configure(self, cnf=..., **kw): ...
+    pack = ...  # type: Any
+    def pack_forget(self): ...
+    forget = ...  # type: Any
+    def pack_info(self): ...
+    info = ...  # type: Any
+    propagate = ...  # type: Any
+    slaves = ...  # type: Any
+
+class Place:
+    def place_configure(self, cnf=..., **kw): ...
+    place = ...  # type: Any
+    def place_forget(self): ...
+    forget = ...  # type: Any
+    def place_info(self): ...
+    info = ...  # type: Any
+    slaves = ...  # type: Any
+
+class Grid:
+    def grid_configure(self, cnf=..., **kw): ...
+    grid = ...  # type: Any
+    bbox = ...  # type: Any
+    columnconfigure = ...  # type: Any
+    def grid_forget(self): ...
+    forget = ...  # type: Any
+    def grid_remove(self): ...
+    def grid_info(self): ...
+    info = ...  # type: Any
+    location = ...  # type: Any
+    propagate = ...  # type: Any
+    rowconfigure = ...  # type: Any
+    size = ...  # type: Any
+    slaves = ...  # type: Any
+
+class BaseWidget(Misc):
+    widgetName = ...  # type: Any
+    def __init__(self, master, widgetName, cnf=..., kw=..., extra=...): ...
+    def destroy(self): ...
+
+class Widget(BaseWidget, Pack, Place, Grid): ...
+
+class Toplevel(BaseWidget, Wm):
+    def __init__(self, master=None, cnf=..., **kw): ...
+
+class Button(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def flash(self): ...
+    def invoke(self): ...
+
+class Canvas(Widget, XView, YView):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def addtag(self, *args): ...
+    def addtag_above(self, newtag, tagOrId): ...
+    def addtag_all(self, newtag): ...
+    def addtag_below(self, newtag, tagOrId): ...
+    def addtag_closest(self, newtag, x, y, halo=None, start=None): ...
+    def addtag_enclosed(self, newtag, x1, y1, x2, y2): ...
+    def addtag_overlapping(self, newtag, x1, y1, x2, y2): ...
+    def addtag_withtag(self, newtag, tagOrId): ...
+    def bbox(self, *args): ...
+    def tag_unbind(self, tagOrId, sequence, funcid=None): ...
+    def tag_bind(self, tagOrId, sequence=None, func=None, add=None): ...
+    def canvasx(self, screenx, gridspacing=None): ...
+    def canvasy(self, screeny, gridspacing=None): ...
+    def coords(self, *args): ...
+    def create_arc(self, *args, **kw): ...
+    def create_bitmap(self, *args, **kw): ...
+    def create_image(self, *args, **kw): ...
+    def create_line(self, *args, **kw): ...
+    def create_oval(self, *args, **kw): ...
+    def create_polygon(self, *args, **kw): ...
+    def create_rectangle(self, *args, **kw): ...
+    def create_text(self, *args, **kw): ...
+    def create_window(self, *args, **kw): ...
+    def dchars(self, *args): ...
+    def delete(self, *args): ...
+    def dtag(self, *args): ...
+    def find(self, *args): ...
+    def find_above(self, tagOrId): ...
+    def find_all(self): ...
+    def find_below(self, tagOrId): ...
+    def find_closest(self, x, y, halo=None, start=None): ...
+    def find_enclosed(self, x1, y1, x2, y2): ...
+    def find_overlapping(self, x1, y1, x2, y2): ...
+    def find_withtag(self, tagOrId): ...
+    def focus(self, *args): ...
+    def gettags(self, *args): ...
+    def icursor(self, *args): ...
+    def index(self, *args): ...
+    def insert(self, *args): ...
+    def itemcget(self, tagOrId, option): ...
+    def itemconfigure(self, tagOrId, cnf=None, **kw): ...
+    itemconfig = ...  # type: Any
+    def tag_lower(self, *args): ...
+    lower = ...  # type: Any
+    def move(self, *args): ...
+    def postscript(self, cnf=..., **kw): ...
+    def tag_raise(self, *args): ...
+    lift = ...  # type: Any
+    def scale(self, *args): ...
+    def scan_mark(self, x, y): ...
+    def scan_dragto(self, x, y, gain=10): ...
+    def select_adjust(self, tagOrId, index): ...
+    def select_clear(self): ...
+    def select_from(self, tagOrId, index): ...
+    def select_item(self): ...
+    def select_to(self, tagOrId, index): ...
+    def type(self, tagOrId): ...
+
+class Checkbutton(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def deselect(self): ...
+    def flash(self): ...
+    def invoke(self): ...
+    def select(self): ...
+    def toggle(self): ...
+
+class Entry(Widget, XView):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def delete(self, first, last=None): ...
+    def get(self): ...
+    def icursor(self, index): ...
+    def index(self, index): ...
+    def insert(self, index, string): ...
+    def scan_mark(self, x): ...
+    def scan_dragto(self, x): ...
+    def selection_adjust(self, index): ...
+    select_adjust = ...  # type: Any
+    def selection_clear(self): ...
+    select_clear = ...  # type: Any
+    def selection_from(self, index): ...
+    select_from = ...  # type: Any
+    def selection_present(self): ...
+    select_present = ...  # type: Any
+    def selection_range(self, start, end): ...
+    select_range = ...  # type: Any
+    def selection_to(self, index): ...
+    select_to = ...  # type: Any
+
+class Frame(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+
+class Label(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+
+class Listbox(Widget, XView, YView):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def activate(self, index): ...
+    def bbox(self, index): ...
+    def curselection(self): ...
+    def delete(self, first, last=None): ...
+    def get(self, first, last=None): ...
+    def index(self, index): ...
+    def insert(self, index, *elements): ...
+    def nearest(self, y): ...
+    def scan_mark(self, x, y): ...
+    def scan_dragto(self, x, y): ...
+    def see(self, index): ...
+    def selection_anchor(self, index): ...
+    select_anchor = ...  # type: Any
+    def selection_clear(self, first, last=None): ...
+    select_clear = ...  # type: Any
+    def selection_includes(self, index): ...
+    select_includes = ...  # type: Any
+    def selection_set(self, first, last=None): ...
+    select_set = ...  # type: Any
+    def size(self): ...
+    def itemcget(self, index, option): ...
+    def itemconfigure(self, index, cnf=None, **kw): ...
+    itemconfig = ...  # type: Any
+
+class Menu(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def tk_popup(self, x, y, entry=''): ...
+    def tk_bindForTraversal(self): ...
+    def activate(self, index): ...
+    def add(self, itemType, cnf=..., **kw): ...
+    def add_cascade(self, cnf=..., **kw): ...
+    def add_checkbutton(self, cnf=..., **kw): ...
+    def add_command(self, cnf=..., **kw): ...
+    def add_radiobutton(self, cnf=..., **kw): ...
+    def add_separator(self, cnf=..., **kw): ...
+    def insert(self, index, itemType, cnf=..., **kw): ...
+    def insert_cascade(self, index, cnf=..., **kw): ...
+    def insert_checkbutton(self, index, cnf=..., **kw): ...
+    def insert_command(self, index, cnf=..., **kw): ...
+    def insert_radiobutton(self, index, cnf=..., **kw): ...
+    def insert_separator(self, index, cnf=..., **kw): ...
+    def delete(self, index1, index2=None): ...
+    def entrycget(self, index, option): ...
+    def entryconfigure(self, index, cnf=None, **kw): ...
+    entryconfig = ...  # type: Any
+    def index(self, index): ...
+    def invoke(self, index): ...
+    def post(self, x, y): ...
+    def type(self, index): ...
+    def unpost(self): ...
+    def xposition(self, index): ...
+    def yposition(self, index): ...
+
+class Menubutton(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+
+class Message(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+
+class Radiobutton(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def deselect(self): ...
+    def flash(self): ...
+    def invoke(self): ...
+    def select(self): ...
+
+class Scale(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def get(self): ...
+    def set(self, value): ...
+    def coords(self, value=None): ...
+    def identify(self, x, y): ...
+
+class Scrollbar(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def activate(self, index=None): ...
+    def delta(self, deltax, deltay): ...
+    def fraction(self, x, y): ...
+    def identify(self, x, y): ...
+    def get(self): ...
+    def set(self, first, last): ...
+
+class Text(Widget, XView, YView):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def bbox(self, index): ...
+    def compare(self, index1, op, index2): ...
+    def count(self, index1, index2, *args): ...
+    def debug(self, boolean=None): ...
+    def delete(self, index1, index2=None): ...
+    def dlineinfo(self, index): ...
+    def dump(self, index1, index2=None, command=None, **kw): ...
+    def edit(self, *args): ...
+    def edit_modified(self, arg=None): ...
+    def edit_redo(self): ...
+    def edit_reset(self): ...
+    def edit_separator(self): ...
+    def edit_undo(self): ...
+    def get(self, index1, index2=None): ...
+    def image_cget(self, index, option): ...
+    def image_configure(self, index, cnf=None, **kw): ...
+    def image_create(self, index, cnf=..., **kw): ...
+    def image_names(self): ...
+    def index(self, index): ...
+    def insert(self, index, chars, *args): ...
+    def mark_gravity(self, markName, direction=None): ...
+    def mark_names(self): ...
+    def mark_set(self, markName, index): ...
+    def mark_unset(self, *markNames): ...
+    def mark_next(self, index): ...
+    def mark_previous(self, index): ...
+    def peer_create(self, newPathName, cnf=..., **kw): ...
+    def peer_names(self): ...
+    def replace(self, index1, index2, chars, *args): ...
+    def scan_mark(self, x, y): ...
+    def scan_dragto(self, x, y): ...
+    def search(self, pattern, index, stopindex=None, forwards=None, backwards=None, exact=None, regexp=None, nocase=None, count=None, elide=None): ...
+    def see(self, index): ...
+    def tag_add(self, tagName, index1, *args): ...
+    def tag_unbind(self, tagName, sequence, funcid=None): ...
+    def tag_bind(self, tagName, sequence, func, add=None): ...
+    def tag_cget(self, tagName, option): ...
+    def tag_configure(self, tagName, cnf=None, **kw): ...
+    tag_config = ...  # type: Any
+    def tag_delete(self, *tagNames): ...
+    def tag_lower(self, tagName, belowThis=None): ...
+    def tag_names(self, index=None): ...
+    def tag_nextrange(self, tagName, index1, index2=None): ...
+    def tag_prevrange(self, tagName, index1, index2=None): ...
+    def tag_raise(self, tagName, aboveThis=None): ...
+    def tag_ranges(self, tagName): ...
+    def tag_remove(self, tagName, index1, index2=None): ...
+    def window_cget(self, index, option): ...
+    def window_configure(self, index, cnf=None, **kw): ...
+    window_config = ...  # type: Any
+    def window_create(self, index, cnf=..., **kw): ...
+    def window_names(self): ...
+    def yview_pickplace(self, *what): ...
+
+class _setit:
+    def __init__(self, var, value, callback=None): ...
+    def __call__(self, *args): ...
+
+class OptionMenu(Menubutton):
+    widgetName = ...  # type: Any
+    menuname = ...  # type: Any
+    def __init__(self, master, variable, value, *values, **kwargs): ...
+    def __getitem__(self, name): ...
+    def destroy(self): ...
+
+class Image:
+    name = ...  # type: Any
+    tk = ...  # type: Any
+    def __init__(self, imgtype, name=None, cnf=..., master=None, **kw): ...
+    def __del__(self): ...
+    def __setitem__(self, key, value): ...
+    def __getitem__(self, key): ...
+    def configure(self, **kw): ...
+    config = ...  # type: Any
+    def height(self): ...
+    def type(self): ...
+    def width(self): ...
+
+class PhotoImage(Image):
+    def __init__(self, name=None, cnf=..., master=None, **kw): ...
+    def blank(self): ...
+    def cget(self, option): ...
+    def __getitem__(self, key): ...
+    def copy(self): ...
+    def zoom(self, x, y=''): ...
+    def subsample(self, x, y=''): ...
+    def get(self, x, y): ...
+    def put(self, data, to=None): ...
+    def write(self, filename, format=None, from_coords=None): ...
+
+class BitmapImage(Image):
+    def __init__(self, name=None, cnf=..., master=None, **kw): ...
+
+def image_names(): ...
+def image_types(): ...
+
+class Spinbox(Widget, XView):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def bbox(self, index): ...
+    def delete(self, first, last=None): ...
+    def get(self): ...
+    def icursor(self, index): ...
+    def identify(self, x, y): ...
+    def index(self, index): ...
+    def insert(self, index, s): ...
+    def invoke(self, element): ...
+    def scan(self, *args): ...
+    def scan_mark(self, x): ...
+    def scan_dragto(self, x): ...
+    def selection(self, *args): ...
+    def selection_adjust(self, index): ...
+    def selection_clear(self): ...
+    def selection_element(self, element=None): ...
+
+class LabelFrame(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+
+class PanedWindow(Widget):
+    def __init__(self, master=None, cnf=..., **kw): ...
+    def add(self, child, **kw): ...
+    def remove(self, child): ...
+    forget = ...  # type: Any
+    def identify(self, x, y): ...
+    def proxy(self, *args): ...
+    def proxy_coord(self): ...
+    def proxy_forget(self): ...
+    def proxy_place(self, x, y): ...
+    def sash(self, *args): ...
+    def sash_coord(self, index): ...
+    def sash_mark(self, index): ...
+    def sash_place(self, index, x, y): ...
+    def panecget(self, child, option): ...
+    def paneconfigure(self, tagOrId, cnf=None, **kw): ...
+    paneconfig = ...  # type: Any
+    def panes(self): ...
diff --git a/typeshed/stdlib/3/tkinter/constants.pyi b/typeshed/stdlib/3/tkinter/constants.pyi
new file mode 100644
index 0000000..6a6deae
--- /dev/null
+++ b/typeshed/stdlib/3/tkinter/constants.pyi
@@ -0,0 +1,83 @@
+# Stubs for tkinter.constants (Python 3.5)
+#
+# NOTE: This dynamically typed stub was automatically generated by stubgen.
+
+from typing import Any
+
+NO = ...  # type: Any
+YES = ...  # type: Any
+TRUE = ... # type: Any
+FALSE = ... # type: Any
+ON = ... # type: Any
+OFF = ... # type: Any
+N = ...  # type: Any
+S = ...  # type: Any
+W = ...  # type: Any
+E = ...  # type: Any
+NW = ...  # type: Any
+SW = ...  # type: Any
+NE = ...  # type: Any
+SE = ...  # type: Any
+NS = ...  # type: Any
+EW = ...  # type: Any
+NSEW = ...  # type: Any
+CENTER = ...  # type: Any
+NONE = ...  # type: Any
+X = ...  # type: Any
+Y = ...  # type: Any
+BOTH = ...  # type: Any
+LEFT = ...  # type: Any
+TOP = ...  # type: Any
+RIGHT = ...  # type: Any
+BOTTOM = ...  # type: Any
+RAISED = ...  # type: Any
+SUNKEN = ...  # type: Any
+FLAT = ...  # type: Any
+RIDGE = ...  # type: Any
+GROOVE = ...  # type: Any
+SOLID = ...  # type: Any
+HORIZONTAL = ...  # type: Any
+VERTICAL = ...  # type: Any
+NUMERIC = ...  # type: Any
+CHAR = ...  # type: Any
+WORD = ...  # type: Any
+BASELINE = ...  # type: Any
+INSIDE = ...  # type: Any
+OUTSIDE = ...  # type: Any
+SEL = ...  # type: Any
+SEL_FIRST = ...  # type: Any
+SEL_LAST = ...  # type: Any
+END = ...  # type: Any
+INSERT = ...  # type: Any
+CURRENT = ...  # type: Any
+ANCHOR = ...  # type: Any
+ALL = ...  # type: Any
+NORMAL = ...  # type: Any
+DISABLED = ...  # type: Any
+ACTIVE = ...  # type: Any
+HIDDEN = ...  # type: Any
+CASCADE = ...  # type: Any
+CHECKBUTTON = ...  # type: Any
+COMMAND = ...  # type: Any
+RADIOBUTTON = ...  # type: Any
+SEPARATOR = ...  # type: Any
+SINGLE = ...  # type: Any
+BROWSE = ...  # type: Any
+MULTIPLE = ...  # type: Any
+EXTENDED = ...  # type: Any
+DOTBOX = ...  # type: Any
+UNDERLINE = ...  # type: Any
+PIESLICE = ...  # type: Any
+CHORD = ...  # type: Any
+ARC = ...  # type: Any
+FIRST = ...  # type: Any
+LAST = ...  # type: Any
+BUTT = ...  # type: Any
+PROJECTING = ...  # type: Any
+ROUND = ...  # type: Any
+BEVEL = ...  # type: Any
+MITER = ...  # type: Any
+MOVETO = ...  # type: Any
+SCROLL = ...  # type: Any
+UNITS = ...  # type: Any
+PAGES = ...  # type: Any
diff --git a/typeshed/stdlib/3/tkinter/ttk.pyi b/typeshed/stdlib/3/tkinter/ttk.pyi
new file mode 100644
index 0000000..099f308
--- /dev/null
+++ b/typeshed/stdlib/3/tkinter/ttk.pyi
@@ -0,0 +1,158 @@
+# Stubs for tkinter.ttk (Python 3.5)
+#
+# NOTE: This dynamically typed stub was automatically generated by stubgen.
+
+from typing import Any
+import tkinter
+
+def tclobjs_to_py(adict): ...
+def setup_master(master=None): ...
+
+class Style:
+    master = ...  # type: Any
+    tk = ...  # type: Any
+    def __init__(self, master=None): ...
+    def configure(self, style, query_opt=None, **kw): ...
+    def map(self, style, query_opt=None, **kw): ...
+    def lookup(self, style, option, state=None, default=None): ...
+    def layout(self, style, layoutspec=None): ...
+    def element_create(self, elementname, etype, *args, **kw): ...
+    def element_names(self): ...
+    def element_options(self, elementname): ...
+    def theme_create(self, themename, parent=None, settings=None): ...
+    def theme_settings(self, themename, settings): ...
+    def theme_names(self): ...
+    def theme_use(self, themename=None): ...
+
+class Widget(tkinter.Widget):
+    def __init__(self, master, widgetname, kw=None): ...
+    def identify(self, x, y): ...
+    def instate(self, statespec, callback=None, *args, **kw): ...
+    def state(self, statespec=None): ...
+
+class Button(Widget):
+    def __init__(self, master=None, **kw): ...
+    def invoke(self): ...
+
+class Checkbutton(Widget):
+    def __init__(self, master=None, **kw): ...
+    def invoke(self): ...
+
+class Entry(Widget, tkinter.Entry):
+    def __init__(self, master=None, widget=None, **kw): ...
+    def bbox(self, index): ...
+    def identify(self, x, y): ...
+    def validate(self): ...
+
+class Combobox(Entry):
+    def __init__(self, master=None, **kw): ...
+    def current(self, newindex=None): ...
+    def set(self, value): ...
+
+class Frame(Widget):
+    def __init__(self, master=None, **kw): ...
+
+class Label(Widget):
+    def __init__(self, master=None, **kw): ...
+
+class Labelframe(Widget):
+    def __init__(self, master=None, **kw): ...
+
+LabelFrame = ...  # type: Any
+
+class Menubutton(Widget):
+    def __init__(self, master=None, **kw): ...
+
+class Notebook(Widget):
+    def __init__(self, master=None, **kw): ...
+    def add(self, child, **kw): ...
+    def forget(self, tab_id): ...
+    def hide(self, tab_id): ...
+    def identify(self, x, y): ...
+    def index(self, tab_id): ...
+    def insert(self, pos, child, **kw): ...
+    def select(self, tab_id=None): ...
+    def tab(self, tab_id, option=None, **kw): ...
+    def tabs(self): ...
+    def enable_traversal(self): ...
+
+class Panedwindow(Widget, tkinter.PanedWindow):
+    def __init__(self, master=None, **kw): ...
+    forget = ...  # type: Any
+    def insert(self, pos, child, **kw): ...
+    def pane(self, pane, option=None, **kw): ...
+    def sashpos(self, index, newpos=None): ...
+
+PanedWindow = ...  # type: Any
+
+class Progressbar(Widget):
+    def __init__(self, master=None, **kw): ...
+    def start(self, interval=None): ...
+    def step(self, amount=None): ...
+    def stop(self): ...
+
+class Radiobutton(Widget):
+    def __init__(self, master=None, **kw): ...
+    def invoke(self): ...
+
+class Scale(Widget, tkinter.Scale):
+    def __init__(self, master=None, **kw): ...
+    def configure(self, cnf=None, **kw): ...
+    def get(self, x=None, y=None): ...
+
+class Scrollbar(Widget, tkinter.Scrollbar):
+    def __init__(self, master=None, **kw): ...
+
+class Separator(Widget):
+    def __init__(self, master=None, **kw): ...
+
+class Sizegrip(Widget):
+    def __init__(self, master=None, **kw): ...
+
+class Treeview(Widget, tkinter.XView, tkinter.YView):
+    def __init__(self, master=None, **kw): ...
+    def bbox(self, item, column=None): ...
+    def get_children(self, item=None): ...
+    def set_children(self, item, *newchildren): ...
+    def column(self, column, option=None, **kw): ...
+    def delete(self, *items): ...
+    def detach(self, *items): ...
+    def exists(self, item): ...
+    def focus(self, item=None): ...
+    def heading(self, column, option=None, **kw): ...
+    def identify(self, component, x, y): ...
+    def identify_row(self, y): ...
+    def identify_column(self, x): ...
+    def identify_region(self, x, y): ...
+    def identify_element(self, x, y): ...
+    def index(self, item): ...
+    def insert(self, parent, index, iid=None, **kw): ...
+    def item(self, item, option=None, **kw): ...
+    def move(self, item, parent, index): ...
+    reattach = ...  # type: Any
+    def next(self, item): ...
+    def parent(self, item): ...
+    def prev(self, item): ...
+    def see(self, item): ...
+    def selection(self, selop=None, items=None): ...
+    def selection_set(self, items): ...
+    def selection_add(self, items): ...
+    def selection_remove(self, items): ...
+    def selection_toggle(self, items): ...
+    def set(self, item, column=None, value=None): ...
+    def tag_bind(self, tagname, sequence=None, callback=None): ...
+    def tag_configure(self, tagname, option=None, **kw): ...
+    def tag_has(self, tagname, item=None): ...
+
+class LabeledScale(Frame):
+    label = ...  # type: Any
+    scale = ...  # type: Any
+    def __init__(self, master=None, variable=None, from_=0, to=10, **kw): ...
+    def destroy(self): ...
+    value = ...  # type: Any
+
+class OptionMenu(Menubutton):
+    def __init__(self, master, variable, default=None, *values, **kwargs): ...
+    def __getitem__(self, item): ...
+    def set_menu(self, default=None, *values): ...
+    def destroy(self): ...
diff --git a/typeshed/stdlib/3/typing.pyi b/typeshed/stdlib/3/typing.pyi
index 8bb7606..33235c7 100644
--- a/typeshed/stdlib/3/typing.pyi
+++ b/typeshed/stdlib/3/typing.pyi
@@ -12,6 +12,7 @@ TypeVar = object()
 Generic = object()
 Tuple = object()
 Callable = object()
+Type = object()
 builtinclass = object()
 _promote = object()
 NamedTuple = object()
@@ -360,9 +361,9 @@ class Match(Generic[AnyStr]):
 
     def groups(self, default: AnyStr = ...) -> Sequence[AnyStr]: ...
     def groupdict(self, default: AnyStr = ...) -> dict[str, AnyStr]: ...
-    def start(self, group: int = ...) -> int: ...
-    def end(self, group: int = ...) -> int: ...
-    def span(self, group: int = ...) -> Tuple[int, int]: ...
+    def start(self, group: Union[int, str] = ...) -> int: ...
+    def end(self, group: Union[int, str] = ...) -> int: ...
+    def span(self, group: Union[int, str] = ...) -> Tuple[int, int]: ...
 
 class Pattern(Generic[AnyStr]):
     flags = 0
diff --git a/typeshed/stdlib/3/urllib/request.pyi b/typeshed/stdlib/3/urllib/request.pyi
index 3aeb20f..bdfa336 100644
--- a/typeshed/stdlib/3/urllib/request.pyi
+++ b/typeshed/stdlib/3/urllib/request.pyi
@@ -1,15 +1,199 @@
-# Stubs for urllib.request
+# Stubs for urllib.request (Python 3.4)
 
-# NOTE: These are incomplete!
+from typing import (
+    Any, Callable, List, IO, Mapping, Optional, Sequence, Tuple, TypeVar, Union,
+    overload,
+)
+from http.client import HTTPResponse, HTTPMessage
+from http.cookiejar import CookieJar
+from email.message import Message
+from urllib.response import addinfourl
+import ssl
+import sys
 
-from typing import Any
 
-class BaseHandler(): ...
-class HTTPRedirectHandler(BaseHandler): ...
-class OpenerDirector(): ...
+_T = TypeVar('_T')
+_UrlopenRet = Union[HTTPResponse, addinfourl]
 
-# TODO args should be types that extend BaseHandler (types, not instances)
-def build_opener(*args: Any) -> OpenerDirector: ...
+
+def urlopen(url: Union[str, 'Request'], data: Optional[bytes] = ...,
+            timeout: float = ..., *, cafile: Optional[str] = ...,
+            capath: Optional[str] = ..., cadefault: bool = ...,
+            context: Optional[ssl.SSLContext] = ...) \
+            -> _UrlopenRet: ...
 def install_opener(opener: OpenerDirector) -> None: ...
+def build_opener(*handlers: Union[BaseHandler, Callable[[], BaseHandler]]) \
+                 -> OpenerDirector: ...
+def url2pathname(path: str) -> str: ...
+def pathname2url(path: str) -> str: ...
+def getproxies() -> Dict[str, str]: ...
+
+
+class Request:
+    if sys.version_info >= (3, 4):
+        @property
+        def full_url(self) -> str: ...
+        @full_url.setter
+        def full_url(self, value: str) -> None: ...
+        @full_url.deleter
+        def full_url(self) -> None: ...
+    else:
+        full_url = ...  # type: ignore # type: str
+    type = ...  # type: str
+    host = ...  # type: str
+    origin_req_host = ...  # type: str
+    selector = ...  # type: str
+    data = ...  # type: Optional[bytes]
+    unverifiable = ...  # type: bool
+    method = ...  # type: Optional[str]
+    def __init__(self, url: str, data: Optional[bytes] = ...,
+            headers: Dict[str, str] =..., origin_req_host: Optional[str] = ...,
+            unverifiable: bool = ..., method: Optional[str] = ...) -> None: ...
+    def get_method(self) -> str: ...
+    def add_header(self, key: str, val: str) -> None: ...
+    def add_unredirected_header(self, key: str, val: str) -> None: ...
+    def has_header(self, header_name: str) -> bool: ...
+    if sys.version_info >= (3, 4):
+        def remove_header(self, header_name: str) -> None: ...
+    def get_full_url(self) -> str: ...
+    def set_proxy(self, host: str, type: str) -> None: ...
+    @overload
+    def get_header(self, header_name: str) -> Optional[str]: ...
+    @overload
+    def get_header(self, header_name: str, default: _T) -> Union[str, _T]: ...
+    def header_items(self) -> List[Tuple[str, str]]: ...
+
+class OpenerDirector:
+    def add_handler(self, handler: BaseHandler) -> None: ...
+    def open(self, url: Union[str, Request], data: Optional[bytes] = None,
+             timeout: float = ...) -> _UrlopenRet: ...
+    def error(self, proto: str, *args: Any) -> _UrlopenRet: ...
+
+
+class BaseHandler:
+    parent = ...  # type: OpenerDirector
+    def add_parent(self, parent: OpenerDirector) -> None: ...
+    def close(self) -> None: ...
+    def http_error_nnn(req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> _UrlopenRet: ...
+
+class HTTPDefaultErrorHandler(BaseHandler): ...
+
+class HTTPRedirectHandler(BaseHandler):
+    def redirect_request(self, req: Request, fp: IO[str], code: int, msg: int,
+                         hdrs: Mapping[str, str],
+                         newurl: str) -> Optional[Request]: ...
+    def http_error_301(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+    def http_error_302(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+    def http_error_303(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+    def http_error_307(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+
+class HTTPCookieProcessor(BaseHandler):
+    cookiejar = ...  # type: CookieJar
+    def __init__(self, cookiejar: Optional[CookieJar] = ...) -> None: ...
+
+class ProxyHandler(BaseHandler):
+    def __init__(self, proxies: Optional[Dict[str, str]] = ...) -> None: ...
+    # TODO add a method for every (common) proxy protocol
+
+class HTTPPasswordMgr:
+    def add_password(self, realm: str, uri: Union[str, Sequence[str]],
+                     user: str, passwd: str) -> None: ...
+    def find_user_password(self, realm: str, authuri: str) \
+                           -> Tuple[Optional[str], Optional[str]]: ...
+
+class HTTPPasswordMgrWithDefaultRealm:
+    def add_password(self, realm: str, uri: Union[str, Sequence[str]],
+                     user: str, passwd: str) -> None: ...
+    def find_user_password(self, realm: str, authuri: str) \
+                           -> Tuple[Optional[str], Optional[str]]: ...
+
+if sys.version_info >= (3, 5):
+    class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm):
+        def add_password(self, realm: str, uri: Union[str, Sequence[str]],
+                         user: str, passwd: str,
+                         is_authenticated: bool = ...) -> None: ...
+        def update_authenticated(uri: Union[str, Sequence[str]],
+                                 is_authenticated: bool = ...) -> None: ...
+        def is_authenticated(authuri: str) -> bool: ...
+
+class AbstractBasicAuthHandler:
+    def __init__(self,
+                 password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ...
+    def http_error_auth_reqed(self, authreq: str, host: str, req: Request,
+                              headers: Mapping[str, str]) -> None: ...
+
+class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
+    def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+
+class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
+    def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+
+class AbstractDigestAuthHandler:
+    def __init__(self,
+                 password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ...
+    def http_error_auth_reqed(self, auth_header: str, host: str, req: Request,
+                              headers: Mapping[str, str]) -> None: ...
+
+class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
+    def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+
+class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
+    def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int,
+                       hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ...
+
+class HTTPHandler(BaseHandler):
+    def http_open(self, req: Request) -> _UrlopenRet: ...
+
+class HTTPSHandler(BaseHandler):
+    def __init__(self, debuglevel: int = 0,
+                 context: Optional[ssl.SSLContext] = ...,
+                 check_hostname: bool = ...) -> None: ...
+    def https_open(self, req: Request) -> _UrlopenRet: ...
+
+class FileHandler(BaseHandler):
+    def file_open(self, req: Request) -> _UrlopenRet: ...
+
+class DataHandler(BaseHandler):
+    def data_open(self, req: Request) -> _UrlopenRet: ...
+
+class FTPHandler(BaseHandler):
+    def ftp_open(self, req: Request) -> _UrlopenRet: ...
+
+class CacheFTPHandler(FTPHandler):
+    def setTimeout(self, t: float) -> None: ...
+    def setMaxConns(self, m: int) -> None: ...
+
+class UnknownHandler(BaseHandler):
+    def unknown_open(self, req: Request) -> _UrlopenRet: ...
+
+class HTTPErrorProcessor(BaseHandler):
+    def http_response(self) -> _UrlopenRet: ...
+    def https_response(self) -> _UrlopenRet: ...
+
+
+def urlretrieve(url: str, filename: Optional[str] = ...,
+                reporthook: Optional[Callable[[int, int, int], None]] = ...,
+                data: Optional[bytes] = ...) -> Tuple[str, HTTPMessage]: ...
+def urlcleanup() -> None: ...
+
+class URLopener:
+    version = ...  # type: str
+    def __init__(self, proxies: Optional[Dict[str, str]] = ...,
+                 **x509: str) -> None: ...
+    def open(self, fullurl: str, data: Optional[bytes] = ...) -> _UrlopenRet: ...
+    def open_unknown(self, fullurl: str,
+                     data: Optional[bytes] = ...) -> _UrlopenRet: ...
+    def retrieve(url: str, filename: Optional[str] = ...,
+                 reporthook: Optional[Callable[[int, int, int], None]] = ...,
+                 data: Optional[bytes] = ...) -> Tuple[str, Optional[Message]]: ...
 
-def proxy_bypass(host): ...
+class FancyURLopener(URLopener):
+    def prompt_user_passwd(self, host: str, realm: str) -> Tuple[str, str]: ...
diff --git a/typeshed/stdlib/3/urllib/response.pyi b/typeshed/stdlib/3/urllib/response.pyi
index 20b01ea..033bbaa 100644
--- a/typeshed/stdlib/3/urllib/response.pyi
+++ b/typeshed/stdlib/3/urllib/response.pyi
@@ -1,32 +1,8 @@
-from typing import Any
+# private module, we only expose what's needed
 
-class addbase:
-    fp = ... # type: Any
-    read = ... # type: Any
-    readline = ... # type: Any
-    readlines = ... # type: Any
-    fileno = ... # type: Any
-    __iter__ = ... # type: Any
-    next = ... # type: Any
-    def __init__(self, fp) -> None: ...
-    def close(self): ...
+from typing import BinaryIO, Mapping, Optional
+from types import TracebackType
 
-class addclosehook(addbase):
-    closehook = ... # type: Any
-    hookargs = ... # type: Any
-    def __init__(self, fp, closehook, *hookargs) -> None: ...
-    def close(self): ...
-
-class addinfo(addbase):
-    headers = ... # type: Any
-    def __init__(self, fp, headers) -> None: ...
-    def info(self): ...
-
-class addinfourl(addbase):
-    headers = ... # type: Any
-    url = ... # type: Any
-    code = ... # type: Any
-    def __init__(self, fp, headers, url, code=...) -> None: ...
-    def info(self): ...
-    def getcode(self): ...
-    def geturl(self): ...
+class addinfourl(BinaryIO):
+    def info(self) -> Mapping[str, str]: ...
+    def geturl(self) -> str: ...
diff --git a/typeshed/stdlib/3/urllib/robotparser.pyi b/typeshed/stdlib/3/urllib/robotparser.pyi
index 403039a..e8403f7 100644
--- a/typeshed/stdlib/3/urllib/robotparser.pyi
+++ b/typeshed/stdlib/3/urllib/robotparser.pyi
@@ -1,7 +1,18 @@
+# Stubs for urllib.robotparser (Python 3.4)
+
+from typing import Iterable, NamedTuple, Optional
+import sys
+
+_RequestRate = NamedTuple('_RequestRate', [('requests', int), ('seconds', int)])
+
 class RobotFileParser:
-    def set_url(self, url: str): ...
-    def read(self): ...
-    def parse(self, lines: str): ...
-    def can_fetch(self, user_agent: str, url: str): ...
-    def mtime(self): ...
-    def modified(self): ...
+    def __init__(url: str = ...) -> None: ...
+    def set_url(self, url: str) -> None: ...
+    def read(self) -> None: ...
+    def parse(self, lines: Iterable[str]) -> None: ...
+    def can_fetch(self, user_agent: str, url: str) -> bool: ...
+    def mtime(self) -> int: ...
+    def modified(self) -> None: ...
+    if sys.version_info >= (3, 6):
+        def crawl_delay(useragent: str) -> Optional[str]: ...
+        def request_rate(useragent: str) -> Optional[_RequestRate]: ...
diff --git a/typeshed/third_party/2.7/requests/__init__.pyi b/typeshed/third_party/2.7/requests/__init__.pyi
index 6ea56ef..a42d186 100644
--- a/typeshed/third_party/2.7/requests/__init__.pyi
+++ b/typeshed/third_party/2.7/requests/__init__.pyi
@@ -12,6 +12,7 @@ __title__ = ...  # type: Any
 __build__ = ...  # type: Any
 __license__ = ...  # type: Any
 __copyright__ = ...  # type: Any
+__version__ = ... # type: Any
 
 Request = models.Request
 Response = models.Response
diff --git a/typeshed/third_party/2.7/requests/api.pyi b/typeshed/third_party/2.7/requests/api.pyi
index 7b04128..0f13779 100644
--- a/typeshed/third_party/2.7/requests/api.pyi
+++ b/typeshed/third_party/2.7/requests/api.pyi
@@ -1,14 +1,15 @@
 # Stubs for requests.api (Python 3)
 
-import typing
+from typing import Union
 
 from .models import Response
 
 def request(method: str, url: str, **kwargs) -> Response: ...
-def get(url: str, **kwargs) -> Response: ...
-def options(url: str, **kwargs) -> Response: ...
-def head(url: str, **kwargs) -> Response: ...
-def post(url: str, data=..., json=..., **kwargs) -> Response: ...
-def put(url: str, data=..., **kwargs) -> Response: ...
-def patch(url: str, data=..., **kwargs) -> Response: ...
-def delete(url: str, **kwargs) -> Response: ...
+def get(url: Union[str, unicode], **kwargs) -> Response: ...
+def options(url: Union[str, unicode], **kwargs) -> Response: ...
+def head(url: Union[str, unicode], **kwargs) -> Response: ...
+def post(url: Union[str, unicode], data=..., json=...,
+         **kwargs) -> Response: ...
+def put(url: Union[str, unicode], data=..., **kwargs) -> Response: ...
+def patch(url: Union[str, unicode], data=..., **kwargs) -> Response: ...
+def delete(url: Union[str, unicode], **kwargs) -> Response: ...
diff --git a/typeshed/third_party/2.7/six/moves/__init__.pyi b/typeshed/third_party/2.7/six/moves/__init__.pyi
index 1347e75..e2dee78 100644
--- a/typeshed/third_party/2.7/six/moves/__init__.pyi
+++ b/typeshed/third_party/2.7/six/moves/__init__.pyi
@@ -1,5 +1,6 @@
 # Provisional stubs for six.moves (Python 2.7)
 
+import Cookie as http_cookies
 from cStringIO import StringIO as cStringIO
 from itertools import ifilter as filter
 from itertools import ifilterfalse as filterfalse
diff --git a/typeshed/third_party/3/requests/__init__.pyi b/typeshed/third_party/3/requests/__init__.pyi
index 173481a..a89d4a0 100644
--- a/typeshed/third_party/3/requests/__init__.pyi
+++ b/typeshed/third_party/3/requests/__init__.pyi
@@ -12,6 +12,7 @@ __title__ = ...  # type: Any
 __build__ = ...  # type: Any
 __license__ = ...  # type: Any
 __copyright__ = ...  # type: Any
+__version__ = ...  # type: Any
 
 Request = models.Request
 Response = models.Response
diff --git a/typeshed/third_party/3/six/moves/__init__.pyi b/typeshed/third_party/3/six/moves/__init__.pyi
index 49cf9bc..b2dc6cd 100644
--- a/typeshed/third_party/3/six/moves/__init__.pyi
+++ b/typeshed/third_party/3/six/moves/__init__.pyi
@@ -3,6 +3,7 @@
 #
 # Stubs for six.moves (Python 3.2)
 
+from http import cookies as http_cookies
 from io import StringIO as cStringIO
 from builtins import filter as filter
 from itertools import filterfalse as filterfalse
diff --git a/typeshed/third_party/3/six/moves/urllib/request.pyi b/typeshed/third_party/3/six/moves/urllib/request.pyi
index 1a75378..b15ced7 100644
--- a/typeshed/third_party/3/six/moves/urllib/request.pyi
+++ b/typeshed/third_party/3/six/moves/urllib/request.pyi
@@ -37,4 +37,4 @@ from urllib.request import build_opener as build_opener
 # from urllib.request import urlcleanup as urlcleanup
 # from urllib.request import URLopener as URLopener
 # from urllib.request import FancyURLopener as FancyURLopener
-from urllib.request import proxy_bypass as proxy_bypass
+# from urllib.request import proxy_bypass as proxy_bypass
diff --git a/typeshed/third_party/3/six/moves/urllib/response.pyi b/typeshed/third_party/3/six/moves/urllib/response.pyi
index 93ec5ce..c3b34a8 100644
--- a/typeshed/third_party/3/six/moves/urllib/response.pyi
+++ b/typeshed/third_party/3/six/moves/urllib/response.pyi
@@ -1,9 +1 @@
-# Generated by stubtool 0.1, DO NOT EDIT
-# See https://github.com/o11c/stubtool
-#
-# Stubs for six.moves.urllib.response (Python 3.2)
-
-from urllib.response import addbase as addbase
-from urllib.response import addclosehook as addclosehook
-from urllib.response import addinfo as addinfo
 from urllib.response import addinfourl as addinfourl
diff --git a/typeshed/third_party/3/six/moves/urllib_response.pyi b/typeshed/third_party/3/six/moves/urllib_response.pyi
index 0a834a7..1574d7d 100644
--- a/typeshed/third_party/3/six/moves/urllib_response.pyi
+++ b/typeshed/third_party/3/six/moves/urllib_response.pyi
@@ -1,11 +1 @@
-# Generated by stubtool 0.1, DO NOT EDIT
-# See https://github.com/o11c/stubtool
-#
-# Stubs for six.moves.urllib_response (Python 3.2)
-
-from six.moves.urllib.response import (
-    addbase as addbase,
-    addclosehook as addclosehook,
-    addinfo as addinfo,
-    addinfourl as addinfourl,
-)
+from six.moves.urllib.response import addinfourl as addinfourl

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-med/mypy.git



More information about the debian-med-commit mailing list