[med-svn] [mypy] 01/01: New upstream version 0.520

Michael Crusoe misterc-guest at moszumanska.debian.org
Sat Oct 7 17:16:03 UTC 2017


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

misterc-guest pushed a commit to annotated tag upstream/0.520
in repository mypy.

commit c2332c17d1bf9b0d5bc925fc5bc742c9938d82ae
Author: Michael R. Crusoe <michael.crusoe at gmail.com>
Date:   Fri Jul 14 07:55:19 2017 -0700

    New upstream version 0.520
---
 PKG-INFO                                           |   2 +-
 mypy.egg-info/PKG-INFO                             |   2 +-
 mypy.egg-info/SOURCES.txt                          |  91 ++-
 mypy.egg-info/entry_points.txt                     |   4 +
 mypy.egg-info/requires.txt                         |   2 +-
 mypy/__main__.py                                   |   8 +-
 mypy/binder.py                                     |  36 +-
 mypy/build.py                                      | 318 ++++++--
 mypy/checker.py                                    | 204 +++--
 mypy/checkexpr.py                                  | 437 ++++++++---
 mypy/checkmember.py                                |  74 +-
 mypy/constraints.py                                |   5 +-
 mypy/erasetype.py                                  |   2 +-
 mypy/errors.py                                     |   4 +-
 mypy/expandtype.py                                 |   2 +-
 mypy/experiments.py                                |  12 +-
 mypy/exprtotype.py                                 |   1 +
 mypy/fastparse.py                                  |  99 +--
 mypy/fastparse2.py                                 |  37 +-
 mypy/fixup.py                                      |  32 +-
 mypy/join.py                                       |  12 +-
 mypy/main.py                                       |  74 +-
 mypy/meet.py                                       |  22 +-
 mypy/messages.py                                   | 287 +++++--
 mypy/nodes.py                                      | 108 ++-
 mypy/options.py                                    |  15 +-
 mypy/parse.py                                      |   6 +-
 mypy/plugin.py                                     | 334 ++++++++
 mypy/report.py                                     |  83 +-
 mypy/semanal.py                                    | 838 +++++++++++++++------
 mypy/stats.py                                      |  59 +-
 mypy/stubgen.py                                    |  34 +-
 mypy/subtypes.py                                   |  55 +-
 mypy/traverser.py                                  |  10 +-
 mypy/treetransform.py                              |   3 +-
 mypy/tvar_scope.py                                 |   3 +-
 mypy/typeanal.py                                   | 336 ++++++---
 mypy/typefixture.py                                |  12 +-
 mypy/types.py                                      | 178 +++--
 mypy/version.py                                    |   2 +-
 mypy/waiter.py                                     |  16 +-
 scripts/stubgen                                    |   0
 setup.cfg                                          |   3 +-
 setup.py                                           |   8 +-
 typeshed/stdlib/2/Cookie.pyi                       |   4 -
 typeshed/stdlib/2/SocketServer.pyi                 |  20 +-
 typeshed/stdlib/2/__builtin__.pyi                  |  58 +-
 typeshed/stdlib/2/_ast.pyi                         |  24 +-
 typeshed/stdlib/2/_io.pyi                          | 123 ++-
 typeshed/stdlib/2/_threading_local.pyi             |  14 +
 typeshed/stdlib/2/_weakrefset.pyi                  |  14 -
 typeshed/stdlib/2/ast.pyi                          |   4 +-
 typeshed/stdlib/2/builtins.pyi                     |  58 +-
 typeshed/stdlib/2/calendar.pyi                     |  92 ---
 typeshed/stdlib/2/collections.pyi                  |  41 +-
 typeshed/stdlib/2/compileall.pyi                   |   8 +-
 typeshed/stdlib/2/cookielib.pyi                    |   4 -
 typeshed/stdlib/2/csv.pyi                          |  88 ---
 typeshed/stdlib/2/datetime.pyi                     |   7 +-
 typeshed/stdlib/2/doctest.pyi                      |   9 -
 typeshed/stdlib/2/dummy_thread.pyi                 |  22 +
 typeshed/stdlib/2/email/MIMEText.pyi               |   4 -
 typeshed/stdlib/2/email/_parseaddr.pyi             |   4 -
 typeshed/stdlib/2/email/mime/base.pyi              |   4 +-
 typeshed/stdlib/2/email/mime/multipart.pyi         |   4 -
 typeshed/stdlib/2/email/mime/nonmultipart.pyi      |   4 -
 typeshed/stdlib/2/email/mime/text.pyi              |   4 -
 typeshed/stdlib/2/email/utils.pyi                  |   4 -
 typeshed/stdlib/2/fileinput.pyi                    |  46 --
 typeshed/stdlib/2/genericpath.pyi                  |  20 +-
 typeshed/stdlib/2/glob.pyi                         |   4 +-
 typeshed/stdlib/2/grp.pyi                          |  11 -
 typeshed/stdlib/2/gzip.pyi                         |  10 +-
 typeshed/stdlib/2/htmlentitydefs.pyi               |   4 -
 typeshed/stdlib/2/inspect.pyi                      |   2 +-
 typeshed/stdlib/2/io.pyi                           | 111 +--
 typeshed/stdlib/2/itertools.pyi                    |  44 +-
 typeshed/stdlib/2/linecache.pyi                    |   7 -
 typeshed/stdlib/2/macpath.pyi                      |  16 +-
 typeshed/stdlib/2/mimetools.pyi                    |   4 -
 typeshed/stdlib/2/multiprocessing/__init__.pyi     |   4 -
 typeshed/stdlib/2/multiprocessing/process.pyi      |   4 -
 typeshed/stdlib/2/multiprocessing/util.pyi         |   4 -
 typeshed/stdlib/2/ntpath.pyi                       |  16 +-
 typeshed/stdlib/2/os/__init__.pyi                  | 260 ++++---
 typeshed/stdlib/2/os/path.pyi                      |  32 +-
 typeshed/stdlib/2/os2emxpath.pyi                   |  16 +-
 typeshed/stdlib/2/pdb.pyi                          |  30 -
 typeshed/stdlib/2/pickle.pyi                       |  38 -
 typeshed/stdlib/2/popen2.pyi                       |  29 +
 typeshed/stdlib/2/posixpath.pyi                    |  16 +-
 typeshed/stdlib/2/pwd.pyi                          |  17 -
 typeshed/stdlib/2/pydoc.pyi                        |   4 -
 typeshed/stdlib/2/re.pyi                           |   1 +
 typeshed/stdlib/2/runpy.pyi                        |   4 -
 typeshed/stdlib/2/select.pyi                       | 100 ---
 typeshed/stdlib/2/shutil.pyi                       |   4 -
 typeshed/stdlib/2/smtplib.pyi                      |   4 -
 typeshed/stdlib/2/spwd.pyi                         |  14 +
 typeshed/stdlib/2/sqlite3/__init__.pyi             |   4 -
 typeshed/stdlib/2/sqlite3/dbapi2.pyi               |   5 +-
 typeshed/stdlib/2/subprocess.pyi                   |   2 +-
 typeshed/stdlib/2/sys.pyi                          |   4 +-
 typeshed/stdlib/2/textwrap.pyi                     |   8 +-
 typeshed/stdlib/2/time.pyi                         |   5 +-
 typeshed/stdlib/2/toaiff.pyi                       |  16 +
 typeshed/stdlib/2/types.pyi                        |   1 +
 typeshed/stdlib/2/typing.pyi                       |  40 +-
 typeshed/stdlib/2/unittest.pyi                     |  41 +-
 typeshed/stdlib/2/urllib.pyi                       |   3 -
 typeshed/stdlib/2/urllib2.pyi                      |   2 +-
 typeshed/stdlib/2/urlparse.pyi                     |  30 +-
 typeshed/stdlib/2/user.pyi                         |   9 +
 typeshed/stdlib/2/weakref.pyi                      |  47 --
 typeshed/stdlib/2/wsgiref/validate.pyi             |   4 -
 typeshed/stdlib/2and3/__future__.pyi               |  23 +-
 typeshed/stdlib/2and3/_csv.pyi                     |  45 ++
 typeshed/stdlib/{2 => 2and3}/_weakref.pyi          |  11 +-
 typeshed/stdlib/2and3/_weakrefset.pyi              |  43 ++
 typeshed/stdlib/2and3/asynchat.pyi                 |  22 +-
 typeshed/stdlib/2and3/asyncore.pyi                 |  92 ++-
 typeshed/stdlib/2and3/bz2.pyi                      |  10 +-
 typeshed/stdlib/{3 => 2and3}/calendar.pyi          |  56 +-
 typeshed/stdlib/2and3/contextlib.pyi               |  27 +-
 typeshed/stdlib/2and3/csv.pyi                      |  97 +++
 typeshed/stdlib/{2 => 2and3}/difflib.pyi           |  28 +-
 typeshed/stdlib/2and3/distutils/core.pyi           |   4 +-
 typeshed/stdlib/2and3/distutils/version.pyi        |   4 -
 typeshed/stdlib/2and3/doctest.pyi                  | 161 ++++
 typeshed/stdlib/{3 => 2and3}/fileinput.pyi         |  33 +-
 typeshed/stdlib/2and3/grp.pyi                      |  10 +
 typeshed/stdlib/2and3/linecache.pyi                |  12 +
 typeshed/stdlib/2and3/locale.pyi                   |   3 +-
 typeshed/stdlib/2and3/logging/__init__.pyi         |  39 +-
 typeshed/stdlib/2and3/logging/config.pyi           |   4 +-
 typeshed/stdlib/2and3/logging/handlers.pyi         |   4 +-
 typeshed/stdlib/2and3/numbers.pyi                  |   4 +-
 typeshed/stdlib/2and3/optparse.pyi                 |   4 +-
 typeshed/stdlib/2and3/pdb.pyi                      |  30 +
 typeshed/stdlib/2and3/pickle.pyi                   | 140 ++++
 typeshed/stdlib/2and3/pstats.pyi                   |  12 +-
 typeshed/stdlib/2and3/pwd.pyi                      |  13 +
 typeshed/stdlib/2and3/sched.pyi                    |   2 -
 typeshed/stdlib/2and3/select.pyi                   | 137 ++++
 typeshed/stdlib/2and3/smtpd.pyi                    |   2 +-
 typeshed/stdlib/2and3/socket.pyi                   | 646 ++++++++++------
 typeshed/stdlib/2and3/spwd.pyi                     |  15 -
 typeshed/stdlib/2and3/symtable.pyi                 |   6 +-
 typeshed/stdlib/2and3/tarfile.pyi                  |  26 +-
 typeshed/stdlib/2and3/threading.pyi                |   3 +-
 typeshed/stdlib/2and3/weakref.pyi                  | 110 +++
 typeshed/stdlib/2and3/webbrowser.pyi               |   4 -
 typeshed/stdlib/2and3/xml/__init__.pyi             |  20 -
 typeshed/stdlib/2and3/xml/sax/handler.pyi          |   4 -
 typeshed/stdlib/2and3/xml/sax/saxutils.pyi         |  19 +-
 typeshed/stdlib/2and3/xml/sax/xmlreader.pyi        |   4 -
 typeshed/stdlib/2and3/zipfile.pyi                  |   1 +
 typeshed/stdlib/2and3/zlib.pyi                     |  16 +-
 typeshed/stdlib/3.3/ipaddress.pyi                  | 149 ++--
 typeshed/stdlib/3.4/asyncio/__init__.pyi           |  16 +-
 typeshed/stdlib/3.4/asyncio/coroutines.pyi         |   4 +-
 typeshed/stdlib/3.4/asyncio/events.pyi             |  36 +-
 typeshed/stdlib/3.4/asyncio/futures.pyi            |  14 +-
 typeshed/stdlib/3.4/asyncio/locks.pyi              |  17 +-
 typeshed/stdlib/3.4/asyncio/protocols.pyi          |   4 +-
 typeshed/stdlib/3.4/asyncio/queues.pyi             |   4 +-
 typeshed/stdlib/3.4/asyncio/streams.pyi            |  20 +-
 typeshed/stdlib/3.4/asyncio/subprocess.pyi         |  18 +-
 typeshed/stdlib/3.4/asyncio/tasks.pyi              |   3 +-
 typeshed/stdlib/3.4/asyncio/transports.pyi         |   8 +-
 typeshed/stdlib/3.4/enum.pyi                       |  14 +-
 typeshed/stdlib/3.4/selectors.pyi                  |  78 +-
 typeshed/stdlib/3/_ast.pyi                         |  28 +-
 typeshed/stdlib/3/_compression.pyi                 |   4 -
 typeshed/stdlib/3/_curses.pyi                      | 243 +++++-
 typeshed/stdlib/3/_dummy_thread.pyi                |  25 +-
 typeshed/stdlib/3/_importlib_modulespec.pyi        |   4 +-
 typeshed/stdlib/3/builtins.pyi                     | 143 ++--
 typeshed/stdlib/3/collections/__init__.pyi         |  75 +-
 typeshed/stdlib/3/collections/abc.pyi              |   1 +
 typeshed/stdlib/3/compileall.pyi                   |  12 +-
 typeshed/stdlib/3/concurrent/futures/_base.pyi     |  18 +-
 typeshed/stdlib/3/concurrent/futures/process.pyi   |   7 +-
 typeshed/stdlib/3/concurrent/futures/thread.pyi    |  14 +-
 typeshed/stdlib/3/configparser.pyi                 |  66 +-
 typeshed/stdlib/3/csv.pyi                          |  77 --
 typeshed/stdlib/3/curses/__init__.pyi              |  10 +-
 typeshed/stdlib/3/datetime.pyi                     |  16 +-
 typeshed/stdlib/3/difflib.pyi                      |  62 --
 typeshed/stdlib/3/doctest.pyi                      |   9 -
 typeshed/stdlib/3/email/contentmanager.pyi         |   4 -
 typeshed/stdlib/3/email/headerregistry.pyi         |  11 +-
 typeshed/stdlib/3/email/message.pyi                |   6 +-
 typeshed/stdlib/3/functools.pyi                    |  36 +-
 typeshed/stdlib/3/getpass.pyi                      |   4 +-
 typeshed/stdlib/3/glob.pyi                         |   7 +
 typeshed/stdlib/3/grp.pyi                          |  13 -
 typeshed/stdlib/3/gzip.pyi                         |   4 -
 typeshed/stdlib/3/hashlib.pyi                      |  60 +-
 typeshed/stdlib/3/html/entities.pyi                |   4 -
 typeshed/stdlib/3/http/client.pyi                  |   3 +-
 typeshed/stdlib/3/http/cookiejar.pyi               |   3 +-
 typeshed/stdlib/3/importlib/__init__.pyi           |  12 +-
 typeshed/stdlib/3/importlib/abc.pyi                |  10 +-
 typeshed/stdlib/3/importlib/machinery.pyi          |  20 +-
 typeshed/stdlib/3/importlib/util.pyi               |  14 +-
 typeshed/stdlib/3/inspect.pyi                      |  17 +-
 typeshed/stdlib/3/io.pyi                           |   9 +-
 typeshed/stdlib/3/itertools.pyi                    |  52 +-
 typeshed/stdlib/3/json/decoder.pyi                 |  16 +-
 typeshed/stdlib/3/json/encoder.pyi                 |  10 +-
 typeshed/stdlib/3/linecache.pyi                    |   5 -
 typeshed/stdlib/3/multiprocessing/__init__.pyi     |  79 +-
 typeshed/stdlib/3/multiprocessing/context.pyi      | 163 ++++
 typeshed/stdlib/3/multiprocessing/managers.pyi     |  33 +-
 typeshed/stdlib/3/multiprocessing/pool.pyi         |  42 +-
 typeshed/stdlib/3/os/__init__.pyi                  | 322 ++++----
 typeshed/stdlib/3/os/path.pyi                      |  25 +-
 typeshed/stdlib/3/pdb.pyi                          |  30 -
 typeshed/stdlib/3/pickle.pyi                       |  67 --
 typeshed/stdlib/3/posix.pyi                        |   6 +
 typeshed/stdlib/3/pwd.pyi                          |  18 -
 typeshed/stdlib/3/queue.pyi                        |   2 +
 typeshed/stdlib/3/random.pyi                       |   5 +-
 typeshed/stdlib/3/re.pyi                           |   5 +-
 typeshed/stdlib/3/runpy.pyi                        |   4 -
 typeshed/stdlib/3/select.pyi                       |  27 -
 typeshed/stdlib/3/shutil.pyi                       |  11 +-
 typeshed/stdlib/3/smtplib.pyi                      |   4 -
 typeshed/stdlib/3/socketserver.pyi                 |  20 +-
 typeshed/stdlib/3/spwd.pyi                         |  14 +
 typeshed/stdlib/3/sqlite3/__init__.pyi             |   4 -
 typeshed/stdlib/3/sqlite3/dbapi2.pyi               |  12 +-
 typeshed/stdlib/3/ssl.pyi                          |   9 +-
 typeshed/stdlib/3/subprocess.pyi                   |  52 +-
 typeshed/stdlib/3/tempfile.pyi                     |   1 +
 typeshed/stdlib/3/time.pyi                         |  10 +
 typeshed/stdlib/3/tkinter/__init__.pyi             |   4 -
 typeshed/stdlib/3/tkinter/constants.pyi            |   4 -
 typeshed/stdlib/3/tkinter/ttk.pyi                  |   4 -
 typeshed/stdlib/3/tokenize.pyi                     |   5 +-
 typeshed/stdlib/3/types.pyi                        |  39 +-
 typeshed/stdlib/3/typing.pyi                       |  52 +-
 typeshed/stdlib/3/unittest/__init__.pyi            |   3 +-
 typeshed/stdlib/3/unittest/mock.pyi                |  28 +-
 typeshed/stdlib/3/urllib/request.pyi               |   6 +-
 typeshed/stdlib/3/weakref.pyi                      | 120 ---
 typeshed/stdlib/3/wsgiref/validate.pyi             |   4 -
 typeshed/tests/mypy_selftest.py                    |   1 +
 typeshed/tests/mypy_test.py                        |  12 +-
 typeshed/tests/pytype_test.py                      |   2 +-
 .../third_party/2/concurrent/futures/__init__.pyi  |  17 +-
 typeshed/third_party/2/croniter.pyi                |   4 -
 .../hazmat/primitives/serialization.pyi            |   4 -
 typeshed/third_party/2/dateutil/parser.pyi         |   8 +-
 typeshed/third_party/2/dateutil/tz/__init__.pyi    |   4 -
 typeshed/third_party/2/dateutil/tz/_common.pyi     |   4 -
 typeshed/third_party/2/dateutil/tz/tz.pyi          |   4 -
 typeshed/third_party/2/enum.pyi                    |  12 +-
 typeshed/third_party/2/fb303/FacebookService.pyi   |   4 -
 .../third_party/2/google/protobuf/descriptor.pyi   |   4 -
 .../2/google/protobuf/descriptor_pool.pyi          |   4 -
 .../2/google/protobuf/internal/decoder.pyi         |   4 -
 .../2/google/protobuf/internal/encoder.pyi         |   4 -
 .../2/google/protobuf/internal/wire_format.pyi     |   4 -
 typeshed/third_party/2/google/protobuf/message.pyi |  10 +-
 .../2/google/protobuf/message_factory.pyi          |   6 +-
 .../third_party/2/google/protobuf/reflection.pyi   |   4 -
 .../2/google/protobuf/symbol_database.pyi          |   4 -
 typeshed/third_party/2/itsdangerous.pyi            |   4 -
 typeshed/third_party/2/kazoo/__init__.pyi          |   3 -
 typeshed/third_party/2/kazoo/client.pyi            |   4 -
 typeshed/third_party/2/kazoo/exceptions.pyi        |   4 -
 typeshed/third_party/2/kazoo/recipe/__init__.pyi   |   3 -
 typeshed/third_party/2/kazoo/recipe/watchers.pyi   |   4 -
 typeshed/third_party/2/pymssql.pyi                 |   2 +-
 typeshed/third_party/2/redis/__init__.pyi          |   4 -
 typeshed/third_party/2/redis/client.pyi            |   4 -
 typeshed/third_party/2/redis/connection.pyi        |   4 -
 typeshed/third_party/2/redis/exceptions.pyi        |   4 -
 typeshed/third_party/2/redis/utils.pyi             |   4 -
 typeshed/third_party/2/routes/__init__.pyi         |   4 -
 typeshed/third_party/2/routes/mapper.pyi           |   4 -
 typeshed/third_party/2/routes/util.pyi             |   4 -
 typeshed/third_party/2/scribe/scribe.pyi           |   4 -
 typeshed/third_party/2/scribe/ttypes.pyi           |   4 -
 .../2/selenium/webdriver/remote/webdriver.pyi      |   4 -
 .../2/selenium/webdriver/remote/webelement.pyi     |   4 -
 typeshed/third_party/2/thrift/Thrift.pyi           |   4 -
 .../2/thrift/protocol/TBinaryProtocol.pyi          |   4 -
 .../third_party/2/thrift/protocol/TProtocol.pyi    |   4 -
 .../third_party/2/thrift/protocol/__init__.pyi     |   4 -
 .../third_party/2/thrift/transport/TSocket.pyi     |   4 -
 .../third_party/2/thrift/transport/TTransport.pyi  |   4 -
 .../third_party/2/thrift/transport/__init__.pyi    |   4 -
 typeshed/third_party/2/tornado/concurrent.pyi      |   4 -
 typeshed/third_party/2/tornado/gen.pyi             |   4 -
 typeshed/third_party/2/tornado/httpclient.pyi      |   4 -
 typeshed/third_party/2/tornado/httpserver.pyi      |   4 -
 typeshed/third_party/2/tornado/httputil.pyi        |   4 -
 typeshed/third_party/2/tornado/ioloop.pyi          |   4 -
 typeshed/third_party/2/tornado/locks.pyi           |   4 -
 typeshed/third_party/2/tornado/netutil.pyi         |   4 -
 typeshed/third_party/2/tornado/tcpserver.pyi       |   4 -
 typeshed/third_party/2/tornado/testing.pyi         |   4 -
 typeshed/third_party/2/tornado/util.pyi            |   4 -
 typeshed/third_party/2/tornado/web.pyi             |   4 -
 typeshed/third_party/2/werkzeug/__init__.pyi       |   4 -
 typeshed/third_party/2/werkzeug/_compat.pyi        |   4 -
 typeshed/third_party/2/werkzeug/_internal.pyi      |   4 -
 typeshed/third_party/2/werkzeug/_reloader.pyi      |   4 -
 .../third_party/2/werkzeug/contrib/__init__.pyi    |   3 -
 typeshed/third_party/2/werkzeug/contrib/atom.pyi   |   4 -
 typeshed/third_party/2/werkzeug/contrib/cache.pyi  |   4 -
 typeshed/third_party/2/werkzeug/contrib/fixers.pyi |   4 -
 typeshed/third_party/2/werkzeug/contrib/iterio.pyi |   4 -
 .../third_party/2/werkzeug/contrib/jsrouting.pyi   |   4 -
 .../third_party/2/werkzeug/contrib/limiter.pyi     |   4 -
 typeshed/third_party/2/werkzeug/contrib/lint.pyi   |   4 -
 .../third_party/2/werkzeug/contrib/profiler.pyi    |   4 -
 .../2/werkzeug/contrib/securecookie.pyi            |   4 -
 .../third_party/2/werkzeug/contrib/sessions.pyi    |   4 -
 .../third_party/2/werkzeug/contrib/testtools.pyi   |   4 -
 .../third_party/2/werkzeug/contrib/wrappers.pyi    |   4 -
 typeshed/third_party/2/werkzeug/datastructures.pyi |   4 -
 typeshed/third_party/2/werkzeug/debug/__init__.pyi |   4 -
 typeshed/third_party/2/werkzeug/debug/console.pyi  |   4 -
 typeshed/third_party/2/werkzeug/debug/repr.pyi     |   4 -
 typeshed/third_party/2/werkzeug/debug/tbtools.pyi  |   4 -
 typeshed/third_party/2/werkzeug/exceptions.pyi     |   4 -
 typeshed/third_party/2/werkzeug/filesystem.pyi     |   4 -
 typeshed/third_party/2/werkzeug/formparser.pyi     |   4 -
 typeshed/third_party/2/werkzeug/http.pyi           |   4 -
 typeshed/third_party/2/werkzeug/local.pyi          |   4 -
 typeshed/third_party/2/werkzeug/posixemulation.pyi |   4 -
 typeshed/third_party/2/werkzeug/routing.pyi        |   4 -
 typeshed/third_party/2/werkzeug/script.pyi         |   4 -
 typeshed/third_party/2/werkzeug/security.pyi       |   4 -
 typeshed/third_party/2/werkzeug/serving.pyi        |   4 -
 typeshed/third_party/2/werkzeug/test.pyi           |   4 -
 typeshed/third_party/2/werkzeug/testapp.pyi        |   4 -
 typeshed/third_party/2/werkzeug/urls.pyi           |   4 -
 typeshed/third_party/2/werkzeug/useragents.pyi     |   4 -
 typeshed/third_party/2/werkzeug/utils.pyi          |   4 -
 typeshed/third_party/2/werkzeug/wrappers.pyi       |  14 +-
 typeshed/third_party/2/werkzeug/wsgi.pyi           |   4 -
 typeshed/third_party/2and3/Crypto/Cipher/AES.pyi   |   4 -
 typeshed/third_party/2and3/Crypto/Cipher/ARC2.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/Cipher/ARC4.pyi  |   4 -
 .../third_party/2and3/Crypto/Cipher/Blowfish.pyi   |   4 -
 typeshed/third_party/2and3/Crypto/Cipher/CAST.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/Cipher/DES.pyi   |   4 -
 typeshed/third_party/2and3/Crypto/Cipher/DES3.pyi  |   4 -
 .../third_party/2and3/Crypto/Cipher/PKCS1_OAEP.pyi |   4 -
 .../third_party/2and3/Crypto/Cipher/PKCS1_v1_5.pyi |   4 -
 typeshed/third_party/2and3/Crypto/Cipher/XOR.pyi   |   4 -
 .../third_party/2and3/Crypto/Cipher/__init__.pyi   |   4 -
 .../third_party/2and3/Crypto/Cipher/blockalgo.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/Hash/HMAC.pyi    |   4 -
 typeshed/third_party/2and3/Crypto/Hash/MD2.pyi     |   4 -
 typeshed/third_party/2and3/Crypto/Hash/MD4.pyi     |   4 -
 typeshed/third_party/2and3/Crypto/Hash/MD5.pyi     |   4 -
 typeshed/third_party/2and3/Crypto/Hash/RIPEMD.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/Hash/SHA.pyi     |   4 -
 typeshed/third_party/2and3/Crypto/Hash/SHA224.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/Hash/SHA256.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/Hash/SHA384.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/Hash/SHA512.pyi  |   4 -
 .../third_party/2and3/Crypto/Hash/__init__.pyi     |   4 -
 .../third_party/2and3/Crypto/Hash/hashalgo.pyi     |   4 -
 .../2and3/Crypto/Protocol/AllOrNothing.pyi         |   4 -
 .../third_party/2and3/Crypto/Protocol/Chaffing.pyi |   4 -
 typeshed/third_party/2and3/Crypto/Protocol/KDF.pyi |   4 -
 .../third_party/2and3/Crypto/Protocol/__init__.pyi |   4 -
 .../third_party/2and3/Crypto/PublicKey/DSA.pyi     |   4 -
 .../third_party/2and3/Crypto/PublicKey/ElGamal.pyi |   4 -
 .../third_party/2and3/Crypto/PublicKey/RSA.pyi     |   4 -
 .../2and3/Crypto/PublicKey/__init__.pyi            |   4 -
 .../third_party/2and3/Crypto/PublicKey/pubkey.pyi  |   4 -
 .../Crypto/Random/Fortuna/FortunaAccumulator.pyi   |   4 -
 .../Crypto/Random/Fortuna/FortunaGenerator.pyi     |   4 -
 .../2and3/Crypto/Random/Fortuna/SHAd256.pyi        |   4 -
 .../2and3/Crypto/Random/Fortuna/__init__.pyi       |   3 -
 .../2and3/Crypto/Random/OSRNG/__init__.pyi         |   4 -
 .../2and3/Crypto/Random/OSRNG/fallback.pyi         |   4 -
 .../2and3/Crypto/Random/OSRNG/posix.pyi            |   4 -
 .../2and3/Crypto/Random/OSRNG/rng_base.pyi         |   4 -
 .../third_party/2and3/Crypto/Random/__init__.pyi   |   4 -
 .../third_party/2and3/Crypto/Random/random.pyi     |   4 -
 .../2and3/Crypto/Signature/PKCS1_PSS.pyi           |   4 -
 .../2and3/Crypto/Signature/PKCS1_v1_5.pyi          |   5 -
 .../2and3/Crypto/Signature/__init__.pyi            |   4 -
 typeshed/third_party/2and3/Crypto/Util/Counter.pyi |   4 -
 typeshed/third_party/2and3/Crypto/Util/RFC1751.pyi |   4 -
 .../third_party/2and3/Crypto/Util/__init__.pyi     |   4 -
 typeshed/third_party/2and3/Crypto/Util/asn1.pyi    |   4 -
 typeshed/third_party/2and3/Crypto/Util/number.pyi  |   4 -
 .../third_party/2and3/Crypto/Util/randpool.pyi     |   4 -
 typeshed/third_party/2and3/Crypto/Util/strxor.pyi  |   4 -
 typeshed/third_party/2and3/Crypto/__init__.pyi     |   4 -
 typeshed/third_party/2and3/Crypto/pct_warnings.pyi |   4 -
 .../third_party/2and3/atomicwrites/__init__.pyi    |  12 +-
 typeshed/third_party/2and3/backports_abc.pyi       |   4 -
 typeshed/third_party/2and3/boto/__init__.pyi       |   4 -
 typeshed/third_party/2and3/boto/auth.pyi           |   4 -
 typeshed/third_party/2and3/boto/auth_handler.pyi   |   4 -
 typeshed/third_party/2and3/boto/compat.pyi         |   4 -
 typeshed/third_party/2and3/boto/connection.pyi     |   4 -
 typeshed/third_party/2and3/boto/ec2/__init__.pyi   |   4 -
 typeshed/third_party/2and3/boto/elb/__init__.pyi   |   4 -
 typeshed/third_party/2and3/boto/exception.pyi      |   4 -
 typeshed/third_party/2and3/boto/kms/__init__.pyi   |   4 -
 typeshed/third_party/2and3/boto/kms/exceptions.pyi |   4 -
 typeshed/third_party/2and3/boto/kms/layer1.pyi     |   4 -
 typeshed/third_party/2and3/boto/plugin.pyi         |   4 -
 typeshed/third_party/2and3/boto/regioninfo.pyi     |   4 -
 typeshed/third_party/2and3/boto/s3/__init__.pyi    |   6 +-
 typeshed/third_party/2and3/boto/s3/acl.pyi         |   4 -
 typeshed/third_party/2and3/boto/s3/bucket.pyi      |   4 -
 .../2and3/boto/s3/bucketlistresultset.pyi          |   4 -
 .../third_party/2and3/boto/s3/bucketlogging.pyi    |   4 -
 typeshed/third_party/2and3/boto/s3/connection.pyi  |   4 -
 typeshed/third_party/2and3/boto/s3/cors.pyi        |   4 -
 .../third_party/2and3/boto/s3/deletemarker.pyi     |   4 -
 typeshed/third_party/2and3/boto/s3/key.pyi         |   4 -
 typeshed/third_party/2and3/boto/s3/keyfile.pyi     |   4 -
 typeshed/third_party/2and3/boto/s3/lifecycle.pyi   |   4 -
 typeshed/third_party/2and3/boto/s3/multidelete.pyi |   4 -
 typeshed/third_party/2and3/boto/s3/multipart.pyi   |   4 -
 typeshed/third_party/2and3/boto/s3/prefix.pyi      |   4 -
 typeshed/third_party/2and3/boto/s3/tagging.pyi     |   4 -
 typeshed/third_party/2and3/boto/s3/user.pyi        |   4 -
 typeshed/third_party/2and3/boto/s3/website.pyi     |   4 -
 .../third_party/{3.6 => 2and3}/click/__init__.pyi  |   0
 typeshed/third_party/{3.6 => 2and3}/click/core.pyi |  92 +--
 .../{3.6 => 2and3}/click/decorators.pyi            | 128 ++--
 .../{3.6 => 2and3}/click/exceptions.pyi            |  32 +-
 .../{3.6 => 2and3}/click/formatting.pyi            |   4 +-
 .../third_party/{3.6 => 2and3}/click/globals.pyi   |   2 +-
 .../third_party/{3.6 => 2and3}/click/parser.pyi    |  18 +-
 .../third_party/{3.6 => 2and3}/click/termui.pyi    |  62 +-
 .../third_party/{3.6 => 2and3}/click/types.pyi     |  56 +-
 .../third_party/{3.6 => 2and3}/click/utils.pyi     |  12 +-
 typeshed/third_party/2and3/jinja2/__init__.pyi     |   4 -
 typeshed/third_party/2and3/jinja2/_compat.pyi      |   4 -
 typeshed/third_party/2and3/jinja2/_stringdefs.pyi  |   4 -
 typeshed/third_party/2and3/jinja2/bccache.pyi      |   4 -
 typeshed/third_party/2and3/jinja2/compiler.pyi     |   4 -
 typeshed/third_party/2and3/jinja2/constants.pyi    |   4 -
 typeshed/third_party/2and3/jinja2/debug.pyi        |   4 -
 typeshed/third_party/2and3/jinja2/defaults.pyi     |   4 -
 typeshed/third_party/2and3/jinja2/environment.pyi  |   4 -
 typeshed/third_party/2and3/jinja2/exceptions.pyi   |   4 -
 typeshed/third_party/2and3/jinja2/ext.pyi          |   4 -
 typeshed/third_party/2and3/jinja2/filters.pyi      |   4 -
 typeshed/third_party/2and3/jinja2/lexer.pyi        |   4 -
 typeshed/third_party/2and3/jinja2/loaders.pyi      |   4 -
 typeshed/third_party/2and3/jinja2/meta.pyi         |   4 -
 typeshed/third_party/2and3/jinja2/nodes.pyi        |   4 -
 typeshed/third_party/2and3/jinja2/optimizer.pyi    |   4 -
 typeshed/third_party/2and3/jinja2/parser.pyi       |   4 -
 typeshed/third_party/2and3/jinja2/runtime.pyi      |   4 -
 typeshed/third_party/2and3/jinja2/sandbox.pyi      |   4 -
 typeshed/third_party/2and3/jinja2/tests.pyi        |   4 -
 typeshed/third_party/2and3/jinja2/utils.pyi        |   4 -
 typeshed/third_party/2and3/jinja2/visitor.pyi      |   4 -
 typeshed/third_party/2and3/markupsafe/__init__.pyi |  14 +-
 typeshed/third_party/2and3/markupsafe/_compat.pyi  |   4 -
 .../third_party/2and3/markupsafe/_constants.pyi    |   4 -
 typeshed/third_party/2and3/markupsafe/_native.pyi  |   4 -
 .../third_party/2and3/markupsafe/_speedups.pyi     |   4 -
 typeshed/third_party/2and3/mypy_extensions.pyi     |   2 +-
 typeshed/third_party/2and3/pymysql/__init__.pyi    |   4 -
 typeshed/third_party/2and3/pymysql/charset.pyi     |   4 -
 typeshed/third_party/2and3/pymysql/connections.pyi |   4 -
 .../third_party/2and3/pymysql/constants/CLIENT.pyi |   4 -
 .../2and3/pymysql/constants/COMMAND.pyi            |   4 -
 .../third_party/2and3/pymysql/constants/ER.pyi     |   4 -
 .../2and3/pymysql/constants/FIELD_TYPE.pyi         |   4 -
 .../third_party/2and3/pymysql/constants/FLAG.pyi   |   4 -
 .../2and3/pymysql/constants/SERVER_STATUS.pyi      |   4 -
 .../2and3/pymysql/constants/__init__.pyi           |   3 -
 typeshed/third_party/2and3/pymysql/converters.pyi  |   4 -
 typeshed/third_party/2and3/pymysql/cursors.pyi     |   6 +-
 typeshed/third_party/2and3/pymysql/err.pyi         |   4 -
 typeshed/third_party/2and3/pymysql/times.pyi       |   4 -
 typeshed/third_party/2and3/pymysql/util.pyi        |   4 -
 typeshed/third_party/2and3/pynamodb/__init__.pyi   |   1 +
 typeshed/third_party/2and3/pynamodb/attributes.pyi |  84 +++
 .../2and3/pynamodb/connection/__init__.pyi         |   2 +
 .../third_party/2and3/pynamodb/connection/base.pyi |  55 ++
 .../2and3/pynamodb/connection/table.pyi            |  18 +
 .../third_party/2and3/pynamodb/connection/util.pyi |   3 +
 typeshed/third_party/2and3/pynamodb/constants.pyi  | 166 ++++
 typeshed/third_party/2and3/pynamodb/exceptions.pyi |  40 +
 typeshed/third_party/2and3/pynamodb/indexes.pyi    |  30 +
 typeshed/third_party/2and3/pynamodb/models.pyi     |  85 +++
 typeshed/third_party/2and3/pynamodb/settings.pyi   |   8 +
 typeshed/third_party/2and3/pynamodb/throttle.pyi   |  19 +
 typeshed/third_party/2and3/pynamodb/types.pyi      |   5 +
 typeshed/third_party/2and3/pytz/__init__.pyi       |   4 +-
 typeshed/third_party/2and3/requests/api.pyi        |   6 +-
 .../2and3/requests/packages/__init__.pyi           |   4 -
 .../2and3/requests/packages/urllib3/__init__.pyi   |   4 -
 .../requests/packages/urllib3/_collections.pyi     |   4 -
 .../requests/packages/urllib3/connectionpool.pyi   |   4 -
 .../requests/packages/urllib3/contrib/__init__.pyi |   3 -
 .../2and3/requests/packages/urllib3/exceptions.pyi |   4 -
 .../2and3/requests/packages/urllib3/filepost.pyi   |   4 -
 .../packages/urllib3/packages/__init__.pyi         |   3 -
 .../packages/ssl_match_hostname/__init__.pyi       |   4 -
 .../ssl_match_hostname/_implementation.pyi         |   4 -
 .../requests/packages/urllib3/poolmanager.pyi      |   4 -
 .../2and3/requests/packages/urllib3/request.pyi    |   4 -
 .../2and3/requests/packages/urllib3/response.pyi   |   4 -
 .../requests/packages/urllib3/util/__init__.pyi    |   4 -
 .../requests/packages/urllib3/util/connection.pyi  |   5 +-
 .../requests/packages/urllib3/util/request.pyi     |   4 -
 .../requests/packages/urllib3/util/response.pyi    |   4 -
 .../2and3/requests/packages/urllib3/util/retry.pyi |   4 -
 .../2and3/requests/packages/urllib3/util/ssl_.pyi  |   4 -
 .../requests/packages/urllib3/util/timeout.pyi     |   4 -
 .../2and3/requests/packages/urllib3/util/url.pyi   |   4 -
 .../third_party/2and3/requests/status_codes.pyi    |   4 -
 typeshed/third_party/2and3/ujson.pyi               |   6 +-
 typeshed/third_party/2and3/yaml/__init__.pyi       |  16 +-
 typeshed/third_party/2and3/yaml/composer.pyi       |   4 -
 typeshed/third_party/2and3/yaml/constructor.pyi    |   6 +-
 typeshed/third_party/2and3/yaml/dumper.pyi         |   4 -
 typeshed/third_party/2and3/yaml/emitter.pyi        |   4 -
 typeshed/third_party/2and3/yaml/error.pyi          |   4 -
 typeshed/third_party/2and3/yaml/events.pyi         |   4 -
 typeshed/third_party/2and3/yaml/loader.pyi         |   4 -
 typeshed/third_party/2and3/yaml/nodes.pyi          |   4 -
 typeshed/third_party/2and3/yaml/parser.pyi         |   4 -
 typeshed/third_party/2and3/yaml/reader.pyi         |   4 -
 typeshed/third_party/2and3/yaml/representer.pyi    |   6 +-
 typeshed/third_party/2and3/yaml/resolver.pyi       |   6 +-
 typeshed/third_party/2and3/yaml/scanner.pyi        |   4 -
 typeshed/third_party/2and3/yaml/serializer.pyi     |   4 -
 typeshed/third_party/2and3/yaml/tokens.pyi         |   4 -
 typeshed/third_party/3/dateutil/tz/__init__.pyi    |   4 -
 typeshed/third_party/3/dateutil/tz/_common.pyi     |   4 -
 typeshed/third_party/3/dateutil/tz/tz.pyi          |   4 -
 typeshed/third_party/3/enum.pyi                    |  14 +-
 typeshed/third_party/3/itsdangerous.pyi            |   4 -
 typeshed/third_party/3/jwt/__init__.pyi            |  41 +
 typeshed/third_party/3/jwt/algorithms.pyi          |   3 +
 typeshed/third_party/3/jwt/contrib/__init__.pyi    |   0
 .../3/jwt/contrib/algorithms/__init__.pyi          |   1 +
 .../3/jwt/contrib/algorithms/py_ecdsa.pyi          |  10 +
 .../3/jwt/contrib/algorithms/pycrypto.pyi          |  10 +
 typeshed/third_party/3/six/__init__.pyi            |   6 +-
 typeshed/third_party/3/typed_ast/ast27.pyi         |   2 +-
 typeshed/third_party/3/werkzeug/__init__.pyi       |   4 -
 typeshed/third_party/3/werkzeug/_compat.pyi        |   4 -
 typeshed/third_party/3/werkzeug/_internal.pyi      |   4 -
 typeshed/third_party/3/werkzeug/_reloader.pyi      |   4 -
 .../third_party/3/werkzeug/contrib/__init__.pyi    |   3 -
 typeshed/third_party/3/werkzeug/contrib/atom.pyi   |   4 -
 typeshed/third_party/3/werkzeug/contrib/cache.pyi  |   4 -
 typeshed/third_party/3/werkzeug/contrib/fixers.pyi |   4 -
 typeshed/third_party/3/werkzeug/contrib/iterio.pyi |   4 -
 .../third_party/3/werkzeug/contrib/jsrouting.pyi   |   4 -
 .../third_party/3/werkzeug/contrib/limiter.pyi     |   4 -
 typeshed/third_party/3/werkzeug/contrib/lint.pyi   |   4 -
 .../third_party/3/werkzeug/contrib/profiler.pyi    |   4 -
 .../3/werkzeug/contrib/securecookie.pyi            |   4 -
 .../third_party/3/werkzeug/contrib/sessions.pyi    |   4 -
 .../third_party/3/werkzeug/contrib/testtools.pyi   |   4 -
 .../third_party/3/werkzeug/contrib/wrappers.pyi    |   4 -
 typeshed/third_party/3/werkzeug/datastructures.pyi |   4 -
 typeshed/third_party/3/werkzeug/debug/__init__.pyi |   4 -
 typeshed/third_party/3/werkzeug/debug/console.pyi  |   4 -
 typeshed/third_party/3/werkzeug/debug/repr.pyi     |   4 -
 typeshed/third_party/3/werkzeug/debug/tbtools.pyi  |   4 -
 typeshed/third_party/3/werkzeug/exceptions.pyi     |   4 -
 typeshed/third_party/3/werkzeug/filesystem.pyi     |   4 -
 typeshed/third_party/3/werkzeug/formparser.pyi     |   4 -
 typeshed/third_party/3/werkzeug/http.pyi           |   4 -
 typeshed/third_party/3/werkzeug/local.pyi          |   4 -
 typeshed/third_party/3/werkzeug/posixemulation.pyi |   4 -
 typeshed/third_party/3/werkzeug/routing.pyi        |   4 -
 typeshed/third_party/3/werkzeug/script.pyi         |   4 -
 typeshed/third_party/3/werkzeug/security.pyi       |   4 -
 typeshed/third_party/3/werkzeug/serving.pyi        |   4 -
 typeshed/third_party/3/werkzeug/test.pyi           |   4 -
 typeshed/third_party/3/werkzeug/testapp.pyi        |   4 -
 typeshed/third_party/3/werkzeug/urls.pyi           |   4 -
 typeshed/third_party/3/werkzeug/useragents.pyi     |   4 -
 typeshed/third_party/3/werkzeug/utils.pyi          |   4 -
 typeshed/third_party/3/werkzeug/wrappers.pyi       |  13 +-
 typeshed/third_party/3/werkzeug/wsgi.pyi           |   4 -
 xml/mypy-html.css                                  |   2 +-
 xml/mypy.xsd                                       |   2 +
 595 files changed, 7380 insertions(+), 5258 deletions(-)

diff --git a/PKG-INFO b/PKG-INFO
index 135e4bd..b194318 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: mypy
-Version: 0.511
+Version: 0.520
 Summary: Optional static typing for Python
 Home-page: http://www.mypy-lang.org/
 Author: Jukka Lehtosalo
diff --git a/mypy.egg-info/PKG-INFO b/mypy.egg-info/PKG-INFO
index 135e4bd..b194318 100644
--- a/mypy.egg-info/PKG-INFO
+++ b/mypy.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: mypy
-Version: 0.511
+Version: 0.520
 Summary: Optional static typing for Python
 Home-page: http://www.mypy-lang.org/
 Author: Jukka Lehtosalo
diff --git a/mypy.egg-info/SOURCES.txt b/mypy.egg-info/SOURCES.txt
index 5e48494..de025b6 100644
--- a/mypy.egg-info/SOURCES.txt
+++ b/mypy.egg-info/SOURCES.txt
@@ -33,6 +33,7 @@ mypy/moduleinfo.py
 mypy/nodes.py
 mypy/options.py
 mypy/parse.py
+mypy/plugin.py
 mypy/report.py
 mypy/sametypes.py
 mypy/semanal.py
@@ -58,6 +59,7 @@ mypy/waiter.py
 mypy.egg-info/PKG-INFO
 mypy.egg-info/SOURCES.txt
 mypy.egg-info/dependency_links.txt
+mypy.egg-info/entry_points.txt
 mypy.egg-info/requires.txt
 mypy.egg-info/top_level.txt
 scripts/dumpmodule.py
@@ -92,9 +94,8 @@ typeshed/stdlib/2/_socket.pyi
 typeshed/stdlib/2/_sre.pyi
 typeshed/stdlib/2/_struct.pyi
 typeshed/stdlib/2/_symtable.pyi
+typeshed/stdlib/2/_threading_local.pyi
 typeshed/stdlib/2/_warnings.pyi
-typeshed/stdlib/2/_weakref.pyi
-typeshed/stdlib/2/_weakrefset.pyi
 typeshed/stdlib/2/abc.pyi
 typeshed/stdlib/2/array.pyi
 typeshed/stdlib/2/ast.pyi
@@ -102,19 +103,15 @@ typeshed/stdlib/2/atexit.pyi
 typeshed/stdlib/2/builtins.pyi
 typeshed/stdlib/2/cPickle.pyi
 typeshed/stdlib/2/cStringIO.pyi
-typeshed/stdlib/2/calendar.pyi
 typeshed/stdlib/2/collections.pyi
 typeshed/stdlib/2/commands.pyi
 typeshed/stdlib/2/compileall.pyi
 typeshed/stdlib/2/cookielib.pyi
-typeshed/stdlib/2/csv.pyi
 typeshed/stdlib/2/datetime.pyi
 typeshed/stdlib/2/decimal.pyi
-typeshed/stdlib/2/difflib.pyi
-typeshed/stdlib/2/doctest.pyi
+typeshed/stdlib/2/dummy_thread.pyi
 typeshed/stdlib/2/exceptions.pyi
 typeshed/stdlib/2/fcntl.pyi
-typeshed/stdlib/2/fileinput.pyi
 typeshed/stdlib/2/fnmatch.pyi
 typeshed/stdlib/2/functools.pyi
 typeshed/stdlib/2/future_builtins.pyi
@@ -124,7 +121,6 @@ typeshed/stdlib/2/getopt.pyi
 typeshed/stdlib/2/getpass.pyi
 typeshed/stdlib/2/gettext.pyi
 typeshed/stdlib/2/glob.pyi
-typeshed/stdlib/2/grp.pyi
 typeshed/stdlib/2/gzip.pyi
 typeshed/stdlib/2/hashlib.pyi
 typeshed/stdlib/2/heapq.pyi
@@ -136,7 +132,6 @@ typeshed/stdlib/2/inspect.pyi
 typeshed/stdlib/2/io.pyi
 typeshed/stdlib/2/itertools.pyi
 typeshed/stdlib/2/json.pyi
-typeshed/stdlib/2/linecache.pyi
 typeshed/stdlib/2/macpath.pyi
 typeshed/stdlib/2/markupbase.pyi
 typeshed/stdlib/2/md5.pyi
@@ -144,13 +139,11 @@ typeshed/stdlib/2/mimetools.pyi
 typeshed/stdlib/2/ntpath.pyi
 typeshed/stdlib/2/nturl2path.pyi
 typeshed/stdlib/2/os2emxpath.pyi
-typeshed/stdlib/2/pdb.pyi
-typeshed/stdlib/2/pickle.pyi
 typeshed/stdlib/2/pipes.pyi
 typeshed/stdlib/2/platform.pyi
+typeshed/stdlib/2/popen2.pyi
 typeshed/stdlib/2/posix.pyi
 typeshed/stdlib/2/posixpath.pyi
-typeshed/stdlib/2/pwd.pyi
 typeshed/stdlib/2/pydoc.pyi
 typeshed/stdlib/2/random.pyi
 typeshed/stdlib/2/re.pyi
@@ -159,7 +152,6 @@ typeshed/stdlib/2/resource.pyi
 typeshed/stdlib/2/rfc822.pyi
 typeshed/stdlib/2/robotparser.pyi
 typeshed/stdlib/2/runpy.pyi
-typeshed/stdlib/2/select.pyi
 typeshed/stdlib/2/sets.pyi
 typeshed/stdlib/2/sha.pyi
 typeshed/stdlib/2/shelve.pyi
@@ -167,6 +159,7 @@ typeshed/stdlib/2/shlex.pyi
 typeshed/stdlib/2/shutil.pyi
 typeshed/stdlib/2/signal.pyi
 typeshed/stdlib/2/smtplib.pyi
+typeshed/stdlib/2/spwd.pyi
 typeshed/stdlib/2/ssl.pyi
 typeshed/stdlib/2/stat.pyi
 typeshed/stdlib/2/string.pyi
@@ -178,6 +171,7 @@ typeshed/stdlib/2/tempfile.pyi
 typeshed/stdlib/2/textwrap.pyi
 typeshed/stdlib/2/thread.pyi
 typeshed/stdlib/2/time.pyi
+typeshed/stdlib/2/toaiff.pyi
 typeshed/stdlib/2/tokenize.pyi
 typeshed/stdlib/2/types.pyi
 typeshed/stdlib/2/typing.pyi
@@ -185,7 +179,7 @@ typeshed/stdlib/2/unittest.pyi
 typeshed/stdlib/2/urllib.pyi
 typeshed/stdlib/2/urllib2.pyi
 typeshed/stdlib/2/urlparse.pyi
-typeshed/stdlib/2/weakref.pyi
+typeshed/stdlib/2/user.pyi
 typeshed/stdlib/2/xmlrpclib.pyi
 typeshed/stdlib/2/distutils/__init__.pyi
 typeshed/stdlib/2/distutils/emxccompiler.pyi
@@ -213,8 +207,11 @@ typeshed/stdlib/2/wsgiref/validate.pyi
 typeshed/stdlib/2and3/__future__.pyi
 typeshed/stdlib/2and3/_bisect.pyi
 typeshed/stdlib/2and3/_codecs.pyi
+typeshed/stdlib/2and3/_csv.pyi
 typeshed/stdlib/2and3/_heapq.pyi
 typeshed/stdlib/2and3/_random.pyi
+typeshed/stdlib/2and3/_weakref.pyi
+typeshed/stdlib/2and3/_weakrefset.pyi
 typeshed/stdlib/2and3/argparse.pyi
 typeshed/stdlib/2and3/asynchat.pyi
 typeshed/stdlib/2and3/asyncore.pyi
@@ -224,6 +221,7 @@ typeshed/stdlib/2and3/binhex.pyi
 typeshed/stdlib/2and3/bisect.pyi
 typeshed/stdlib/2and3/bz2.pyi
 typeshed/stdlib/2and3/cProfile.pyi
+typeshed/stdlib/2and3/calendar.pyi
 typeshed/stdlib/2and3/cgi.pyi
 typeshed/stdlib/2and3/cmath.pyi
 typeshed/stdlib/2and3/cmd.pyi
@@ -232,13 +230,19 @@ typeshed/stdlib/2and3/codecs.pyi
 typeshed/stdlib/2and3/colorsys.pyi
 typeshed/stdlib/2and3/contextlib.pyi
 typeshed/stdlib/2and3/copy.pyi
+typeshed/stdlib/2and3/csv.pyi
+typeshed/stdlib/2and3/difflib.pyi
 typeshed/stdlib/2and3/dis.pyi
+typeshed/stdlib/2and3/doctest.pyi
 typeshed/stdlib/2and3/errno.pyi
 typeshed/stdlib/2and3/filecmp.pyi
+typeshed/stdlib/2and3/fileinput.pyi
 typeshed/stdlib/2and3/fractions.pyi
 typeshed/stdlib/2and3/ftplib.pyi
+typeshed/stdlib/2and3/grp.pyi
 typeshed/stdlib/2and3/hmac.pyi
 typeshed/stdlib/2and3/keyword.pyi
+typeshed/stdlib/2and3/linecache.pyi
 typeshed/stdlib/2and3/locale.pyi
 typeshed/stdlib/2and3/marshal.pyi
 typeshed/stdlib/2and3/math.pyi
@@ -248,6 +252,8 @@ typeshed/stdlib/2and3/numbers.pyi
 typeshed/stdlib/2and3/opcode.pyi
 typeshed/stdlib/2and3/operator.pyi
 typeshed/stdlib/2and3/optparse.pyi
+typeshed/stdlib/2and3/pdb.pyi
+typeshed/stdlib/2and3/pickle.pyi
 typeshed/stdlib/2and3/pickletools.pyi
 typeshed/stdlib/2and3/pkgutil.pyi
 typeshed/stdlib/2and3/plistlib.pyi
@@ -256,17 +262,18 @@ typeshed/stdlib/2and3/pprint.pyi
 typeshed/stdlib/2and3/profile.pyi
 typeshed/stdlib/2and3/pstats.pyi
 typeshed/stdlib/2and3/pty.pyi
+typeshed/stdlib/2and3/pwd.pyi
 typeshed/stdlib/2and3/py_compile.pyi
 typeshed/stdlib/2and3/pyclbr.pyi
 typeshed/stdlib/2and3/quopri.pyi
 typeshed/stdlib/2and3/readline.pyi
 typeshed/stdlib/2and3/rlcompleter.pyi
 typeshed/stdlib/2and3/sched.pyi
+typeshed/stdlib/2and3/select.pyi
 typeshed/stdlib/2and3/site.pyi
 typeshed/stdlib/2and3/smtpd.pyi
 typeshed/stdlib/2and3/sndhdr.pyi
 typeshed/stdlib/2and3/socket.pyi
-typeshed/stdlib/2and3/spwd.pyi
 typeshed/stdlib/2and3/stringprep.pyi
 typeshed/stdlib/2and3/struct.pyi
 typeshed/stdlib/2and3/sunau.pyi
@@ -288,6 +295,7 @@ typeshed/stdlib/2and3/uu.pyi
 typeshed/stdlib/2and3/uuid.pyi
 typeshed/stdlib/2and3/warnings.pyi
 typeshed/stdlib/2and3/wave.pyi
+typeshed/stdlib/2and3/weakref.pyi
 typeshed/stdlib/2and3/webbrowser.pyi
 typeshed/stdlib/2and3/xdrlib.pyi
 typeshed/stdlib/2and3/zipfile.pyi
@@ -381,16 +389,11 @@ typeshed/stdlib/3/array.pyi
 typeshed/stdlib/3/ast.pyi
 typeshed/stdlib/3/atexit.pyi
 typeshed/stdlib/3/builtins.pyi
-typeshed/stdlib/3/calendar.pyi
 typeshed/stdlib/3/compileall.pyi
 typeshed/stdlib/3/configparser.pyi
-typeshed/stdlib/3/csv.pyi
 typeshed/stdlib/3/datetime.pyi
 typeshed/stdlib/3/decimal.pyi
-typeshed/stdlib/3/difflib.pyi
-typeshed/stdlib/3/doctest.pyi
 typeshed/stdlib/3/fcntl.pyi
-typeshed/stdlib/3/fileinput.pyi
 typeshed/stdlib/3/fnmatch.pyi
 typeshed/stdlib/3/functools.pyi
 typeshed/stdlib/3/gc.pyi
@@ -398,7 +401,6 @@ typeshed/stdlib/3/getopt.pyi
 typeshed/stdlib/3/getpass.pyi
 typeshed/stdlib/3/gettext.pyi
 typeshed/stdlib/3/glob.pyi
-typeshed/stdlib/3/grp.pyi
 typeshed/stdlib/3/gzip.pyi
 typeshed/stdlib/3/hashlib.pyi
 typeshed/stdlib/3/heapq.pyi
@@ -406,32 +408,28 @@ typeshed/stdlib/3/imp.pyi
 typeshed/stdlib/3/inspect.pyi
 typeshed/stdlib/3/io.pyi
 typeshed/stdlib/3/itertools.pyi
-typeshed/stdlib/3/linecache.pyi
 typeshed/stdlib/3/macpath.pyi
 typeshed/stdlib/3/msvcrt.pyi
 typeshed/stdlib/3/nntplib.pyi
 typeshed/stdlib/3/ntpath.pyi
 typeshed/stdlib/3/nturl2path.pyi
-typeshed/stdlib/3/pdb.pyi
-typeshed/stdlib/3/pickle.pyi
 typeshed/stdlib/3/pipes.pyi
 typeshed/stdlib/3/platform.pyi
 typeshed/stdlib/3/posix.pyi
 typeshed/stdlib/3/posixpath.pyi
-typeshed/stdlib/3/pwd.pyi
 typeshed/stdlib/3/queue.pyi
 typeshed/stdlib/3/random.pyi
 typeshed/stdlib/3/re.pyi
 typeshed/stdlib/3/reprlib.pyi
 typeshed/stdlib/3/resource.pyi
 typeshed/stdlib/3/runpy.pyi
-typeshed/stdlib/3/select.pyi
 typeshed/stdlib/3/shelve.pyi
 typeshed/stdlib/3/shlex.pyi
 typeshed/stdlib/3/shutil.pyi
 typeshed/stdlib/3/signal.pyi
 typeshed/stdlib/3/smtplib.pyi
 typeshed/stdlib/3/socketserver.pyi
+typeshed/stdlib/3/spwd.pyi
 typeshed/stdlib/3/ssl.pyi
 typeshed/stdlib/3/stat.pyi
 typeshed/stdlib/3/string.pyi
@@ -444,7 +442,6 @@ typeshed/stdlib/3/time.pyi
 typeshed/stdlib/3/tokenize.pyi
 typeshed/stdlib/3/types.pyi
 typeshed/stdlib/3/typing.pyi
-typeshed/stdlib/3/weakref.pyi
 typeshed/stdlib/3.3/ipaddress.pyi
 typeshed/stdlib/3.4/_stat.pyi
 typeshed/stdlib/3.4/_tracemalloc.pyi
@@ -515,6 +512,7 @@ typeshed/stdlib/3/json/__init__.pyi
 typeshed/stdlib/3/json/decoder.pyi
 typeshed/stdlib/3/json/encoder.pyi
 typeshed/stdlib/3/multiprocessing/__init__.pyi
+typeshed/stdlib/3/multiprocessing/context.pyi
 typeshed/stdlib/3/multiprocessing/managers.pyi
 typeshed/stdlib/3/multiprocessing/pool.pyi
 typeshed/stdlib/3/multiprocessing/process.pyi
@@ -762,6 +760,16 @@ typeshed/third_party/2and3/boto/s3/tagging.pyi
 typeshed/third_party/2and3/boto/s3/user.pyi
 typeshed/third_party/2and3/boto/s3/website.pyi
 typeshed/third_party/2and3/characteristic/__init__.pyi
+typeshed/third_party/2and3/click/__init__.pyi
+typeshed/third_party/2and3/click/core.pyi
+typeshed/third_party/2and3/click/decorators.pyi
+typeshed/third_party/2and3/click/exceptions.pyi
+typeshed/third_party/2and3/click/formatting.pyi
+typeshed/third_party/2and3/click/globals.pyi
+typeshed/third_party/2and3/click/parser.pyi
+typeshed/third_party/2and3/click/termui.pyi
+typeshed/third_party/2and3/click/types.pyi
+typeshed/third_party/2and3/click/utils.pyi
 typeshed/third_party/2and3/jinja2/__init__.pyi
 typeshed/third_party/2and3/jinja2/_compat.pyi
 typeshed/third_party/2and3/jinja2/_stringdefs.pyi
@@ -805,6 +813,19 @@ typeshed/third_party/2and3/pymysql/constants/FIELD_TYPE.pyi
 typeshed/third_party/2and3/pymysql/constants/FLAG.pyi
 typeshed/third_party/2and3/pymysql/constants/SERVER_STATUS.pyi
 typeshed/third_party/2and3/pymysql/constants/__init__.pyi
+typeshed/third_party/2and3/pynamodb/__init__.pyi
+typeshed/third_party/2and3/pynamodb/attributes.pyi
+typeshed/third_party/2and3/pynamodb/constants.pyi
+typeshed/third_party/2and3/pynamodb/exceptions.pyi
+typeshed/third_party/2and3/pynamodb/indexes.pyi
+typeshed/third_party/2and3/pynamodb/models.pyi
+typeshed/third_party/2and3/pynamodb/settings.pyi
+typeshed/third_party/2and3/pynamodb/throttle.pyi
+typeshed/third_party/2and3/pynamodb/types.pyi
+typeshed/third_party/2and3/pynamodb/connection/__init__.pyi
+typeshed/third_party/2and3/pynamodb/connection/base.pyi
+typeshed/third_party/2and3/pynamodb/connection/table.pyi
+typeshed/third_party/2and3/pynamodb/connection/util.pyi
 typeshed/third_party/2and3/pytz/__init__.pyi
 typeshed/third_party/2and3/pytz/lazy.pyi
 typeshed/third_party/2and3/requests/__init__.pyi
@@ -862,16 +883,6 @@ typeshed/third_party/2and3/yaml/tokens.pyi
 typeshed/third_party/3/enum.pyi
 typeshed/third_party/3/itsdangerous.pyi
 typeshed/third_party/3/pkg_resources.pyi
-typeshed/third_party/3.6/click/__init__.pyi
-typeshed/third_party/3.6/click/core.pyi
-typeshed/third_party/3.6/click/decorators.pyi
-typeshed/third_party/3.6/click/exceptions.pyi
-typeshed/third_party/3.6/click/formatting.pyi
-typeshed/third_party/3.6/click/globals.pyi
-typeshed/third_party/3.6/click/parser.pyi
-typeshed/third_party/3.6/click/termui.pyi
-typeshed/third_party/3.6/click/types.pyi
-typeshed/third_party/3.6/click/utils.pyi
 typeshed/third_party/3/dateutil/__init__.pyi
 typeshed/third_party/3/dateutil/parser.pyi
 typeshed/third_party/3/dateutil/relativedelta.pyi
@@ -886,6 +897,12 @@ typeshed/third_party/3/docutils/parsers/rst/__init__.pyi
 typeshed/third_party/3/docutils/parsers/rst/nodes.pyi
 typeshed/third_party/3/docutils/parsers/rst/roles.pyi
 typeshed/third_party/3/docutils/parsers/rst/states.pyi
+typeshed/third_party/3/jwt/__init__.pyi
+typeshed/third_party/3/jwt/algorithms.pyi
+typeshed/third_party/3/jwt/contrib/__init__.pyi
+typeshed/third_party/3/jwt/contrib/algorithms/__init__.pyi
+typeshed/third_party/3/jwt/contrib/algorithms/py_ecdsa.pyi
+typeshed/third_party/3/jwt/contrib/algorithms/pycrypto.pyi
 typeshed/third_party/3/lxml/__init__.pyi
 typeshed/third_party/3/lxml/etree.pyi
 typeshed/third_party/3/lxml/objectify.pyi
diff --git a/mypy.egg-info/entry_points.txt b/mypy.egg-info/entry_points.txt
new file mode 100644
index 0000000..b385ace
--- /dev/null
+++ b/mypy.egg-info/entry_points.txt
@@ -0,0 +1,4 @@
+[console_scripts]
+mypy = mypy.__main__:console_entry
+stubgen = mypy.stubgen:main
+
diff --git a/mypy.egg-info/requires.txt b/mypy.egg-info/requires.txt
index 8b20c5b..f175af7 100644
--- a/mypy.egg-info/requires.txt
+++ b/mypy.egg-info/requires.txt
@@ -1 +1 @@
-typed-ast >= 1.0.3, < 1.1.0
+typed-ast >= 1.0.4, < 1.1.0
diff --git a/mypy/__main__.py b/mypy/__main__.py
index 0a6f792..625242d 100644
--- a/mypy/__main__.py
+++ b/mypy/__main__.py
@@ -2,4 +2,10 @@
 
 from mypy.main import main
 
-main(None)
+
+def console_entry() -> None:
+    main(None)
+
+
+if __name__ == '__main__':
+    main(None)
diff --git a/mypy/binder.py b/mypy/binder.py
index 3ae2952..2a54859 100644
--- a/mypy/binder.py
+++ b/mypy/binder.py
@@ -1,4 +1,4 @@
-from typing import (Dict, List, Set, Iterator, Union)
+from typing import Dict, List, Set, Iterator, Union, Optional, cast
 from contextlib import contextmanager
 
 from mypy.types import Type, AnyType, PartialType, UnionType, NoneTyp
@@ -31,6 +31,13 @@ class Frame(Dict[Key, Type]):
         self.unreachable = False
 
 
+class DeclarationsFrame(Dict[Key, Optional[Type]]):
+    """Same as above, but allowed to have None values."""
+
+    def __init__(self) -> None:
+        self.unreachable = False
+
+
 class ConditionalTypeBinder:
     """Keep track of conditional types of variables.
 
@@ -68,9 +75,9 @@ class ConditionalTypeBinder:
         # has no corresponding element in this list.
         self.options_on_return = []  # type: List[List[Frame]]
 
-        # Maps expr.literal_hash] to get_declaration(expr)
+        # Maps expr.literal_hash to get_declaration(expr)
         # for every expr stored in the binder
-        self.declarations = Frame()
+        self.declarations = DeclarationsFrame()
         # Set of other keys to invalidate if a key is changed, e.g. x -> {x.a, x[0]}
         # Whenever a new key (e.g. x.a.b) is added, we update this
         self.dependencies = {}  # type: Dict[Key, Set[Key]]
@@ -101,7 +108,7 @@ class ConditionalTypeBinder:
     def _put(self, key: Key, type: Type, index: int=-1) -> None:
         self.frames[index][key] = type
 
-    def _get(self, key: Key, index: int=-1) -> Type:
+    def _get(self, key: Key, index: int=-1) -> Optional[Type]:
         if index < 0:
             index += len(self.frames)
         for i in range(index, -1, -1):
@@ -115,6 +122,7 @@ class ConditionalTypeBinder:
         if not expr.literal:
             return
         key = expr.literal_hash
+        assert key is not None, 'Internal error: binder tried to put non-literal'
         if key not in self.declarations:
             assert isinstance(expr, BindableTypes)
             self.declarations[key] = get_declaration(expr)
@@ -124,7 +132,8 @@ class ConditionalTypeBinder:
     def unreachable(self) -> None:
         self.frames[-1].unreachable = True
 
-    def get(self, expr: Expression) -> Type:
+    def get(self, expr: Expression) -> Optional[Type]:
+        assert expr.literal_hash is not None, 'Internal error: binder tried to get non-literal'
         return self._get(expr.literal_hash)
 
     def is_unreachable(self) -> bool:
@@ -134,6 +143,7 @@ class ConditionalTypeBinder:
 
     def cleanse(self, expr: Expression) -> None:
         """Remove all references to a Node from the binder."""
+        assert expr.literal_hash is not None, 'Internal error: binder tried cleanse non-literal'
         self._cleanse_key(expr.literal_hash)
 
     def _cleanse_key(self, key: Key) -> None:
@@ -163,15 +173,17 @@ class ConditionalTypeBinder:
                 # know anything about key in at least one possible frame.
                 continue
 
+            type = resulting_values[0]
+            assert type is not None
             if isinstance(self.declarations.get(key), AnyType):
-                type = resulting_values[0]
-                if not all(is_same_type(type, t) for t in resulting_values[1:]):
+                # At this point resulting values can't contain None, see continue above
+                if not all(is_same_type(type, cast(Type, t)) for t in resulting_values[1:]):
                     type = AnyType()
             else:
-                type = resulting_values[0]
                 for other in resulting_values[1:]:
+                    assert other is not None
                     type = join_simple(self.declarations[key], type, other)
-            if not is_same_type(type, current_value):
+            if current_value is None or not is_same_type(type, current_value):
                 self._put(key, type)
                 changed = True
 
@@ -249,13 +261,15 @@ class ConditionalTypeBinder:
         It is overly conservative: it invalidates globally, including
         in code paths unreachable from here.
         """
+        assert expr.literal_hash is not None
         for dep in self.dependencies.get(expr.literal_hash, set()):
             self._cleanse_key(dep)
 
-    def most_recent_enclosing_type(self, expr: BindableExpression, type: Type) -> Type:
+    def most_recent_enclosing_type(self, expr: BindableExpression, type: Type) -> Optional[Type]:
         if isinstance(type, AnyType):
             return get_declaration(expr)
         key = expr.literal_hash
+        assert key is not None
         enclosers = ([get_declaration(expr)] +
                      [f[key] for f in self.frames
                       if key in f and is_subtype(type, f[key])])
@@ -342,7 +356,7 @@ class ConditionalTypeBinder:
         self.pop_frame(True, 0)
 
 
-def get_declaration(expr: BindableExpression) -> Type:
+def get_declaration(expr: BindableExpression) -> Optional[Type]:
     if isinstance(expr, RefExpr) and isinstance(expr.node, Var):
         type = expr.node.type
         if not isinstance(type, PartialType):
diff --git a/mypy/build.py b/mypy/build.py
index f803929..18811bf 100644
--- a/mypy/build.py
+++ b/mypy/build.py
@@ -16,12 +16,13 @@ import contextlib
 import hashlib
 import json
 import os.path
+import re
 import sys
 import time
 from os.path import dirname, basename
 
 from typing import (AbstractSet, Dict, Iterable, Iterator, List,
-                    NamedTuple, Optional, Set, Tuple, Union)
+                    NamedTuple, Optional, Set, Tuple, Union, Callable)
 # Can't use TYPE_CHECKING because it's not in the Python 3.5.1 stdlib
 MYPY = False
 if MYPY:
@@ -42,6 +43,7 @@ from mypy.parse import parse
 from mypy.stats import dump_type_stats
 from mypy.types import Type
 from mypy.version import __version__
+from mypy.plugin import Plugin, DefaultPlugin, ChainedPlugin
 
 
 # We need to know the location of this file to load data, but
@@ -54,6 +56,10 @@ PYTHON_EXTENSIONS = ['.pyi', '.py']
 Graph = Dict[str, 'State']
 
 
+def getmtime(name: str) -> int:
+    return int(os.path.getmtime(name))
+
+
 # TODO: Get rid of BuildResult.  We might as well return a BuildManager.
 class BuildResult:
     """The result of a successful build.
@@ -170,8 +176,9 @@ def build(sources: List[BuildSource],
         lib_path.insert(0, alt_lib_path)
 
     reports = Reports(data_dir, options.report_dirs)
-
     source_set = BuildSourceSet(sources)
+    errors = Errors(options.show_error_context, options.show_column_numbers)
+    plugin = load_plugins(options, errors)
 
     # Construct a build manager object to hold state during the build.
     #
@@ -182,7 +189,8 @@ def build(sources: List[BuildSource],
                            reports=reports,
                            options=options,
                            version_id=__version__,
-                           )
+                           plugin=plugin,
+                           errors=errors)
 
     try:
         graph = dispatch(sources, manager)
@@ -292,14 +300,15 @@ def default_lib_path(data_dir: str,
 CacheMeta = NamedTuple('CacheMeta',
                        [('id', str),
                         ('path', str),
-                        ('mtime', float),
+                        ('mtime', int),
                         ('size', int),
+                        ('hash', str),
                         ('dependencies', List[str]),  # names of imported modules
-                        ('data_mtime', float),  # mtime of data_json
+                        ('data_mtime', int),  # mtime of data_json
                         ('data_json', str),  # path of <id>.data.json
                         ('suppressed', List[str]),  # dependencies that weren't imported
                         ('child_modules', List[str]),  # all submodules of the given module
-                        ('options', Optional[Dict[str, bool]]),  # build options
+                        ('options', Optional[Dict[str, object]]),  # build options
                         ('dep_prios', List[int]),
                         ('interface_hash', str),  # hash representing the public interface
                         ('version_id', str),  # mypy version for cache invalidation
@@ -332,6 +341,96 @@ def import_priority(imp: ImportBase, toplevel_priority: int) -> int:
     return toplevel_priority
 
 
+def load_plugins(options: Options, errors: Errors) -> Plugin:
+    """Load all configured plugins.
+
+    Return a plugin that encapsulates all plugins chained together. Always
+    at least include the default plugin (it's last in the chain).
+    """
+
+    default_plugin = DefaultPlugin(options)  # type: Plugin
+    if not options.config_file:
+        return default_plugin
+
+    line = find_config_file_line_number(options.config_file, 'mypy', 'plugins')
+    if line == -1:
+        line = 1  # We need to pick some line number that doesn't look too confusing
+
+    def plugin_error(message: str) -> None:
+        errors.report(line, 0, message)
+        errors.raise_error()
+
+    custom_plugins = []  # type: List[Plugin]
+    errors.set_file(options.config_file, None)
+    for plugin_path in options.plugins:
+        # Plugin paths are relative to the config file location.
+        plugin_path = os.path.join(os.path.dirname(options.config_file), plugin_path)
+
+        if not os.path.isfile(plugin_path):
+            plugin_error("Can't find plugin '{}'".format(plugin_path))
+        plugin_dir = os.path.dirname(plugin_path)
+        fnam = os.path.basename(plugin_path)
+        if not fnam.endswith('.py'):
+            plugin_error("Plugin '{}' does not have a .py extension".format(fnam))
+        module_name = fnam[:-3]
+        import importlib
+        sys.path.insert(0, plugin_dir)
+        try:
+            m = importlib.import_module(module_name)
+        except Exception:
+            print('Error importing plugin {}\n'.format(plugin_path))
+            raise  # Propagate to display traceback
+        finally:
+            assert sys.path[0] == plugin_dir
+            del sys.path[0]
+        if not hasattr(m, 'plugin'):
+            plugin_error('Plugin \'{}\' does not define entry point function "plugin"'.format(
+                plugin_path))
+        try:
+            plugin_type = getattr(m, 'plugin')(__version__)
+        except Exception:
+            print('Error calling the plugin(version) entry point of {}\n'.format(plugin_path))
+            raise  # Propagate to display traceback
+        if not isinstance(plugin_type, type):
+            plugin_error(
+                'Type object expected as the return value of "plugin"; got {!r} (in {})'.format(
+                    plugin_type, plugin_path))
+        if not issubclass(plugin_type, Plugin):
+            plugin_error(
+                'Return value of "plugin" must be a subclass of "mypy.plugin.Plugin" '
+                '(in {})'.format(plugin_path))
+        try:
+            custom_plugins.append(plugin_type(options))
+        except Exception:
+            print('Error constructing plugin instance of {}\n'.format(plugin_type.__name__))
+            raise  # Propagate to display traceback
+    # Custom plugins take precedence over the default plugin.
+    return ChainedPlugin(options, custom_plugins + [default_plugin])
+
+
+def find_config_file_line_number(path: str, section: str, setting_name: str) -> int:
+    """Return the approximate location of setting_name within mypy config file.
+
+    Return -1 if can't determine the line unambiguously.
+    """
+    in_desired_section = False
+    try:
+        results = []
+        with open(path) as f:
+            for i, line in enumerate(f):
+                line = line.strip()
+                if line.startswith('[') and line.endswith(']'):
+                    current_section = line[1:-1].strip()
+                    in_desired_section = (current_section == section)
+                elif in_desired_section and re.match(r'{}\s*='.format(setting_name), line):
+                    results.append(i + 1)
+        if len(results) == 1:
+            return results[0]
+    except OSError:
+        pass
+    return -1
+
+
 # TODO: Get rid of all_types.  It's not used except for one log message.
 #       Maybe we could instead publish a map from module ID to its type_map.
 class BuildManager:
@@ -350,11 +449,12 @@ class BuildManager:
       semantic_analyzer_pass3:
                        Semantic analyzer, pass 3
       all_types:       Map {Expression: Type} collected from all modules
-      errors:          Used for reporting all errors
       options:         Build options
       missing_modules: Set of modules that could not be imported encountered so far
       stale_modules:   Set of modules that needed to be rechecked
       version_id:      The current mypy version (based on commit id when possible)
+      plugin:          Active mypy plugin(s)
+      errors:          Used for reporting all errors
     """
 
     def __init__(self, data_dir: str,
@@ -363,10 +463,12 @@ class BuildManager:
                  source_set: BuildSourceSet,
                  reports: Reports,
                  options: Options,
-                 version_id: str) -> None:
+                 version_id: str,
+                 plugin: Plugin,
+                 errors: Errors) -> None:
         self.start_time = time.time()
         self.data_dir = data_dir
-        self.errors = Errors(options.show_error_context, options.show_column_numbers)
+        self.errors = errors
         self.errors.set_ignore_prefix(ignore_prefix)
         self.lib_path = tuple(lib_path)
         self.source_set = source_set
@@ -375,14 +477,16 @@ class BuildManager:
         self.version_id = version_id
         self.modules = {}  # type: Dict[str, MypyFile]
         self.missing_modules = set()  # type: Set[str]
+        self.plugin = plugin
         self.semantic_analyzer = SemanticAnalyzer(self.modules, self.missing_modules,
-                                                  lib_path, self.errors)
+                                                  lib_path, self.errors, self.plugin)
         self.modules = self.semantic_analyzer.modules
         self.semantic_analyzer_pass3 = ThirdPass(self.modules, self.errors)
         self.all_types = {}  # type: Dict[Expression, Type]
         self.indirection_detector = TypeIndirectionVisitor()
         self.stale_modules = set()  # type: Set[str]
         self.rechecked_modules = set()  # type: Set[str]
+        self.plugin = plugin
 
     def maybe_swap_for_shadow_path(self, path: str) -> str:
         if (self.options.shadow_file and
@@ -684,8 +788,12 @@ def verify_module(id: str, path: str) -> bool:
     return True
 
 
-def read_with_python_encoding(path: str, pyversion: Tuple[int, int]) -> str:
-    """Read the Python file with while obeying PEP-263 encoding detection"""
+def read_with_python_encoding(path: str, pyversion: Tuple[int, int]) -> Tuple[str, str]:
+    """Read the Python file with while obeying PEP-263 encoding detection.
+
+    Returns:
+      A tuple: the source as a string, and the hash calculated from the binary representation.
+    """
     source_bytearray = bytearray()
     encoding = 'utf8' if pyversion[0] >= 3 else 'ascii'
 
@@ -693,6 +801,7 @@ def read_with_python_encoding(path: str, pyversion: Tuple[int, int]) -> str:
         # read first two lines and check if PEP-263 coding is present
         source_bytearray.extend(f.readline())
         source_bytearray.extend(f.readline())
+        m = hashlib.md5(source_bytearray)
 
         # check for BOM UTF-8 encoding and strip it out if present
         if source_bytearray.startswith(b'\xef\xbb\xbf'):
@@ -705,16 +814,17 @@ def read_with_python_encoding(path: str, pyversion: Tuple[int, int]) -> str:
             if _encoding != 'mypy':
                 encoding = _encoding
 
-        source_bytearray.extend(f.read())
+        remainder = f.read()
+        m.update(remainder)
+        source_bytearray.extend(remainder)
         try:
-            source_bytearray.decode(encoding)
+            source_text = source_bytearray.decode(encoding)
         except LookupError as lookuperr:
             raise DecodeError(str(lookuperr))
-        return source_bytearray.decode(encoding)
+        return source_text, m.hexdigest()
 
 
-def get_cache_names(id: str, path: str, cache_dir: str,
-                    pyversion: Tuple[int, int]) -> Tuple[str, str]:
+def get_cache_names(id: str, path: str, manager: BuildManager) -> Tuple[str, str]:
     """Return the file names for the cache files.
 
     Args:
@@ -727,6 +837,8 @@ def get_cache_names(id: str, path: str, cache_dir: str,
       A tuple with the file names to be used for the meta JSON and the
       data JSON, respectively.
     """
+    cache_dir = manager.options.cache_dir
+    pyversion = manager.options.python_version
     prefix = os.path.join(cache_dir, '%d.%d' % pyversion, *id.split('.'))
     is_package = os.path.basename(path).startswith('__init__.py')
     if is_package:
@@ -747,8 +859,7 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
       valid; otherwise None.
     """
     # TODO: May need to take more build options into account
-    meta_json, data_json = get_cache_names(
-        id, path, manager.options.cache_dir, manager.options.python_version)
+    meta_json, data_json = get_cache_names(id, path, manager)
     manager.trace('Looking for {} {}'.format(id, data_json))
     if not os.path.exists(meta_json):
         manager.trace('Could not load cache for {}: could not find {}'.format(id, meta_json))
@@ -760,14 +871,14 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
     if not isinstance(meta, dict):
         manager.trace('Could not load cache for {}: meta cache is not a dict'.format(id))
         return None
-    path = os.path.abspath(path)
     m = CacheMeta(
         meta.get('id'),
         meta.get('path'),
-        meta.get('mtime'),
+        int(meta['mtime']) if 'mtime' in meta else None,
         meta.get('size'),
+        meta.get('hash'),
         meta.get('dependencies', []),
-        meta.get('data_mtime'),
+        int(meta['data_mtime']) if 'data_mtime' in meta else None,
         data_json,
         meta.get('suppressed', []),
         meta.get('child_modules', []),
@@ -776,14 +887,15 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
         meta.get('interface_hash', ''),
         meta.get('version_id'),
     )
-    if (m.id != id or m.path != path or
+    # Don't check for path match, that is dealt with in validate_meta().
+    if (m.id != id or
             m.mtime is None or m.size is None or
             m.dependencies is None or m.data_mtime is None):
         manager.trace('Metadata abandoned for {}: attributes are missing'.format(id))
         return None
 
     # Ignore cache if generated by an older mypy version.
-    if (m.version_id != manager.version_id
+    if ((m.version_id != manager.version_id and not manager.options.skip_version_check)
             or m.options is None
             or len(m.dependencies) != len(m.dep_prios)):
         manager.trace('Metadata abandoned for {}: new attributes are missing'.format(id))
@@ -795,6 +907,9 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
     if manager.options.quick_and_dirty:
         # In quick_and_dirty mode allow non-quick_and_dirty cache files.
         cached_options['quick_and_dirty'] = True
+    if not cached_options.get('platform') and manager.options.skip_version_check:
+        # Older versions didn't write platform.
+        cached_options['platform'] = manager.options.platform
     if cached_options != current_options:
         manager.trace('Metadata abandoned for {}: options differ'.format(id))
         return None
@@ -802,28 +917,73 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
     return m
 
 
-def is_meta_fresh(meta: Optional[CacheMeta], id: str, path: str, manager: BuildManager) -> bool:
-    if meta is None:
+def random_string() -> str:
+    return binascii.hexlify(os.urandom(8)).decode('ascii')
+
+
+def atomic_write(filename: str, *lines: str) -> bool:
+    tmp_filename = filename + '.' + random_string()
+    try:
+        with open(tmp_filename, 'w') as f:
+            for line in lines:
+                f.write(line)
+        os.replace(tmp_filename, filename)
+    except os.error as err:
         return False
+    return True
+
+
+def validate_meta(meta: Optional[CacheMeta], id: str, path: str,
+                  manager: BuildManager) -> Optional[CacheMeta]:
+    '''Checks whether the cached AST of this module can be used.
+
+    Return:
+      None, if the cached AST is unusable.
+      Original meta, if mtime/size matched.
+      Meta with mtime updated to match source file, if hash/size matched but mtime/path didn't.
+    '''
+    # This requires two steps. The first one is obvious: we check that the module source file
+    # contents is the same as it was when the cache data file was created. The second one is not
+    # too obvious: we check that the cache data file mtime has not changed; it is needed because
+    # we use cache data file mtime to propagate information about changes in the dependencies.
+
+    if meta is None:
+        return None
 
     # TODO: Share stat() outcome with find_module()
+    path = os.path.abspath(path)
     st = manager.get_stat(path)  # TODO: Errors
-    if st.st_mtime != meta.mtime or st.st_size != meta.size:
-        manager.log('Metadata abandoned for {}: file {} is modified'.format(id, path))
-        return False
+    if st.st_size != meta.size:
+        manager.log('Metadata abandoned for {}: file {} has different size'.format(id, path))
+        return None
 
-    # It's a match on (id, path, mtime, size).
+    if int(st.st_mtime) != meta.mtime or path != meta.path:
+        with open(path, 'rb') as f:
+            source_hash = hashlib.md5(f.read()).hexdigest()
+        if source_hash != meta.hash:
+            manager.log('Metadata abandoned for {}: file {} has different hash'.format(id, path))
+            return None
+        else:
+            manager.log('Metadata ok for {}: file {} (match on path, size, hash)'.format(id, path))
+            # Optimization: update mtime and path (otherwise, this mismatch will reappear).
+            meta = meta._replace(mtime=int(st.st_mtime), path=path)
+            if manager.options.debug_cache:
+                meta_str = json.dumps(meta, indent=2, sort_keys=True)
+            else:
+                meta_str = json.dumps(meta)
+            meta_json, _ = get_cache_names(id, path, manager)
+            manager.log('Updating mtime for {}: file {}, meta {}, mtime {}'
+                        .format(id, path, meta_json, meta.mtime))
+            atomic_write(meta_json, meta_str)  # Ignore errors, since this is just an optimization.
+
+    # It's a match on (id, path, mtime/hash, size).
     # Check data_json; assume if its mtime matches it's good.
     # TODO: stat() errors
-    if os.path.getmtime(meta.data_json) != meta.data_mtime:
+    if getmtime(meta.data_json) != meta.data_mtime:
         manager.log('Metadata abandoned for {}: data cache is modified'.format(id))
-        return False
+        return None
     manager.log('Found {} {} (metadata is fresh)'.format(id, meta.data_json))
-    return True
-
-
-def random_string() -> str:
-    return binascii.hexlify(os.urandom(8)).decode('ascii')
+    return meta
 
 
 def compute_hash(text: str) -> str:
@@ -836,7 +996,7 @@ def compute_hash(text: str) -> str:
 def write_cache(id: str, path: str, tree: MypyFile,
                 dependencies: List[str], suppressed: List[str],
                 child_modules: List[str], dep_prios: List[int],
-                old_interface_hash: str, manager: BuildManager) -> str:
+                old_interface_hash: str, source_hash: str, manager: BuildManager) -> str:
     """Write cache files for a module.
 
     Note that this mypy's behavior is still correct when any given
@@ -858,19 +1018,13 @@ def write_cache(id: str, path: str, tree: MypyFile,
     """
     # Obtain file paths
     path = os.path.abspath(path)
-    meta_json, data_json = get_cache_names(
-        id, path, manager.options.cache_dir, manager.options.python_version)
+    meta_json, data_json = get_cache_names(id, path, manager)
     manager.log('Writing {} {} {} {}'.format(id, path, meta_json, data_json))
 
     # Make sure directory for cache files exists
     parent = os.path.dirname(data_json)
     assert os.path.dirname(meta_json) == parent
 
-    # Construct temp file names
-    nonce = '.' + random_string()
-    data_json_tmp = data_json + nonce
-    meta_json_tmp = meta_json + nonce
-
     # Serialize data and analyze interface
     data = tree.serialize()
     if manager.options.debug_cache:
@@ -899,20 +1053,14 @@ def write_cache(id: str, path: str, tree: MypyFile,
     if old_interface_hash == interface_hash:
         # If the interface is unchanged, the cached data is guaranteed
         # to be equivalent, and we only need to update the metadata.
-        data_mtime = os.path.getmtime(data_json)
+        data_mtime = getmtime(data_json)
         manager.trace("Interface for {} is unchanged".format(id))
     else:
         manager.trace("Interface for {} has changed".format(id))
-        try:
-            with open(data_json_tmp, 'w') as f:
-                f.write(data_str)
-                f.write('\n')
-            os.replace(data_json_tmp, data_json)
-            data_mtime = os.path.getmtime(data_json)
-        except os.error as err:
+        if not atomic_write(data_json, data_str, '\n'):
             # Most likely the error is the replace() call
             # (see https://github.com/python/mypy/issues/3215).
-            manager.log("Error writing data JSON file {}".format(data_json_tmp))
+            manager.log("Error writing data JSON file {}".format(data_json))
             # Let's continue without writing the meta file.  Analysis:
             # If the replace failed, we've changed nothing except left
             # behind an extraneous temporary file; if the replace
@@ -922,14 +1070,17 @@ def write_cache(id: str, path: str, tree: MypyFile,
             # Both have the effect of slowing down the next run a
             # little bit due to an out-of-date cache file.
             return interface_hash
+        data_mtime = getmtime(data_json)
 
-    mtime = st.st_mtime
+    mtime = int(st.st_mtime)
     size = st.st_size
     options = manager.options.clone_for_module(id)
+    assert source_hash is not None
     meta = {'id': id,
             'path': path,
             'mtime': mtime,
             'size': size,
+            'hash': source_hash,
             'data_mtime': data_mtime,
             'dependencies': dependencies,
             'suppressed': suppressed,
@@ -941,18 +1092,15 @@ def write_cache(id: str, path: str, tree: MypyFile,
             }
 
     # Write meta cache file
-    try:
-        with open(meta_json_tmp, 'w') as f:
-            if manager.options.debug_cache:
-                json.dump(meta, f, indent=2, sort_keys=True)
-            else:
-                json.dump(meta, f)
-        os.replace(meta_json_tmp, meta_json)
-    except os.error as err:
+    if manager.options.debug_cache:
+        meta_str = json.dumps(meta, indent=2, sort_keys=True)
+    else:
+        meta_str = json.dumps(meta)
+    if not atomic_write(meta_json, meta_str):
         # Most likely the error is the replace() call
         # (see https://github.com/python/mypy/issues/3215).
         # The next run will simply find the cache entry out of date.
-        manager.log("Error writing meta JSON file {}".format(meta_json_tmp))
+        manager.log("Error writing meta JSON file {}".format(meta_json))
 
     return interface_hash
 
@@ -1116,6 +1264,7 @@ class State:
     path = None  # type: Optional[str]  # Path to module source
     xpath = None  # type: str  # Path or '<string>'
     source = None  # type: Optional[str]  # Module source code
+    source_hash = None  # type: str  # Hash calculated based on the source code
     meta = None  # type: Optional[CacheMeta]
     data = None  # type: Optional[str]
     tree = None  # type: Optional[MypyFile]
@@ -1243,7 +1392,8 @@ class State:
             if self.meta is not None:
                 self.interface_hash = self.meta.interface_hash
         self.add_ancestors()
-        if is_meta_fresh(self.meta, self.id, self.path, manager):
+        self.meta = validate_meta(self.meta, self.id, self.path, manager)
+        if self.meta:
             # Make copies, since we may modify these and want to
             # compare them to the originals later.
             self.dependencies = list(self.meta.dependencies)
@@ -1255,7 +1405,6 @@ class State:
             self.dep_line_map = {}
         else:
             # Parse the file (and then some) to get the dependencies.
-            self.meta = None
             self.parse_file()
             self.suppressed = []
             self.child_modules = set()
@@ -1369,6 +1518,24 @@ class State:
         fixup_module_pass_two(self.tree, self.manager.modules,
                               self.manager.options.quick_and_dirty)
 
+    def patch_dependency_parents(self) -> None:
+        """
+        In Python, if a and a.b are both modules, running `import a.b` will
+        modify not only the current module's namespace, but a's namespace as
+        well -- see SemanticAnalyzer.add_submodules_to_parent_modules for more
+        details.
+
+        However, this patching process can occur after `a` has been parsed and
+        serialized during increment mode. Consequently, we need to repeat this
+        patch when deserializing a cached file.
+
+        This function should be called only when processing fresh SCCs -- the
+        semantic analyzer will perform this patch for us when processing stale
+        SCCs.
+        """
+        for dep in self.dependencies:
+            self.manager.semantic_analyzer.add_submodules_to_parent_modules(dep, True)
+
     def fix_suppressed_dependencies(self, graph: Graph) -> None:
         """Corrects whether dependencies are considered stale in silent mode.
 
@@ -1421,7 +1588,8 @@ class State:
             if self.path and source is None:
                 try:
                     path = manager.maybe_swap_for_shadow_path(self.path)
-                    source = read_with_python_encoding(path, self.options.python_version)
+                    source, self.source_hash = read_with_python_encoding(
+                        path, self.options.python_version)
                 except IOError as ioerr:
                     raise CompileError([
                         "mypy: can't read file '{}': {}".format(self.path, ioerr.strerror)])
@@ -1491,8 +1659,10 @@ class State:
         self.check_blockers()
 
     def semantic_analysis(self) -> None:
+        patches = []  # type: List[Callable[[], None]]
         with self.wrap_context():
-            self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options)
+            self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
+        self.patches = patches
 
     def semantic_analysis_pass_three(self) -> None:
         with self.wrap_context():
@@ -1500,13 +1670,17 @@ class State:
             if self.options.dump_type_stats:
                 dump_type_stats(self.tree, self.xpath)
 
+    def semantic_analysis_apply_patches(self) -> None:
+        for patch_func in self.patches:
+            patch_func()
+
     def type_check_first_pass(self) -> None:
         manager = self.manager
         if self.options.semantic_analysis_only:
             return
         with self.wrap_context():
             self.type_checker = TypeChecker(manager.errors, manager.modules, self.options,
-                                            self.tree, self.xpath)
+                                            self.tree, self.xpath, manager.plugin)
             self.type_checker.check_first_pass()
 
     def type_check_second_pass(self) -> bool:
@@ -1572,7 +1746,7 @@ class State:
         new_interface_hash = write_cache(
             self.id, self.path, self.tree,
             list(self.dependencies), list(self.suppressed), list(self.child_modules),
-            dep_prios, self.interface_hash,
+            dep_prios, self.interface_hash, self.source_hash,
             self.manager)
         if new_interface_hash == self.interface_hash:
             self.manager.log("Cached module {} has same interface".format(self.id))
@@ -1900,6 +2074,8 @@ def process_fresh_scc(graph: Graph, scc: List[str]) -> None:
         graph[id].fix_cross_refs()
     for id in scc:
         graph[id].calculate_mros()
+    for id in scc:
+        graph[id].patch_dependency_parents()
 
 
 def process_stale_scc(graph: Graph, scc: List[str], manager: BuildManager) -> None:
@@ -1934,6 +2110,8 @@ def process_stale_scc(graph: Graph, scc: List[str], manager: BuildManager) -> No
     for id in fresh:
         graph[id].calculate_mros()
     for id in stale:
+        graph[id].semantic_analysis_apply_patches()
+    for id in stale:
         graph[id].type_check_first_pass()
     more = True
     while more:
diff --git a/mypy/checker.py b/mypy/checker.py
index c65f956..68284c4 100644
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -29,6 +29,7 @@ from mypy.nodes import (
     ARG_POS, MDEF,
     CONTRAVARIANT, COVARIANT)
 from mypy import nodes
+from mypy.typeanal import has_any_from_unimported_type, check_for_explicit_any
 from mypy.types import (
     Type, AnyType, CallableType, FunctionLike, Overloaded, TupleType, TypedDictType,
     Instance, NoneTyp, strip_type, TypeType,
@@ -36,7 +37,7 @@ from mypy.types import (
     true_only, false_only, function_type, is_named_instance, union_items
 )
 from mypy.sametypes import is_same_type, is_same_types
-from mypy.messages import MessageBuilder
+from mypy.messages import MessageBuilder, make_inferred_type_note
 import mypy.checkexpr
 from mypy.checkmember import map_type_from_supertype, bind_self, erase_to_bound
 from mypy import messages
@@ -56,6 +57,7 @@ from mypy.treetransform import TransformVisitor
 from mypy.binder import ConditionalTypeBinder, get_declaration
 from mypy.meet import is_overlapping_types
 from mypy.options import Options
+from mypy.plugin import Plugin, CheckerPluginInterface
 
 from mypy import experiments
 
@@ -78,7 +80,7 @@ DeferredNode = NamedTuple(
     ])
 
 
-class TypeChecker(NodeVisitor[None]):
+class TypeChecker(NodeVisitor[None], CheckerPluginInterface):
     """Mypy type checker.
 
     Type check mypy source files that have been semantically analyzed.
@@ -127,8 +129,12 @@ class TypeChecker(NodeVisitor[None]):
     # directly or indirectly.
     module_refs = None  # type: Set[str]
 
+    # Plugin that provides special type checking rules for specific library
+    # functions such as open(), etc.
+    plugin = None  # type: Plugin
+
     def __init__(self, errors: Errors, modules: Dict[str, MypyFile], options: Options,
-                 tree: MypyFile, path: str) -> None:
+                 tree: MypyFile, path: str, plugin: Plugin) -> None:
         """Construct a type checker.
 
         Use errors to report type check errors.
@@ -139,7 +145,8 @@ class TypeChecker(NodeVisitor[None]):
         self.tree = tree
         self.path = path
         self.msg = MessageBuilder(errors, modules)
-        self.expr_checker = mypy.checkexpr.ExpressionChecker(self, self.msg)
+        self.plugin = plugin
+        self.expr_checker = mypy.checkexpr.ExpressionChecker(self, self.msg, self.plugin)
         self.scope = Scope(tree)
         self.binder = ConditionalTypeBinder()
         self.globals = tree.names
@@ -170,54 +177,56 @@ class TypeChecker(NodeVisitor[None]):
 
         Deferred functions will be processed by check_second_pass().
         """
-        self.errors.set_file(self.path, self.tree.fullname())
-        with self.enter_partial_types():
-            with self.binder.top_frame_context():
-                for d in self.tree.defs:
-                    self.accept(d)
+        with experiments.strict_optional_set(self.options.strict_optional):
+            self.errors.set_file(self.path, self.tree.fullname())
+            with self.enter_partial_types():
+                with self.binder.top_frame_context():
+                    for d in self.tree.defs:
+                        self.accept(d)
 
-        assert not self.current_node_deferred
+            assert not self.current_node_deferred
 
-        all_ = self.globals.get('__all__')
-        if all_ is not None and all_.type is not None:
-            all_node = all_.node
-            assert all_node is not None
-            seq_str = self.named_generic_type('typing.Sequence',
-                                              [self.named_type('builtins.str')])
-            if self.options.python_version[0] < 3:
+            all_ = self.globals.get('__all__')
+            if all_ is not None and all_.type is not None:
+                all_node = all_.node
+                assert all_node is not None
                 seq_str = self.named_generic_type('typing.Sequence',
-                                                  [self.named_type('builtins.unicode')])
-            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)
+                                                [self.named_type('builtins.str')])
+                if self.options.python_version[0] < 3:
+                    seq_str = self.named_generic_type('typing.Sequence',
+                                                    [self.named_type('builtins.unicode')])
+                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, todo: List[DeferredNode] = None) -> bool:
         """Run second or following pass of type checking.
 
         This goes through deferred nodes, returning True if there were any.
         """
-        if not todo and not self.deferred_nodes:
-            return False
-        self.errors.set_file(self.path, self.tree.fullname())
-        self.pass_num += 1
-        if not todo:
-            todo = self.deferred_nodes
-        else:
-            assert not self.deferred_nodes
-        self.deferred_nodes = []
-        done = set()  # type: Set[Union[FuncDef, LambdaExpr, MypyFile]]
-        for node, type_name, active_typeinfo in todo:
-            if node in done:
-                continue
-            # This is useful for debugging:
-            # print("XXX in pass %d, class %s, function %s" %
-            #       (self.pass_num, type_name, node.fullname() or node.name()))
-            done.add(node)
-            with self.errors.enter_type(type_name) if type_name else nothing():
-                with self.scope.push_class(active_typeinfo) if active_typeinfo else nothing():
-                    self.check_partial(node)
-        return True
+        with experiments.strict_optional_set(self.options.strict_optional):
+            if not todo and not self.deferred_nodes:
+                return False
+            self.errors.set_file(self.path, self.tree.fullname())
+            self.pass_num += 1
+            if not todo:
+                todo = self.deferred_nodes
+            else:
+                assert not self.deferred_nodes
+            self.deferred_nodes = []
+            done = set()  # type: Set[Union[FuncDef, LambdaExpr, MypyFile]]
+            for node, type_name, active_typeinfo in todo:
+                if node in done:
+                    continue
+                # This is useful for debugging:
+                # print("XXX in pass %d, class %s, function %s" %
+                #       (self.pass_num, type_name, node.fullname() or node.name()))
+                done.add(node)
+                with self.errors.enter_type(type_name) if type_name else nothing():
+                    with self.scope.push_class(active_typeinfo) if active_typeinfo else nothing():
+                        self.check_partial(node)
+            return True
 
     def check_partial(self, node: Union[FuncDef, LambdaExpr, MypyFile]) -> None:
         if isinstance(node, MypyFile):
@@ -611,12 +620,23 @@ class TypeChecker(NodeVisitor[None]):
                                 self.fail(messages.RETURN_TYPE_EXPECTED, fdef)
                             if any(is_implicit_any(t) for t in fdef.type.arg_types):
                                 self.fail(messages.ARGUMENT_TYPE_EXPECTED, fdef)
-
+                    if 'unimported' in self.options.disallow_any:
+                        if fdef.type and isinstance(fdef.type, CallableType):
+                            ret_type = fdef.type.ret_type
+                            if has_any_from_unimported_type(ret_type):
+                                self.msg.unimported_type_becomes_any("Return type", ret_type, fdef)
+                            for idx, arg_type in enumerate(fdef.type.arg_types):
+                                if has_any_from_unimported_type(arg_type):
+                                    prefix = "Argument {} to \"{}\"".format(idx + 1, fdef.name())
+                                    self.msg.unimported_type_becomes_any(prefix, arg_type, fdef)
+                    check_for_explicit_any(fdef.type, self.options, self.is_typeshed_stub,
+                                           self.msg, context=fdef)
                 if name in nodes.reverse_op_method_set:
                     self.check_reverse_op_method(item, typ, name)
                 elif name in ('__getattr__', '__getattribute__'):
                     self.check_getattr_method(typ, defn)
-
+                elif name == '__setattr__':
+                    self.check_setattr_method(typ, defn)
                 # Refuse contravariant return type variable
                 if isinstance(typ.ret_type, TypeVarType):
                     if typ.ret_type.variance == CONTRAVARIANT:
@@ -666,7 +686,7 @@ class TypeChecker(NodeVisitor[None]):
                             and typ.arg_kinds[0] not in [nodes.ARG_STAR, nodes.ARG_STAR2]):
                         isclass = defn.is_class or defn.name() in ('__new__', '__init_subclass__')
                         if isclass:
-                            ref_type = mypy.types.TypeType(ref_type)
+                            ref_type = mypy.types.TypeType.make_normalized(ref_type)
                         erased = erase_to_bound(arg_type)
                         if not is_subtype_ignoring_tvars(ref_type, erased):
                             note = None
@@ -916,6 +936,15 @@ class TypeChecker(NodeVisitor[None]):
         if not is_subtype(typ, method_type):
             self.msg.invalid_signature(typ, context)
 
+    def check_setattr_method(self, typ: CallableType, context: Context) -> None:
+        method_type = CallableType([AnyType(), self.named_type('builtins.str'), AnyType()],
+                                   [nodes.ARG_POS, nodes.ARG_POS, nodes.ARG_POS],
+                                   [None, None, None],
+                                   NoneTyp(),
+                                   self.named_type('builtins.function'))
+        if not is_subtype(typ, method_type):
+            self.msg.invalid_signature(typ, context)
+
     def expand_typevars(self, defn: FuncItem,
                         typ: CallableType) -> List[Tuple[FuncItem, CallableType]]:
         # TODO use generator
@@ -1179,6 +1208,17 @@ class TypeChecker(NodeVisitor[None]):
         """
         self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
 
+        if (s.type is not None and
+                'unimported' in self.options.disallow_any and
+                has_any_from_unimported_type(s.type)):
+            if isinstance(s.lvalues[-1], TupleExpr):
+                # This is a multiple assignment. Instead of figuring out which type is problematic,
+                # give a generic error message.
+                self.msg.unimported_type_becomes_any("A type on this line", AnyType(), s)
+            else:
+                self.msg.unimported_type_becomes_any("Type of variable", s.type, s)
+        check_for_explicit_any(s.type, self.options, self.is_typeshed_stub, self.msg, context=s)
+
         if len(s.lvalues) > 1:
             # Chained assignment (e.g. x = y = ...).
             # Make sure that rvalue type will not be reinferred.
@@ -1463,6 +1503,12 @@ class TypeChecker(NodeVisitor[None]):
         rvalue_type = self.expr_checker.accept(rvalue)  # TODO maybe elsewhere; redundant
         undefined_rvalue = False
 
+        if isinstance(rvalue_type, UnionType):
+            # If this is an Optional type in non-strict Optional code, unwrap it.
+            relevant_items = rvalue_type.relevant_items()
+            if len(relevant_items) == 1:
+                rvalue_type = relevant_items[0]
+
         if isinstance(rvalue_type, AnyType):
             for lv in lvalues:
                 if isinstance(lv, StarExpr):
@@ -1490,7 +1536,16 @@ class TypeChecker(NodeVisitor[None]):
             if not undefined_rvalue:
                 # Infer rvalue again, now in the correct type context.
                 lvalue_type = self.lvalue_type_for_inference(lvalues, rvalue_type)
-                rvalue_type = cast(TupleType, self.expr_checker.accept(rvalue, lvalue_type))
+                reinferred_rvalue_type = self.expr_checker.accept(rvalue, lvalue_type)
+
+                if isinstance(reinferred_rvalue_type, UnionType):
+                    # If this is an Optional type in non-strict Optional code, unwrap it.
+                    relevant_items = reinferred_rvalue_type.relevant_items()
+                    if len(relevant_items) == 1:
+                        reinferred_rvalue_type = relevant_items[0]
+
+                assert isinstance(reinferred_rvalue_type, TupleType)
+                rvalue_type = reinferred_rvalue_type
 
             left_rv_types, star_rv_types, right_rv_types = self.split_around_star(
                 rvalue_type.items, star_index, len(lvalues))
@@ -1701,7 +1756,9 @@ class TypeChecker(NodeVisitor[None]):
             # '...' is always a valid initializer in a stub.
             return AnyType()
         else:
-            rvalue_type = self.expr_checker.accept(rvalue, lvalue_type)
+            always_allow_any = lvalue_type is not None and not isinstance(lvalue_type, AnyType)
+            rvalue_type = self.expr_checker.accept(rvalue, lvalue_type,
+                                                   always_allow_any=always_allow_any)
             if isinstance(rvalue_type, DeletedType):
                 self.msg.deleted_as_rvalue(rvalue_type, context)
             if isinstance(lvalue_type, DeletedType):
@@ -1820,7 +1877,7 @@ class TypeChecker(NodeVisitor[None]):
                         del partial_types[var]
 
     def visit_expression_stmt(self, s: ExpressionStmt) -> None:
-        self.expr_checker.accept(s.expr, allow_none_return=True)
+        self.expr_checker.accept(s.expr, allow_none_return=True, always_allow_any=True)
 
     def visit_return_stmt(self, s: ReturnStmt) -> None:
         """Type check a return statement."""
@@ -1864,7 +1921,8 @@ class TypeChecker(NodeVisitor[None]):
                 if isinstance(typ, AnyType):
                     # (Unless you asked to be warned in that case, and the
                     # function is not declared to return Any)
-                    if not isinstance(return_type, AnyType) and self.options.warn_return_any:
+                    if (self.options.warn_return_any and
+                            not is_proper_subtype(AnyType(), return_type)):
                         self.warn(messages.RETURN_ANY.format(return_type), s)
                     return
 
@@ -1939,14 +1997,18 @@ class TypeChecker(NodeVisitor[None]):
         """Type check an operator assignment statement, e.g. x += 1."""
         lvalue_type = self.expr_checker.accept(s.lvalue)
         inplace, method = infer_operator_assignment_method(lvalue_type, s.op)
-        rvalue_type, method_type = self.expr_checker.check_op(
-            method, lvalue_type, s.rvalue, s)
-
-        if isinstance(s.lvalue, IndexExpr) and not inplace:
-            self.check_indexed_assignment(s.lvalue, s.rvalue, s.rvalue)
-        else:
+        if inplace:
+            # There is __ifoo__, treat as x = x.__ifoo__(y)
+            rvalue_type, method_type = self.expr_checker.check_op(
+                method, lvalue_type, s.rvalue, s)
             if not is_subtype(rvalue_type, lvalue_type):
                 self.msg.incompatible_operator_assignment(s.op, s)
+        else:
+            # There is no __ifoo__, treat as x = x <foo> y
+            expr = OpExpr(s.op, s.lvalue, s.rvalue)
+            expr.set_line(s)
+            self.check_assignment(lvalue=s.lvalue, rvalue=expr,
+                                  infer_lvalue_type=True, new_syntax=False)
 
     def visit_assert_stmt(self, s: AssertStmt) -> None:
         self.expr_checker.accept(s.expr)
@@ -2119,7 +2181,7 @@ class TypeChecker(NodeVisitor[None]):
         elif isinstance(typ, UnionType):
             return [
                 union_typ
-                for item in typ.items
+                for item in typ.relevant_items()
                 for union_typ in self.get_types_from_except_handler(item, n)
             ]
         elif isinstance(typ, Instance) and is_named_instance(typ, 'builtins.tuple'):
@@ -2219,8 +2281,13 @@ class TypeChecker(NodeVisitor[None]):
                 continue
             dec = self.expr_checker.accept(d)
             temp = self.temp_node(sig)
+            fullname = None
+            if isinstance(d, RefExpr):
+                fullname = d.fullname
             sig, t2 = self.expr_checker.check_call(dec, [temp],
-                                                   [nodes.ARG_POS], e)
+                                                   [nodes.ARG_POS], e,
+                                                   callable_name=fullname)
+        self.check_untyped_after_decorator(sig, e.func)
         sig = cast(FunctionLike, sig)
         sig = set_callable_name(sig, e.func)
         e.var.type = sig
@@ -2249,6 +2316,13 @@ class TypeChecker(NodeVisitor[None]):
                 self.check_with_item(expr, target, s.target_type is None)
         self.accept(s.body)
 
+    def check_untyped_after_decorator(self, typ: Type, func: FuncDef) -> None:
+        if 'decorated' not in self.options.disallow_any or self.is_stub:
+            return
+
+        if mypy.checkexpr.has_any_type(typ):
+            self.msg.untyped_decorated_function(typ, func)
+
     def check_async_with_item(self, expr: Expression, target: Expression,
                               infer_lvalue_type: bool) -> None:
         echk = self.expr_checker
@@ -2309,15 +2383,20 @@ class TypeChecker(NodeVisitor[None]):
             if self.should_suppress_optional_error([subtype]):
                 return False
             extra_info = []  # type: List[str]
+            note_msg = ''
             if subtype_label is not None or supertype_label is not None:
                 subtype_str, supertype_str = self.msg.format_distinctly(subtype, supertype)
                 if subtype_label is not None:
                     extra_info.append(subtype_label + ' ' + subtype_str)
                 if supertype_label is not None:
                     extra_info.append(supertype_label + ' ' + supertype_str)
+                note_msg = make_inferred_type_note(context, subtype,
+                                                   supertype, supertype_str)
             if extra_info:
                 msg += ' (' + ', '.join(extra_info) + ')'
             self.fail(msg, context)
+            if note_msg:
+                self.note(note_msg, context)
             return False
 
     def contains_none(self, t: Type) -> bool:
@@ -2568,7 +2647,7 @@ def partition_by_callable(type: Optional[Type]) -> Tuple[List[Type], List[Type]]
     if isinstance(type, UnionType):
         callables = []
         uncallables = []
-        for subtype in type.items:
+        for subtype in type.relevant_items():
             subcallables, subuncallables = partition_by_callable(subtype)
             callables.extend(subcallables)
             uncallables.extend(subuncallables)
@@ -2692,13 +2771,10 @@ def convert_to_typetype(type_map: TypeMap) -> TypeMap:
     if type_map is None:
         return None
     for expr, typ in type_map.items():
-        if isinstance(typ, UnionType):
-            converted_type_map[expr] = UnionType([TypeType(t) for t in typ.items])
-        elif isinstance(typ, Instance):
-            converted_type_map[expr] = TypeType(typ)
-        else:
+        if not isinstance(typ, (UnionType, Instance)):
             # unknown type; error was likely reported earlier
             return {}
+        converted_type_map[expr] = TypeType.make_normalized(typ)
     return converted_type_map
 
 
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
index b19a0a1..13e195d 100644
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -4,6 +4,7 @@ from collections import OrderedDict
 from typing import cast, Dict, Set, List, Tuple, Callable, Union, Optional
 
 from mypy.errors import report_internal_error
+from mypy.typeanal import has_any_from_unimported_type, check_for_explicit_any, set_any_tvars
 from mypy.types import (
     Type, AnyType, CallableType, Overloaded, NoneTyp, TypeVarDef,
     TupleType, TypedDictType, Instance, TypeVarType, ErasedType, UnionType,
@@ -44,6 +45,8 @@ from mypy.expandtype import expand_type_by_instance, freshen_function_type_vars
 from mypy.util import split_module_names
 from mypy.typevars import fill_typevars
 from mypy.visitor import ExpressionVisitor
+from mypy.plugin import Plugin, MethodContext, MethodSigContext, FunctionContext
+from mypy.typeanal import make_optional_type
 
 from mypy import experiments
 
@@ -103,13 +106,16 @@ class ExpressionChecker(ExpressionVisitor[Type]):
     type_context = None  # type: List[Optional[Type]]
 
     strfrm_checker = None  # type: StringFormatterChecker
+    plugin = None  # type: Plugin
 
     def __init__(self,
                  chk: 'mypy.checker.TypeChecker',
-                 msg: MessageBuilder) -> None:
+                 msg: MessageBuilder,
+                 plugin: Plugin) -> None:
         """Construct an expression type checker."""
         self.chk = chk
         self.msg = msg
+        self.plugin = plugin
         self.type_context = [None]
         self.strfrm_checker = StringFormatterChecker(self, self.chk, self.msg)
 
@@ -150,7 +156,13 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             result = type_object_type(node, self.named_type)
         elif isinstance(node, MypyFile):
             # Reference to a module object.
-            result = self.named_type('types.ModuleType')
+            try:
+                result = self.named_type('types.ModuleType')
+            except KeyError:
+                # In test cases might 'types' may not be available.
+                # Fall back to a dummy 'object' type instead to
+                # avoid a crash.
+                result = self.named_type('builtins.object')
         elif isinstance(node, Decorator):
             result = self.analyze_var_ref(node.var, e)
         else:
@@ -176,9 +188,12 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             return self.accept(e.analyzed, self.type_context[-1])
         if isinstance(e.callee, NameExpr) and isinstance(e.callee.node, TypeInfo) and \
                 e.callee.node.typeddict_type is not None:
-            return self.check_typeddict_call(e.callee.node.typeddict_type,
-                                             e.arg_kinds, e.arg_names, e.args, e)
-        if isinstance(e.callee, NameExpr) and e.callee.name in ('isinstance', 'issubclass'):
+            # Use named fallback for better error messages.
+            typeddict_type = e.callee.node.typeddict_type.copy_modified(
+                fallback=Instance(e.callee.node, []))
+            return self.check_typeddict_call(typeddict_type, e.arg_kinds, e.arg_names, e.args, e)
+        if (isinstance(e.callee, NameExpr) and e.callee.name in ('isinstance', 'issubclass')
+                and len(e.args) == 2):
             for typ in mypy.checker.flatten(e.args[1]):
                 if isinstance(typ, NameExpr):
                     try:
@@ -186,19 +201,50 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                     except KeyError:
                         # Undefined names should already be reported in semantic analysis.
                         node = None
-                if (isinstance(typ, IndexExpr)
-                        and isinstance(typ.analyzed, (TypeApplication, TypeAliasExpr))
+                if ((isinstance(typ, IndexExpr)
+                        and isinstance(typ.analyzed, (TypeApplication, TypeAliasExpr)))
                         # node.kind == TYPE_ALIAS only for aliases like It = Iterable[int].
-                        or isinstance(typ, NameExpr) and node and node.kind == nodes.TYPE_ALIAS):
+                        or (isinstance(typ, NameExpr) and node and node.kind == nodes.TYPE_ALIAS)):
                     self.msg.type_arguments_not_allowed(e)
+                if isinstance(typ, RefExpr) and isinstance(typ.node, TypeInfo):
+                    if typ.node.typeddict_type:
+                        self.msg.fail(messages.CANNOT_ISINSTANCE_TYPEDDICT, e)
+                    elif typ.node.is_newtype:
+                        self.msg.fail(messages.CANNOT_ISINSTANCE_NEWTYPE, e)
         self.try_infer_partial_type(e)
-        callee_type = self.accept(e.callee)
+        callee_type = self.accept(e.callee, always_allow_any=True)
         if (self.chk.options.disallow_untyped_calls and
                 self.chk.in_checked_function() and
                 isinstance(callee_type, CallableType)
                 and callee_type.implicit):
             return self.msg.untyped_function_call(callee_type, e)
-        ret_type = self.check_call_expr_with_callee_type(callee_type, e)
+        # Figure out the full name of the callee for plugin loopup.
+        object_type = None
+        if not isinstance(e.callee, RefExpr):
+            fullname = None
+        else:
+            fullname = e.callee.fullname
+            if (fullname is None
+                    and isinstance(e.callee, MemberExpr)
+                    and isinstance(callee_type, FunctionLike)):
+                # For method calls we include the defining class for the method
+                # in the full name (example: 'typing.Mapping.get').
+                callee_expr_type = self.chk.type_map.get(e.callee.expr)
+                info = None
+                # TODO: Support fallbacks of other kinds of types as well?
+                if isinstance(callee_expr_type, Instance):
+                    info = callee_expr_type.type
+                elif isinstance(callee_expr_type, TypedDictType):
+                    info = callee_expr_type.fallback.type.get_containing_type_info(e.callee.name)
+                if info:
+                    fullname = '{}.{}'.format(info.fullname(), e.callee.name)
+                    object_type = callee_expr_type
+                    # Apply plugin signature hook that may generate a better signature.
+                    signature_hook = self.plugin.get_method_signature_hook(fullname)
+                    if signature_hook:
+                        callee_type = self.apply_method_signature_hook(
+                            e, callee_type, object_type, signature_hook)
+        ret_type = self.check_call_expr_with_callee_type(callee_type, e, fullname, object_type)
         if isinstance(ret_type, UninhabitedType):
             self.chk.binder.unreachable()
         if not allow_none_return and isinstance(ret_type, NoneTyp):
@@ -244,7 +290,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         item_names = []  # List[str]
         for item_name_expr in item_name_exprs:
             if not isinstance(item_name_expr, StrExpr):
-                self.chk.fail(messages.TYPEDDICT_ITEM_NAME_MUST_BE_STRING_LITERAL, item_name_expr)
+                self.chk.fail(messages.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL, item_name_expr)
                 return AnyType()
             item_names.append(item_name_expr.value)
 
@@ -254,31 +300,27 @@ class ExpressionChecker(ExpressionVisitor[Type]):
     def check_typeddict_call_with_kwargs(self, callee: TypedDictType,
                                          kwargs: 'OrderedDict[str, Expression]',
                                          context: Context) -> Type:
-        if callee.items.keys() != kwargs.keys():
-            callee_item_names = callee.items.keys()
-            kwargs_item_names = kwargs.keys()
-
-            self.msg.typeddict_instantiated_with_unexpected_items(
-                expected_item_names=list(callee_item_names),
-                actual_item_names=list(kwargs_item_names),
+        if not (callee.required_keys <= set(kwargs.keys()) <= set(callee.items.keys())):
+            expected_keys = [key for key in callee.items.keys()
+                             if key in callee.required_keys or key in kwargs.keys()]
+            actual_keys = kwargs.keys()
+            self.msg.unexpected_typeddict_keys(
+                callee,
+                expected_keys=expected_keys,
+                actual_keys=list(actual_keys),
                 context=context)
             return AnyType()
 
-        items = OrderedDict()  # type: OrderedDict[str, Type]
         for (item_name, item_expected_type) in callee.items.items():
-            item_value = kwargs[item_name]
-
-            self.chk.check_simple_assignment(
-                lvalue_type=item_expected_type, rvalue=item_value, context=item_value,
-                msg=messages.INCOMPATIBLE_TYPES,
-                lvalue_name='TypedDict item "{}"'.format(item_name),
-                rvalue_name='expression')
-            items[item_name] = item_expected_type
+            if item_name in kwargs:
+                item_value = kwargs[item_name]
+                self.chk.check_simple_assignment(
+                    lvalue_type=item_expected_type, rvalue=item_value, context=item_value,
+                    msg=messages.INCOMPATIBLE_TYPES,
+                    lvalue_name='TypedDict item "{}"'.format(item_name),
+                    rvalue_name='expression')
 
-        mapping_value_type = join.join_type_list(list(items.values()))
-        fallback = self.chk.named_generic_type('typing.Mapping',
-                                               [self.chk.str_type(), mapping_value_type])
-        return TypedDictType(items, fallback)
+        return callee
 
     # Types and methods that can be used to infer partial types.
     item_args = {'builtins.list': ['append'],
@@ -330,21 +372,99 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                                                                        list(full_item_types))
                                 del partial_types[var]
 
-    def check_call_expr_with_callee_type(self, callee_type: Type,
-                                         e: CallExpr) -> Type:
+    def apply_function_plugin(self,
+                              arg_types: List[Type],
+                              inferred_ret_type: Type,
+                              arg_kinds: List[int],
+                              formal_to_actual: List[List[int]],
+                              args: List[Expression],
+                              num_formals: int,
+                              fullname: str,
+                              object_type: Optional[Type],
+                              context: Context) -> Type:
+        """Use special case logic to infer the return type of a specific named function/method.
+
+        Caller must ensure that a plugin hook exists. There are two different cases:
+
+        - If object_type is None, the caller must ensure that a function hook exists
+          for fullname.
+        - If object_type is not None, the caller must ensure that a method hook exists
+          for fullname.
+
+        Return the inferred return type.
+        """
+        formal_arg_types = [[] for _ in range(num_formals)]  # type: List[List[Type]]
+        formal_arg_exprs = [[] for _ in range(num_formals)]  # type: List[List[Expression]]
+        for formal, actuals in enumerate(formal_to_actual):
+            for actual in actuals:
+                formal_arg_types[formal].append(arg_types[actual])
+                formal_arg_exprs[formal].append(args[actual])
+        if object_type is None:
+            # Apply function plugin
+            callback = self.plugin.get_function_hook(fullname)
+            assert callback is not None  # Assume that caller ensures this
+            return callback(
+                FunctionContext(formal_arg_types, inferred_ret_type, formal_arg_exprs,
+                                context, self.chk))
+        else:
+            # Apply method plugin
+            method_callback = self.plugin.get_method_hook(fullname)
+            assert method_callback is not None  # Assume that caller ensures this
+            return method_callback(
+                MethodContext(object_type, formal_arg_types,
+                              inferred_ret_type, formal_arg_exprs,
+                              context, self.chk))
+
+    def apply_method_signature_hook(
+            self, e: CallExpr, callee: FunctionLike, object_type: Type,
+            signature_hook: Callable[[MethodSigContext], CallableType]) -> FunctionLike:
+        """Apply a plugin hook that may infer a more precise signature for a method."""
+        if isinstance(callee, CallableType):
+            arg_kinds = e.arg_kinds
+            arg_names = e.arg_names
+            args = e.args
+            num_formals = len(callee.arg_kinds)
+            formal_to_actual = map_actuals_to_formals(
+                arg_kinds, arg_names,
+                callee.arg_kinds, callee.arg_names,
+                lambda i: self.accept(args[i]))
+            formal_arg_exprs = [[] for _ in range(num_formals)]  # type: List[List[Expression]]
+            for formal, actuals in enumerate(formal_to_actual):
+                for actual in actuals:
+                    formal_arg_exprs[formal].append(args[actual])
+            return signature_hook(
+                MethodSigContext(object_type, formal_arg_exprs, callee, e, self.chk))
+        else:
+            assert isinstance(callee, Overloaded)
+            items = []
+            for item in callee.items():
+                adjusted = self.apply_method_signature_hook(e, item, object_type, signature_hook)
+                assert isinstance(adjusted, CallableType)
+                items.append(adjusted)
+            return Overloaded(items)
+
+    def check_call_expr_with_callee_type(self,
+                                         callee_type: Type,
+                                         e: CallExpr,
+                                         callable_name: Optional[str],
+                                         object_type: Optional[Type]) -> Type:
         """Type check call expression.
 
         The given callee type overrides the type of the callee
         expression.
         """
         return self.check_call(callee_type, e.args, e.arg_kinds, e,
-                               e.arg_names, callable_node=e.callee)[0]
+                               e.arg_names, callable_node=e.callee,
+                               callable_name=callable_name,
+                               object_type=object_type)[0]
 
     def check_call(self, callee: Type, args: List[Expression],
                    arg_kinds: List[int], context: Context,
                    arg_names: List[str] = None,
                    callable_node: Expression = None,
-                   arg_messages: MessageBuilder = None) -> Tuple[Type, Type]:
+                   arg_messages: MessageBuilder = None,
+                   callable_name: Optional[str] = None,
+                   object_type: Optional[Type] = None) -> Tuple[Type, Type]:
         """Type check a call.
 
         Also infer type arguments if the callee is a generic function.
@@ -352,17 +472,23 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         Return (result type, inferred callee type).
 
         Arguments:
-          callee: type of the called value
-          args: actual argument expressions
-          arg_kinds: contains nodes.ARG_* constant for each argument in args
-            describing whether the argument is positional, *arg, etc.
-          arg_names: names of arguments (optional)
-          callable_node: associate the inferred callable type to this node,
-            if specified
-          arg_messages: TODO
+            callee: type of the called value
+            args: actual argument expressions
+            arg_kinds: contains nodes.ARG_* constant for each argument in args
+                 describing whether the argument is positional, *arg, etc.
+            arg_names: names of arguments (optional)
+            callable_node: associate the inferred callable type to this node,
+                if specified
+            arg_messages: TODO
+            callable_name: Fully-qualified name of the function/method to call,
+                or None if unavaiable (examples: 'builtins.open', 'typing.Mapping.get')
+            object_type: If callable_name refers to a method, the type of the object
+                on which the method is being called
         """
         arg_messages = arg_messages or self.msg
         if isinstance(callee, CallableType):
+            if callable_name is None and callee.name:
+                callable_name = callee.name
             if (isinstance(callable_node, RefExpr)
                 and callable_node.fullname in ('enum.Enum', 'enum.IntEnum',
                                                'enum.Flag', 'enum.IntFlag')):
@@ -401,11 +527,20 @@ class ExpressionChecker(ExpressionVisitor[Type]):
 
             if (callee.is_type_obj() and (len(arg_types) == 1)
                     and is_equivalent(callee.ret_type, self.named_type('builtins.type'))):
-                callee = callee.copy_modified(ret_type=TypeType(arg_types[0]))
+                callee = callee.copy_modified(ret_type=TypeType.make_normalized(arg_types[0]))
 
             if callable_node:
                 # Store the inferred callable type.
                 self.chk.store_type(callable_node, callee)
+
+            if (callable_name
+                    and ((object_type is None and self.plugin.get_function_hook(callable_name))
+                         or (object_type is not None
+                             and self.plugin.get_method_hook(callable_name)))):
+                ret_type = self.apply_function_plugin(
+                    arg_types, callee.ret_type, arg_kinds, formal_to_actual,
+                    args, len(callee.arg_types), callable_name, object_type, context)
+                callee = callee.copy_modified(ret_type=ret_type)
             return callee.ret_type, callee
         elif isinstance(callee, Overloaded):
             # Type check arguments in empty context. They will be checked again
@@ -419,7 +554,9 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                                                callee, context,
                                                messages=arg_messages)
             return self.check_call(target, args, arg_kinds, context, arg_names,
-                                   arg_messages=arg_messages)
+                                   arg_messages=arg_messages,
+                                   callable_name=callable_name,
+                                   object_type=object_type)
         elif isinstance(callee, AnyType) or not self.chk.in_checked_function():
             self.infer_arg_types_in_context(None, args)
             return AnyType(), AnyType()
@@ -427,7 +564,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             self.msg.disable_type_names += 1
             results = [self.check_call(subtype, args, arg_kinds, context, arg_names,
                                        arg_messages=arg_messages)
-                       for subtype in callee.items]
+                       for subtype in callee.relevant_items()]
             self.msg.disable_type_names -= 1
             return (UnionType.make_simplified_union([res[0] for res in results]),
                     callee)
@@ -463,7 +600,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             return res
         if isinstance(item, UnionType):
             return UnionType([self.analyze_type_type_callee(item, context)
-                              for item in item.items], item.line)
+                              for item in item.relevant_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,
@@ -824,7 +961,8 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                     messages.invalid_var_arg(arg_type, context)
                 if (arg_kinds[actual] == nodes.ARG_STAR2 and
                         not self.is_valid_keyword_var_arg(arg_type)):
-                    messages.invalid_keyword_var_arg(arg_type, context)
+                    is_mapping = is_subtype(arg_type, self.chk.named_type('typing.Mapping'))
+                    messages.invalid_keyword_var_arg(arg_type, is_mapping, context)
                 # Get the type of an individual actual argument (for *args
                 # and **args this is the item type, not the collection type).
                 if (isinstance(arg_type, TupleType)
@@ -1072,7 +1210,8 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             owner_type = instance_type
 
         _, inferred_dunder_get_type = self.check_call(
-            dunder_get_type, [TempNode(instance_type), TempNode(TypeType(owner_type))],
+            dunder_get_type,
+            [TempNode(instance_type), TempNode(TypeType.make_normalized(owner_type))],
             [nodes.ARG_POS, nodes.ARG_POS], context)
 
         if isinstance(inferred_dunder_get_type, AnyType):
@@ -1253,8 +1392,16 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         method_type = analyze_member_access(method, base_type, context, False, False, True,
                                             self.named_type, self.not_ready_callback, local_errors,
                                             original_type=base_type, chk=self.chk)
+        callable_name = None
+        object_type = None
+        if isinstance(base_type, Instance):
+            # TODO: Find out in which class the method was defined originally?
+            # TODO: Support non-Instance types.
+            callable_name = '{}.{}'.format(base_type.type.fullname(), method)
+            object_type = base_type
         return self.check_call(method_type, [arg], [nodes.ARG_POS],
-                               context, arg_messages=local_errors)
+                               context, arg_messages=local_errors,
+                               callable_name=callable_name, object_type=object_type)
 
     def check_op(self, method: str, base_type: Type, arg: Expression,
                  context: Context,
@@ -1367,6 +1514,11 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             restricted_left_type = true_only(left_type)
             result_is_left = not left_type.can_be_false
 
+        if e.right_unreachable:
+            right_map = None
+        elif e.right_always:
+            left_map = None
+
         right_type = self.analyze_cond_branch(right_map, e.right, left_type)
 
         if right_map is None:
@@ -1441,31 +1593,23 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             return self.accept(e.analyzed)
         left_type = self.accept(e.base)
         if isinstance(left_type, TupleType) and self.chk.in_checked_function():
-            # Special case for tuples. They support indexing only by integer
-            # literals.
+            # Special case for tuples. They return a more specific type when
+            # indexed by an integer literal.
             index = e.index
             if isinstance(index, SliceExpr):
                 return self.visit_tuple_slice_helper(left_type, index)
 
-            ok = False
-            if isinstance(index, IntExpr):
-                n = index.value
-                ok = True
-            elif isinstance(index, UnaryExpr):
-                if index.op == '-':
-                    operand = index.expr
-                    if isinstance(operand, IntExpr):
-                        n = len(left_type.items) - operand.value
-                        ok = True
-            if ok:
+            n = self._get_value(index)
+            if n is not None:
+                if n < 0:
+                    n += len(left_type.items)
                 if n >= 0 and n < len(left_type.items):
                     return left_type.items[n]
                 else:
                     self.chk.fail(messages.TUPLE_INDEX_OUT_OF_RANGE, e)
                     return AnyType()
             else:
-                self.chk.fail(messages.TUPLE_INDEX_MUST_BE_AN_INT_LITERAL, e)
-                return AnyType()
+                return self.nonliteral_tuple_index_helper(left_type, index)
         elif isinstance(left_type, TypedDictType):
             return self.visit_typeddict_index_expr(left_type, e.index)
         elif (isinstance(left_type, CallableType)
@@ -1484,29 +1628,31 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         if 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()
+                return self.nonliteral_tuple_index_helper(left_type, slic)
 
         if 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()
+                return self.nonliteral_tuple_index_helper(left_type, slic)
 
         if 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 self.nonliteral_tuple_index_helper(left_type, slic)
 
         return left_type.slice(begin, stride, end)
 
+    def nonliteral_tuple_index_helper(self, left_type: TupleType, index: Expression) -> Type:
+        index_type = self.accept(index)
+        expected_type = UnionType.make_union([self.named_type('builtins.int'),
+                                              self.named_type('builtins.slice')])
+        if not self.chk.check_subtype(index_type, expected_type, index,
+                                      messages.INVALID_TUPLE_INDEX_TYPE,
+                                      'actual type', 'expected type'):
+            return AnyType()
+        else:
+            return UnionType.make_simplified_union(left_type.items)
+
     def _get_value(self, index: Expression) -> Optional[int]:
         if isinstance(index, IntExpr):
             return index.value
@@ -1519,13 +1665,13 @@ class ExpressionChecker(ExpressionVisitor[Type]):
 
     def visit_typeddict_index_expr(self, td_type: TypedDictType, index: Expression) -> Type:
         if not isinstance(index, (StrExpr, UnicodeExpr)):
-            self.msg.typeddict_item_name_must_be_string_literal(td_type, index)
+            self.msg.typeddict_key_must_be_string_literal(td_type, index)
             return AnyType()
         item_name = index.value
 
         item_type = td_type.items.get(item_name)
         if item_type is None:
-            self.msg.typeddict_item_name_not_found(td_type, item_name, index)
+            self.msg.typeddict_key_not_found(td_type, item_name, index)
             return AnyType()
         return item_type
 
@@ -1541,10 +1687,16 @@ class ExpressionChecker(ExpressionVisitor[Type]):
 
     def visit_cast_expr(self, expr: CastExpr) -> Type:
         """Type check a cast expression."""
-        source_type = self.accept(expr.expr, type_context=AnyType(), allow_none_return=True)
+        source_type = self.accept(expr.expr, type_context=AnyType(), allow_none_return=True,
+                                  always_allow_any=True)
         target_type = expr.type
-        if self.chk.options.warn_redundant_casts and is_same_type(source_type, target_type):
+        options = self.chk.options
+        if options.warn_redundant_casts and is_same_type(source_type, target_type):
             self.msg.redundant_cast(target_type, expr)
+        if 'unimported' in options.disallow_any and has_any_from_unimported_type(target_type):
+            self.msg.unimported_type_becomes_any("Target type of cast", target_type, expr)
+        check_for_explicit_any(target_type, self.chk.options, self.chk.is_typeshed_stub, self.msg,
+                               context=expr)
         return target_type
 
     def visit_reveal_type_expr(self, expr: RevealTypeExpr) -> Type:
@@ -1585,7 +1737,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         item = alias.type
         if not alias.in_runtime:
             # We don't replace TypeVar's with Any for alias used as Alias[T](42).
-            item = self.replace_tvars_any(item)
+            item = set_any_tvars(item, alias.tvars, alias.line, alias.column)
         if isinstance(item, Instance):
             # Normally we get a callable type (or overloaded) with .is_type_obj() true
             # representing the class's constructor
@@ -1610,26 +1762,6 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                                for it in tp.items()])
         return AnyType()
 
-    def replace_tvars_any(self, tp: Type) -> Type:
-        """Replace all type variables of a type alias tp with Any. Basically, this function
-        finishes what could not be done in method TypeAnalyser.visit_unbound_type()
-        from typeanal.py.
-        """
-        typ_args = get_typ_args(tp)
-        new_args = typ_args[:]
-        for i, arg in enumerate(typ_args):
-            if isinstance(arg, UnboundType):
-                sym = None
-                try:
-                    sym = self.chk.lookup_qualified(arg.name)
-                except KeyError:
-                    pass
-                if sym and (sym.kind == TVAR):
-                    new_args[i] = AnyType()
-            else:
-                new_args[i] = self.replace_tvars_any(arg)
-        return set_typ_args(tp, new_args, tp.line, tp.column)
-
     def visit_list_expr(self, e: ListExpr) -> Type:
         """Type check a list expression [...]."""
         return self.check_lst_expr(e.items, 'builtins.list', '<list>', e)
@@ -1727,13 +1859,14 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         # an error, but returns the TypedDict type that matches the literal it found
         # that would cause a second error when that TypedDict type is returned upstream
         # to avoid the second error, we always return TypedDict type that was requested
-        if isinstance(self.type_context[-1], TypedDictType):
+        typeddict_context = self.find_typeddict_context(self.type_context[-1])
+        if typeddict_context:
             self.check_typeddict_call_with_dict(
-                callee=self.type_context[-1],
+                callee=typeddict_context,
                 kwargs=e,
                 context=e
             )
-            return self.type_context[-1].copy_modified()
+            return typeddict_context.copy_modified()
 
         # Collect function arguments, watching out for **expr.
         args = []  # type: List[Expression]  # Regular "key: value"
@@ -1784,16 +1917,34 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                     self.check_call(method, [arg], [nodes.ARG_POS], arg)
         return rv
 
+    def find_typeddict_context(self, context: Type) -> Optional[TypedDictType]:
+        if isinstance(context, TypedDictType):
+            return context
+        elif isinstance(context, UnionType):
+            items = []
+            for item in context.items:
+                item_context = self.find_typeddict_context(item)
+                if item_context:
+                    items.append(item_context)
+            if len(items) == 1:
+                # Only one union item is TypedDict, so use the context as it's unambiguous.
+                return items[0]
+        # No TypedDict type in context.
+        return None
+
     def visit_lambda_expr(self, e: LambdaExpr) -> Type:
         """Type check lambda expression."""
         inferred_type, type_override = self.infer_lambda_type_using_context(e)
         if not inferred_type:
+            self.chk.return_types.append(AnyType())
             # No useful type context.
             ret_type = self.accept(e.expr(), allow_none_return=True)
             fallback = self.named_type('builtins.function')
+            self.chk.return_types.pop()
             return callable_type(e, fallback, ret_type)
         else:
             # Type context available.
+            self.chk.return_types.append(inferred_type.ret_type)
             self.chk.check_func_item(e, type_override=type_override)
             if e.expr() not in self.chk.type_map:
                 self.accept(e.expr(), allow_none_return=True)
@@ -1802,7 +1953,9 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                 # For "lambda ...: None", just use type from the context.
                 # Important when the context is Callable[..., None] which
                 # really means Void. See #1425.
+                self.chk.return_types.pop()
                 return inferred_type
+            self.chk.return_types.pop()
             return replace_callable_return_type(inferred_type, ret_type)
 
     def infer_lambda_type_using_context(self, e: LambdaExpr) -> Tuple[Optional[CallableType],
@@ -1816,7 +1969,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         ctx = self.type_context[-1]
 
         if isinstance(ctx, UnionType):
-            callables = [t for t in ctx.items if isinstance(t, CallableType)]
+            callables = [t for t in ctx.relevant_items() if isinstance(t, CallableType)]
             if len(callables) == 1:
                 ctx = callables[0]
 
@@ -1893,10 +2046,11 @@ class ExpressionChecker(ExpressionVisitor[Type]):
             return AnyType()
 
     def visit_slice_expr(self, e: SliceExpr) -> Type:
+        expected = make_optional_type(self.named_type('builtins.int'))
         for index in [e.begin_index, e.end_index, e.stride]:
             if index:
                 t = self.accept(index)
-                self.chk.check_subtype(t, self.named_type('builtins.int'),
+                self.chk.check_subtype(t, expected,
                                        index, messages.INVALID_SLICE_INDEX)
         return self.named_type('builtins.slice')
 
@@ -2042,7 +2196,8 @@ class ExpressionChecker(ExpressionVisitor[Type]):
     def accept(self,
                node: Expression,
                type_context: Type = None,
-               allow_none_return: bool = False
+               allow_none_return: bool = False,
+               always_allow_any: bool = False,
                ) -> Type:
         """Type check a node in the given type context.  If allow_none_return
         is True and this expression is a call, allow it to return None.  This
@@ -2062,6 +2217,14 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         self.type_context.pop()
         assert typ is not None
         self.chk.store_type(node, typ)
+
+        if ('expr' in self.chk.options.disallow_any and
+                not always_allow_any and
+                not self.chk.is_stub and
+                self.chk.in_checked_function() and
+                has_any_type(typ)):
+            self.msg.disallowed_any_type(typ, node)
+
         if not self.chk.in_checked_function():
             return AnyType()
         else:
@@ -2084,17 +2247,17 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         """Is a type valid as a **kwargs argument?"""
         if self.chk.options.python_version[0] >= 3:
             return is_subtype(typ, self.chk.named_generic_type(
-                'builtins.dict', [self.named_type('builtins.str'),
-                                  AnyType()]))
+                'typing.Mapping', [self.named_type('builtins.str'),
+                                   AnyType()]))
         else:
             return (
                 is_subtype(typ, self.chk.named_generic_type(
-                    'builtins.dict',
+                    'typing.Mapping',
                     [self.named_type('builtins.str'),
                      AnyType()]))
                 or
                 is_subtype(typ, self.chk.named_generic_type(
-                    'builtins.dict',
+                    'typing.Mapping',
                     [self.named_type('builtins.unicode'),
                      AnyType()])))
 
@@ -2108,7 +2271,7 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         elif isinstance(typ, AnyType):
             return True
         elif isinstance(typ, UnionType):
-            result = all(self.has_member(x, member) for x in typ.items)
+            result = all(self.has_member(x, member) for x in typ.relevant_items())
             return result
         elif isinstance(typ, TupleType):
             return self.has_member(typ.fallback, member)
@@ -2222,15 +2385,20 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         return e.type
 
     def visit_type_var_expr(self, e: TypeVarExpr) -> Type:
-        # TODO: Perhaps return a special type used for type variables only?
-        return AnyType()
+        return AnyType(special_form=True)
 
     def visit_newtype_expr(self, e: NewTypeExpr) -> Type:
-        return AnyType()
+        return AnyType(special_form=True)
 
     def visit_namedtuple_expr(self, e: NamedTupleExpr) -> Type:
-        # TODO: Perhaps return a type object type?
-        return AnyType()
+        tuple_type = e.info.tuple_type
+        if tuple_type:
+            if ('unimported' in self.chk.options.disallow_any and
+                    has_any_from_unimported_type(tuple_type)):
+                self.msg.unimported_type_becomes_any("NamedTuple type", tuple_type, e)
+            check_for_explicit_any(tuple_type, self.chk.options, self.chk.is_typeshed_stub,
+                                   self.msg, context=e)
+        return AnyType(special_form=True)
 
     def visit_enum_call_expr(self, e: EnumCallExpr) -> Type:
         for name, value in zip(e.items, e.values):
@@ -2245,12 +2413,10 @@ class ExpressionChecker(ExpressionVisitor[Type]):
                         # to have type Any in the typeshed stub.)
                         var.type = typ
                         var.is_inferred = True
-        # TODO: Perhaps return a type object type?
-        return AnyType()
+        return AnyType(special_form=True)
 
     def visit_typeddict_expr(self, e: TypedDictExpr) -> Type:
-        # TODO: Perhaps return a type object type?
-        return AnyType()
+        return AnyType(special_form=True)
 
     def visit__promote_expr(self, e: PromoteExpr) -> Type:
         return e.type
@@ -2275,6 +2441,19 @@ class ExpressionChecker(ExpressionVisitor[Type]):
         return known_type
 
 
+def has_any_type(t: Type) -> bool:
+    """Whether t contains an Any type"""
+    return t.accept(HasAnyType())
+
+
+class HasAnyType(types.TypeQuery[bool]):
+    def __init__(self) -> None:
+        super().__init__(any)
+
+    def visit_any(self, t: AnyType) -> bool:
+        return not t.special_form  # special forms are not real Any types
+
+
 def has_coroutine_decorator(t: Type) -> bool:
     """Whether t came from a function decorated with `@coroutine`."""
     return isinstance(t, Instance) and t.type.fullname() == 'typing.AwaitableGenerator'
@@ -2465,10 +2644,10 @@ def overload_arg_similarity(actual: Type, formal: Type) -> int:
                 return 2
     if isinstance(actual, UnionType):
         return max(overload_arg_similarity(item, formal)
-                   for item in actual.items)
+                   for item in actual.relevant_items())
     if isinstance(formal, UnionType):
         return max(overload_arg_similarity(actual, item)
-                   for item in formal.items)
+                   for item in formal.relevant_items())
     if isinstance(formal, TypeType):
         if isinstance(actual, TypeType):
             # Since Type[T] is covariant, check if actual = Type[A] is
@@ -2480,6 +2659,12 @@ def overload_arg_similarity(actual: Type, formal: Type) -> int:
             return overload_arg_similarity(actual.ret_type, formal.item)
         else:
             return 0
+    if isinstance(actual, TypedDictType):
+        if isinstance(formal, TypedDictType):
+            # Don't support overloading based on the keys or value types of a TypedDict since
+            # that would be complicated and probably only marginally useful.
+            return 2
+        return overload_arg_similarity(actual.fallback, formal)
     if isinstance(formal, Instance):
         if isinstance(actual, CallableType):
             actual = actual.fallback
@@ -2497,8 +2682,12 @@ def overload_arg_similarity(actual: Type, formal: Type) -> int:
             else:
                 return 0
         elif isinstance(actual, TypeType):
+            item = actual.item
             if formal.type.fullname() in {"builtins.object", "builtins.type"}:
                 return 2
+            elif isinstance(item, Instance):
+                # FIX: this does not handle e.g. Union of instances
+                return overload_arg_similarity(item.type.metaclass_type, formal)
             else:
                 return 0
         else:
diff --git a/mypy/checkmember.py b/mypy/checkmember.py
index ed3239a..112efcf 100644
--- a/mypy/checkmember.py
+++ b/mypy/checkmember.py
@@ -4,7 +4,7 @@ from typing import cast, Callable, List, Optional, TypeVar
 
 from mypy.types import (
     Type, Instance, AnyType, TupleType, TypedDictType, CallableType, FunctionLike, TypeVarDef,
-    Overloaded, TypeVarType, UnionType, PartialType,
+    Overloaded, TypeVarType, UnionType, PartialType, UninhabitedType,
     DeletedType, NoneTyp, TypeType, function_type, get_type_vars,
 )
 from mypy.nodes import (
@@ -17,6 +17,7 @@ from mypy.maptype import map_instance_to_supertype
 from mypy.expandtype import expand_type_by_instance, expand_type, freshen_function_type_vars
 from mypy.infer import infer_type_arguments
 from mypy.typevars import fill_typevars
+from mypy.plugin import Plugin, AttributeContext
 from mypy import messages
 from mypy import subtypes
 MYPY = False
@@ -36,8 +37,8 @@ def analyze_member_access(name: str,
                           not_ready_callback: Callable[[str, Context], None],
                           msg: MessageBuilder, *,
                           original_type: Type,
-                          override_info: TypeInfo = None,
-                          chk: 'mypy.checker.TypeChecker' = None) -> Type:
+                          chk: 'mypy.checker.TypeChecker',
+                          override_info: TypeInfo = None) -> Type:
     """Return the type of attribute `name` of typ.
 
     This is a general operation that supports various different variations:
@@ -77,7 +78,7 @@ def analyze_member_access(name: str,
                 assert isinstance(method, OverloadedFuncDef)
                 first_item = cast(Decorator, method.items[0])
                 return analyze_var(name, first_item.var, typ, info, node, is_lvalue, msg,
-                                   original_type, not_ready_callback)
+                                   original_type, not_ready_callback, chk=chk)
             if is_lvalue:
                 msg.cant_assign_to_method(node)
             signature = function_type(method, builtin_type('builtins.function'))
@@ -102,7 +103,7 @@ def analyze_member_access(name: str,
         # The base object has dynamic type.
         return AnyType()
     elif isinstance(typ, NoneTyp):
-        if chk and chk.should_suppress_optional_error([typ]):
+        if chk.should_suppress_optional_error([typ]):
             return AnyType()
         # The only attribute NoneType has are those it inherits from object
         return analyze_member_access(name, builtin_type('builtins.object'), node, is_lvalue,
@@ -114,7 +115,7 @@ def analyze_member_access(name: str,
         results = [analyze_member_access(name, subtype, node, is_lvalue, is_super,
                                          is_operator, builtin_type, not_ready_callback, msg,
                                          original_type=original_type, chk=chk)
-                   for subtype in typ.items]
+                   for subtype in typ.relevant_items()]
         msg.disable_type_names -= 1
         return UnionType.make_simplified_union(results)
     elif isinstance(typ, TupleType):
@@ -200,9 +201,9 @@ def analyze_member_access(name: str,
                                      is_operator, builtin_type, not_ready_callback, msg,
                                      original_type=original_type, chk=chk)
 
-    if chk and chk.should_suppress_optional_error([typ]):
+    if chk.should_suppress_optional_error([typ]):
         return AnyType()
-    return msg.has_no_attr(original_type, name, node)
+    return msg.has_no_attr(original_type, typ, name, node)
 
 
 def analyze_member_var_access(name: str, itype: Instance, info: TypeInfo,
@@ -211,7 +212,7 @@ def analyze_member_var_access(name: str, itype: Instance, info: TypeInfo,
                               not_ready_callback: Callable[[str, Context], None],
                               msg: MessageBuilder,
                               original_type: Type,
-                              chk: 'mypy.checker.TypeChecker' = None) -> Type:
+                              chk: 'mypy.checker.TypeChecker') -> Type:
     """Analyse attribute access that does not target a method.
 
     This is logically part of analyze_member_access and the arguments are similar.
@@ -226,9 +227,16 @@ def analyze_member_var_access(name: str, itype: Instance, info: TypeInfo,
         # The associated Var node of a decorator contains the type.
         v = vv.var
 
+    if isinstance(vv, TypeInfo):
+        # If the associated variable is a TypeInfo synthesize a Var node for
+        # the purposes of type checking.  This enables us to type check things
+        # like accessing class attributes on an inner class.
+        v = Var(name, type=type_object_type(vv, builtin_type))
+        v.info = info
+
     if isinstance(v, Var):
         return analyze_var(name, v, itype, info, node, is_lvalue, msg,
-                           original_type, not_ready_callback)
+                           original_type, not_ready_callback, chk=chk)
     elif isinstance(v, FuncDef):
         assert False, "Did not expect a function"
     elif not v and name not in ['__getattr__', '__setattr__', '__getattribute__']:
@@ -245,6 +253,15 @@ def analyze_member_var_access(name: str, itype: Instance, info: TypeInfo,
                     getattr_type = expand_type_by_instance(bound_method, typ)
                     if isinstance(getattr_type, CallableType):
                         return getattr_type.ret_type
+        else:
+            setattr_meth = info.get_method('__setattr__')
+            if setattr_meth and setattr_meth.info.fullname() != 'builtins.object':
+                setattr_func = function_type(setattr_meth, builtin_type('builtins.function'))
+                bound_type = bind_self(setattr_func, original_type)
+                typ = map_instance_to_supertype(itype, setattr_meth.info)
+                setattr_type = expand_type_by_instance(bound_type, typ)
+                if isinstance(setattr_type, CallableType) and len(setattr_type.arg_types) > 0:
+                    return setattr_type.arg_types[-1]
 
     if itype.type.fallback_to_any:
         return AnyType()
@@ -256,12 +273,13 @@ def analyze_member_var_access(name: str, itype: Instance, info: TypeInfo,
     else:
         if chk and chk.should_suppress_optional_error([itype]):
             return AnyType()
-        return msg.has_no_attr(original_type, name, node)
+        return msg.has_no_attr(original_type, itype, name, node)
 
 
 def analyze_var(name: str, var: Var, itype: Instance, info: TypeInfo, node: Context,
                 is_lvalue: bool, msg: MessageBuilder, original_type: Type,
-                not_ready_callback: Callable[[str, Context], None]) -> Type:
+                not_ready_callback: Callable[[str, Context], None], *,
+                chk: 'mypy.checker.TypeChecker') -> Type:
     """Analyze access to an attribute via a Var node.
 
     This is conceptually part of analyze_member_access and the arguments are similar.
@@ -280,6 +298,7 @@ def analyze_var(name: str, var: Var, itype: Instance, info: TypeInfo, node: Cont
             msg.read_only_property(name, info, node)
         if is_lvalue and var.is_classvar:
             msg.cant_assign_to_classvar(name, node)
+        result = t
         if var.is_initialized_in_class and isinstance(t, FunctionLike) and not t.is_type_obj():
             if is_lvalue:
                 if var.is_property:
@@ -294,20 +313,24 @@ def analyze_var(name: str, var: Var, itype: Instance, info: TypeInfo, node: Cont
                 # class.
                 functype = t
                 check_method_type(functype, itype, var.is_classmethod, node, msg)
-                signature = bind_self(functype, original_type)
+                signature = bind_self(functype, original_type, var.is_classmethod)
                 if var.is_property:
                     # A property cannot have an overloaded type => the cast
                     # is fine.
                     assert isinstance(signature, CallableType)
-                    return signature.ret_type
+                    result = signature.ret_type
                 else:
-                    return signature
-        return t
+                    result = signature
     else:
         if not var.is_ready:
             not_ready_callback(var.name(), node)
         # Implicit 'Any' type.
-        return AnyType()
+        result = AnyType()
+    fullname = '{}.{}'.format(var.info.fullname(), name)
+    hook = chk.plugin.get_attribute_hook(fullname)
+    if hook:
+        result = hook(AttributeContext(original_type, result, node, chk))
+    return result
 
 
 def freeze_type_vars(member_type: Type) -> None:
@@ -456,7 +479,7 @@ def add_class_tvars(t: Type, itype: Instance, is_classmethod: bool,
         tvars = [TypeVarDef(n, i + 1, [], builtin_type('builtins.object'), tv.variance)
                  for (i, n), tv in zip(enumerate(info.type_vars), info.defn.type_vars)]
         if is_classmethod:
-            t = bind_self(t, original_type)
+            t = bind_self(t, original_type, is_classmethod=True)
         return t.copy_modified(variables=tvars + t.variables)
     elif isinstance(t, Overloaded):
         return Overloaded([cast(CallableType, add_class_tvars(item, itype, is_classmethod,
@@ -580,7 +603,7 @@ def map_type_from_supertype(typ: Type, sub_info: TypeInfo,
 F = TypeVar('F', bound=FunctionLike)
 
 
-def bind_self(method: F, original_type: Type = None) -> F:
+def bind_self(method: F, original_type: Type = None, is_classmethod: bool = False) -> F:
     """Return a copy of `method`, with the type of its first parameter (usually
     self or cls) bound to original_type.
 
@@ -626,8 +649,13 @@ def bind_self(method: F, original_type: Type = None) -> F:
             # XXX value restriction as union?
             original_type = erase_to_bound(self_param_type)
 
-        typearg = infer_type_arguments([x.id for x in func.variables],
-                                       self_param_type, original_type)[0]
+        ids = [x.id for x in func.variables]
+        typearg = infer_type_arguments(ids, self_param_type, original_type)[0]
+        if (is_classmethod and isinstance(typearg, UninhabitedType)
+                and isinstance(original_type, (Instance, TypeVarType, TupleType))):
+            # In case we call a classmethod through an instance x, fallback to type(x)
+            # TODO: handle Union
+            typearg = infer_type_arguments(ids, self_param_type, TypeType(original_type))[0]
 
         def expand(target: Type) -> Type:
             assert typearg is not None
@@ -641,7 +669,7 @@ def bind_self(method: F, original_type: Type = None) -> F:
         ret_type = func.ret_type
         variables = func.variables
     if isinstance(original_type, CallableType) and original_type.is_type_obj():
-        original_type = TypeType(original_type.ret_type)
+        original_type = TypeType.make_normalized(original_type.ret_type)
     res = func.copy_modified(arg_types=arg_types,
                              arg_kinds=func.arg_kinds[1:],
                              arg_names=func.arg_names[1:],
@@ -656,5 +684,5 @@ def erase_to_bound(t: Type) -> Type:
         return t.upper_bound
     if isinstance(t, TypeType):
         if isinstance(t.item, TypeVarType):
-            return TypeType(t.item.upper_bound)
+            return TypeType.make_normalized(t.item.upper_bound)
     return t
diff --git a/mypy/constraints.py b/mypy/constraints.py
index d65a418..97b0eea 100644
--- a/mypy/constraints.py
+++ b/mypy/constraints.py
@@ -254,9 +254,6 @@ class CompleteTypeVisitor(TypeQuery[bool]):
     def __init__(self) -> None:
         super().__init__(all)
 
-    def visit_none_type(self, t: NoneTyp) -> bool:
-        return experiments.STRICT_OPTIONAL
-
     def visit_uninhabited_type(self, t: UninhabitedType) -> bool:
         return False
 
@@ -312,6 +309,8 @@ class ConstraintBuilderVisitor(TypeVisitor[List[Constraint]]):
         res = []  # type: List[Constraint]
         if isinstance(actual, CallableType) and actual.fallback is not None:
             actual = actual.fallback
+        if isinstance(actual, TypedDictType):
+            actual = actual.as_anonymous().fallback
         if isinstance(actual, Instance):
             instance = actual
             if (self.direction == SUBTYPE_OF and
diff --git a/mypy/erasetype.py b/mypy/erasetype.py
index 49035ac..910793b 100644
--- a/mypy/erasetype.py
+++ b/mypy/erasetype.py
@@ -75,7 +75,7 @@ class EraseTypeVisitor(TypeVisitor[Type]):
         return UnionType.make_simplified_union(erased_items)
 
     def visit_type_type(self, t: TypeType) -> Type:
-        return TypeType(t.item.accept(self), line=t.line)
+        return TypeType.make_normalized(t.item.accept(self), line=t.line)
 
 
 def erase_typevars(t: Type, ids_to_erase: Optional[Container[TypeVarId]] = None) -> Type:
diff --git a/mypy/errors.py b/mypy/errors.py
index 6648784..df1d7ee 100644
--- a/mypy/errors.py
+++ b/mypy/errors.py
@@ -4,7 +4,7 @@ import traceback
 from collections import OrderedDict, defaultdict
 from contextlib import contextmanager
 
-from typing import Tuple, List, TypeVar, Set, Dict, Iterator, Optional
+from typing import Tuple, List, TypeVar, Set, Dict, Iterator, Optional, cast
 
 from mypy.options import Options
 from mypy.version import __version__ as mypy_version
@@ -278,7 +278,7 @@ class Errors:
         self.add_error_info(info)
 
     def add_error_info(self, info: ErrorInfo) -> None:
-        (file, line) = info.origin
+        (file, line) = cast(Tuple[str, int], info.origin)  # see issue 1855
         if not info.blocker:  # Blockers cannot be ignored
             if file in self.ignored_lines and line in self.ignored_lines[file]:
                 # Annotation requests us to ignore all errors on this line.
diff --git a/mypy/expandtype.py b/mypy/expandtype.py
index 1830119..937ed8b 100644
--- a/mypy/expandtype.py
+++ b/mypy/expandtype.py
@@ -124,7 +124,7 @@ class ExpandTypeVisitor(TypeVisitor[Type]):
         # union of instances or Any).  Sadly we can't report errors
         # here yet.
         item = t.item.accept(self)
-        return TypeType(item)
+        return TypeType.make_normalized(item)
 
     def expand_types(self, types: Iterable[Type]) -> List[Type]:
         a = []  # type: List[Type]
diff --git a/mypy/experiments.py b/mypy/experiments.py
index 8ac437e..03a4ceb 100644
--- a/mypy/experiments.py
+++ b/mypy/experiments.py
@@ -1,3 +1,13 @@
-from typing import Optional, Tuple
+from contextlib import contextmanager
+from typing import Optional, Tuple, Iterator
 STRICT_OPTIONAL = False
 find_occurrences = None  # type: Optional[Tuple[str, str]]
+
+
+ at contextmanager
+def strict_optional_set(value: bool) -> Iterator[None]:
+    global STRICT_OPTIONAL
+    saved = STRICT_OPTIONAL
+    STRICT_OPTIONAL = value
+    yield
+    STRICT_OPTIONAL = saved
diff --git a/mypy/exprtotype.py b/mypy/exprtotype.py
index db46cfd..8325f6d 100644
--- a/mypy/exprtotype.py
+++ b/mypy/exprtotype.py
@@ -34,6 +34,7 @@ def expr_to_unanalyzed_type(expr: Expression, _parent: Optional[Expression] = No
     """
     # The `parent` paremeter is used in recursive calls to provide context for
     # understanding whether an CallableArgument is ok.
+    name = None  # type: Optional[str]
     if isinstance(expr, NameExpr):
         name = expr.name
         return UnboundType(name, line=expr.line, column=expr.column)
diff --git a/mypy/fastparse.py b/mypy/fastparse.py
index fe31e4a..58835c6 100644
--- a/mypy/fastparse.py
+++ b/mypy/fastparse.py
@@ -30,6 +30,7 @@ from mypy import defaults
 from mypy import experiments
 from mypy import messages
 from mypy.errors import Errors
+from mypy.options import Options
 
 try:
     from typed_ast import ast3
@@ -60,14 +61,12 @@ TYPE_COMMENT_AST_ERROR = 'invalid type comment or annotation'
 
 
 def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
-          pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
-          custom_typing_module: str = None) -> MypyFile:
+          options: Options = Options()) -> MypyFile:
+
     """Parse a source file, without doing any semantic analysis.
 
     Return the parse tree. If errors is not provided, raise ParseError
     on failure. Otherwise, use the errors object to report parse errors.
-
-    The pyversion (major, minor) argument determines the Python syntax variant.
     """
     raise_on_error = False
     if errors is None:
@@ -76,14 +75,16 @@ def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
     errors.set_file('<input>' if fnam is None else fnam, None)
     is_stub_file = bool(fnam) and fnam.endswith('.pyi')
     try:
-        assert pyversion[0] >= 3 or is_stub_file
-        feature_version = pyversion[1] if not is_stub_file else defaults.PYTHON3_VERSION[1]
+        if is_stub_file:
+            feature_version = defaults.PYTHON3_VERSION[1]
+        else:
+            assert options.python_version[0] >= 3
+            feature_version = options.python_version[1]
         ast = ast3.parse(source, fnam, 'exec', feature_version=feature_version)
 
-        tree = ASTConverter(pyversion=pyversion,
+        tree = ASTConverter(options=options,
                             is_stub=is_stub_file,
                             errors=errors,
-                            custom_typing_module=custom_typing_module,
                             ).visit(ast)
         tree.path = fnam
         tree.is_stub = is_stub_file
@@ -138,17 +139,15 @@ def is_no_type_check_decorator(expr: ast3.expr) -> bool:
 
 class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
     def __init__(self,
-                 pyversion: Tuple[int, int],
+                 options: Options,
                  is_stub: bool,
-                 errors: Errors,
-                 custom_typing_module: str = None) -> None:
+                 errors: Errors) -> None:
         self.class_nesting = 0
         self.imports = []  # type: List[ImportBase]
 
-        self.pyversion = pyversion
+        self.options = options
         self.is_stub = is_stub
         self.errors = errors
-        self.custom_typing_module = custom_typing_module
 
     def fail(self, msg: str, line: int, column: int) -> None:
         self.errors.report(line, column, msg)
@@ -262,9 +261,9 @@ class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
 
         For example, translate '__builtin__' in Python 2 to 'builtins'.
         """
-        if id == self.custom_typing_module:
+        if id == self.options.custom_typing_module:
             return 'typing'
-        elif id == '__builtin__' and self.pyversion[0] == 2:
+        elif id == '__builtin__' and self.options.python_version[0] == 2:
             # HACK: __builtin__ in Python 2 is aliases to builtins. However, the implementation
             #   is named __builtin__.py (there is another layer of translation elsewhere).
             return 'builtins'
@@ -343,7 +342,8 @@ class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
                 return_type = AnyType()
         else:
             arg_types = [a.type_annotation for a in args]
-            return_type = TypeConverter(self.errors, line=n.lineno).visit(n.returns)
+            return_type = TypeConverter(self.errors, line=n.returns.lineno
+                                        if n.returns else n.lineno).visit(n.returns)
 
         for arg, arg_type in zip(args, arg_types):
             self.set_type_optional(arg_type, arg.initializer)
@@ -390,7 +390,7 @@ class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
             return func_def
 
     def set_type_optional(self, type: Type, initializer: Expression) -> None:
-        if not experiments.STRICT_OPTIONAL:
+        if self.options.no_implicit_optional or not experiments.STRICT_OPTIONAL:
             return
         # Indicate that type should be wrapped in an Optional if arg is initialized to None.
         optional = isinstance(initializer, NameExpr) and initializer.name == 'None'
@@ -410,7 +410,7 @@ class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
                     self.fail(messages.DUPLICATE_TYPE_SIGNATURES, arg.lineno, arg.col_offset)
                 arg_type = None
                 if arg.annotation is not None:
-                    arg_type = TypeConverter(self.errors, line=line).visit(arg.annotation)
+                    arg_type = TypeConverter(self.errors, line=arg.lineno).visit(arg.annotation)
                 elif arg.type_comment is not None:
                     arg_type = parse_type_comment(arg.type_comment, arg.lineno, self.errors)
             return Argument(Var(arg.arg), arg_type, self.visit(default), kind)
@@ -467,12 +467,15 @@ class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
             metaclass = stringify_name(metaclass_arg.value)
             if metaclass is None:
                 metaclass = '<error>'  # To be reported later
+        keywords = [(kw.arg, self.visit(kw.value))
+                    for kw in n.keywords]
 
         cdef = ClassDef(n.name,
                         self.as_block(n.body, n.lineno),
                         None,
                         self.translate_expr_list(n.bases),
-                        metaclass=metaclass)
+                        metaclass=metaclass,
+                        keywords=keywords)
         cdef.decorators = self.translate_expr_list(n.decorator_list)
         self.class_nesting -= 1
         return cdef
@@ -845,38 +848,48 @@ class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
     # Str(string s)
     @with_line
     def visit_Str(self, n: ast3.Str) -> Union[UnicodeExpr, StrExpr]:
-        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)
+        # 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)
 
     # Only available with typed_ast >= 0.6.2
     if hasattr(ast3, 'JoinedStr'):
         # JoinedStr(expr* values)
         @with_line
         def visit_JoinedStr(self, n: ast3.JoinedStr) -> Expression:
-            arg_count = len(n.values)
-            format_string = StrExpr('{}' * arg_count)
-            format_string.set_line(n.lineno, n.col_offset)
-            format_method = MemberExpr(format_string, 'format')
-            format_method.set_line(format_string)
-            format_args = self.translate_expr_list(n.values)
-            format_arg_kinds = [ARG_POS] * arg_count
-            result_expression = CallExpr(format_method,
-                                         format_args,
-                                         format_arg_kinds)
+            # Each of n.values is a str or FormattedValue; we just concatenate
+            # them all using ''.join.
+            empty_string = StrExpr('')
+            empty_string.set_line(n.lineno, n.col_offset)
+            strs_to_join = ListExpr(self.translate_expr_list(n.values))
+            strs_to_join.set_line(empty_string)
+            join_method = MemberExpr(empty_string, 'join')
+            join_method.set_line(empty_string)
+            result_expression = CallExpr(join_method,
+                                         [strs_to_join],
+                                         [ARG_POS])
             return result_expression
 
         # FormattedValue(expr value)
         @with_line
         def visit_FormattedValue(self, n: ast3.FormattedValue) -> Expression:
-            return self.visit(n.value)
+            # A FormattedValue is a component of a JoinedStr, or it can exist
+            # on its own. We translate them to individual '{}'.format(value)
+            # calls -- we don't bother with the conversion/format_spec fields.
+            exp = self.visit(n.value)
+            exp.set_line(n.lineno, n.col_offset)
+            format_string = StrExpr('{}')
+            format_string.set_line(n.lineno, n.col_offset)
+            format_method = MemberExpr(format_string, 'format')
+            format_method.set_line(format_string)
+            result_expression = CallExpr(format_method,
+                                         [exp],
+                                         [ARG_POS])
+            return result_expression
 
     # Bytes(bytes s)
     @with_line
@@ -884,11 +897,7 @@ class ASTConverter(ast3.NodeTransformer):  # type: ignore  # typeshed PR #931
         # 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)
+        return BytesExpr(contents)
 
     # NameConstant(singleton value)
     def visit_NameConstant(self, n: ast3.NameConstant) -> NameExpr:
diff --git a/mypy/fastparse2.py b/mypy/fastparse2.py
index b7d5e9d..109dfe4 100644
--- a/mypy/fastparse2.py
+++ b/mypy/fastparse2.py
@@ -38,11 +38,11 @@ from mypy.nodes import (
 from mypy.types import (
     Type, CallableType, AnyType, UnboundType, EllipsisType
 )
-from mypy import defaults
 from mypy import experiments
 from mypy import messages
 from mypy.errors import Errors
 from mypy.fastparse import TypeConverter, parse_type_comment
+from mypy.options import Options
 
 try:
     from typed_ast import ast27
@@ -74,14 +74,11 @@ 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,
-          custom_typing_module: str = None) -> MypyFile:
+          options: Options = Options()) -> MypyFile:
     """Parse a source file, without doing any semantic analysis.
 
     Return the parse tree. If errors is not provided, raise ParseError
     on failure. Otherwise, use the errors object to report parse errors.
-
-    The pyversion (major, minor) argument determines the Python syntax variant.
     """
     raise_on_error = False
     if errors is None:
@@ -90,12 +87,11 @@ def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
     errors.set_file('<input>' if fnam is None else fnam, None)
     is_stub_file = bool(fnam) and fnam.endswith('.pyi')
     try:
-        assert pyversion[0] < 3 and not is_stub_file
+        assert options.python_version[0] < 3 and not is_stub_file
         ast = ast27.parse(source, fnam, 'exec')
-        tree = ASTConverter(pyversion=pyversion,
+        tree = ASTConverter(options=options,
                             is_stub=is_stub_file,
                             errors=errors,
-                            custom_typing_module=custom_typing_module,
                             ).visit(ast)
         assert isinstance(tree, MypyFile)
         tree.path = fnam
@@ -137,17 +133,15 @@ def is_no_type_check_decorator(expr: ast27.expr) -> bool:
 
 class ASTConverter(ast27.NodeTransformer):
     def __init__(self,
-                 pyversion: Tuple[int, int],
+                 options: Options,
                  is_stub: bool,
-                 errors: Errors,
-                 custom_typing_module: str = None) -> None:
+                 errors: Errors) -> None:
         self.class_nesting = 0
         self.imports = []  # type: List[ImportBase]
 
-        self.pyversion = pyversion
+        self.options = options
         self.is_stub = is_stub
         self.errors = errors
-        self.custom_typing_module = custom_typing_module
 
     def fail(self, msg: str, line: int, column: int) -> None:
         self.errors.report(line, column, msg)
@@ -262,9 +256,9 @@ class ASTConverter(ast27.NodeTransformer):
 
         For example, translate '__builtin__' in Python 2 to 'builtins'.
         """
-        if id == self.custom_typing_module:
+        if id == self.options.custom_typing_module:
             return 'typing'
-        elif id == '__builtin__' and self.pyversion[0] == 2:
+        elif id == '__builtin__':
             # HACK: __builtin__ in Python 2 is aliases to builtins. However, the implementation
             #   is named __builtin__.py (there is another layer of translation elsewhere).
             return 'builtins'
@@ -370,7 +364,7 @@ class ASTConverter(ast27.NodeTransformer):
             return func_def
 
     def set_type_optional(self, type: Type, initializer: Expression) -> None:
-        if not experiments.STRICT_OPTIONAL:
+        if self.options.no_implicit_optional or not experiments.STRICT_OPTIONAL:
             return
         # Indicate that type should be wrapped in an Optional if arg is initialized to None.
         optional = isinstance(initializer, NameExpr) and initializer.name == 'None'
@@ -870,16 +864,9 @@ class ASTConverter(ast27.NodeTransformer):
             # 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)[2:-1]
-
-            if self.pyversion[0] >= 3:
-                return BytesExpr(contents)
-            else:
-                return StrExpr(contents)
+            return StrExpr(contents)
         else:
-            if self.pyversion[0] >= 3 or self.is_stub:
-                return StrExpr(s.s)
-            else:
-                return UnicodeExpr(s.s)
+            return UnicodeExpr(s.s)
 
     # Ellipsis
     def visit_Ellipsis(self, n: ast27.Ellipsis) -> EllipsisExpr:
diff --git a/mypy/fixup.py b/mypy/fixup.py
index 5854797..5cb1188 100644
--- a/mypy/fixup.py
+++ b/mypy/fixup.py
@@ -5,8 +5,8 @@ from typing import Any, Dict, Optional
 from mypy.nodes import (
     MypyFile, SymbolNode, SymbolTable, SymbolTableNode,
     TypeInfo, FuncDef, OverloadedFuncDef, Decorator, Var,
-    TypeVarExpr, ClassDef,
-    LDEF, MDEF, GDEF
+    TypeVarExpr, ClassDef, Block,
+    LDEF, MDEF, GDEF, TYPE_ALIAS
 )
 from mypy.types import (
     CallableType, EllipsisType, Instance, Overloaded, TupleType, TypedDictType,
@@ -88,8 +88,14 @@ class NodeFixer(NodeVisitor[None]):
                     if stnode is not None:
                         value.node = stnode.node
                         value.type_override = stnode.type_override
+                        value.alias_tvars = stnode.alias_tvars or []
                     elif not self.quick_and_dirty:
                         assert stnode is not None, "Could not find cross-ref %s" % (cross_ref,)
+                    else:
+                        # We have a missing crossref in quick mode, need to put something
+                        value.node = stale_info()
+                        if value.kind == TYPE_ALIAS:
+                            value.type_override = Instance(stale_info(), [])
             else:
                 if isinstance(value.node, TypeInfo):
                     # TypeInfo has no accept().  TODO: Add it?
@@ -162,6 +168,10 @@ class TypeFixer(TypeVisitor[None]):
             for base in inst.type.bases:
                 if base.type is NOT_READY:
                     base.accept(self)
+        else:
+            # Looks like a missing TypeInfo in quick mode, put something there
+            assert self.quick_and_dirty, "Should never get here in normal mode"
+            inst.type = stale_info()
         for a in inst.args:
             a.accept(self)
 
@@ -182,6 +192,9 @@ class TypeFixer(TypeVisitor[None]):
                 for val in v.values:
                     val.accept(self)
             v.upper_bound.accept(self)
+        for arg in ct.bound_args:
+            if arg:
+                arg.accept(self)
 
     def visit_overloaded(self, t: Overloaded) -> None:
         for ct in t.items():
@@ -267,12 +280,23 @@ def lookup_qualified_stnode(modules: Dict[str, MypyFile], name: str,
             return None
         key = rest.pop()
         if key not in names:
+            if not quick_and_dirty:
+                assert key in names, "Cannot find %s for %s" % (key, name)
             return None
-        elif not quick_and_dirty:
-            assert key in names, "Cannot find %s for %s" % (key, name)
         stnode = names[key]
         if not rest:
             return stnode
         node = stnode.node
         assert isinstance(node, TypeInfo)
         names = node.names
+
+
+def stale_info() -> TypeInfo:
+    suggestion = "<stale cache: consider running mypy without --quick>"
+    dummy_def = ClassDef(suggestion, Block([]))
+    dummy_def.fullname = suggestion
+
+    info = TypeInfo(SymbolTable(), dummy_def, "<stale>")
+    info.mro = [info]
+    info.bases = []
+    return info
diff --git a/mypy/join.py b/mypy/join.py
index 586d281..132017e 100644
--- a/mypy/join.py
+++ b/mypy/join.py
@@ -15,7 +15,7 @@ from mypy.subtypes import is_subtype, is_equivalent, is_subtype_ignoring_tvars,
 from mypy import experiments
 
 
-def join_simple(declaration: Type, s: Type, t: Type) -> Type:
+def join_simple(declaration: Optional[Type], s: Type, t: Type) -> Type:
     """Return a simple least upper bound given the declared type."""
 
     if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):
@@ -228,11 +228,15 @@ class TypeJoinVisitor(TypeVisitor[Type]):
             items = OrderedDict([
                 (item_name, s_item_type)
                 for (item_name, s_item_type, t_item_type) in self.s.zip(t)
-                if is_equivalent(s_item_type, t_item_type)
+                if (is_equivalent(s_item_type, t_item_type) and
+                    (item_name in t.required_keys) == (item_name in self.s.required_keys))
             ])
             mapping_value_type = join_type_list(list(items.values()))
             fallback = self.s.create_anonymous_fallback(value_type=mapping_value_type)
-            return TypedDictType(items, fallback)
+            # We need to filter by items.keys() since some required keys present in both t and
+            # self.s might be missing from the join if the types are incompatible.
+            required_keys = set(items.keys()) & t.required_keys & self.s.required_keys
+            return TypedDictType(items, required_keys, fallback)
         elif isinstance(self.s, Instance):
             return join_instances(self.s, t.fallback)
         else:
@@ -245,7 +249,7 @@ class TypeJoinVisitor(TypeVisitor[Type]):
 
     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)
+            return TypeType.make_normalized(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:
diff --git a/mypy/main.py b/mypy/main.py
index a551167..4e59f68 100644
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -24,7 +24,11 @@ from mypy.version import __version__
 PY_EXTENSIONS = tuple(PYTHON_EXTENSIONS)
 
 
-def main(script_path: str, args: List[str] = None) -> None:
+class InvalidPackageName(Exception):
+    """Exception indicating that a package name was invalid."""
+
+
+def main(script_path: Optional[str], args: List[str] = None) -> None:
     """Main entry point to the type checker.
 
     Args:
@@ -93,6 +97,24 @@ def type_check_only(sources: List[BuildSource], bin_dir: str, options: Options)
                        options=options)
 
 
+disallow_any_options = ['unimported', 'expr', 'unannotated', 'decorated', 'explicit', 'generics']
+
+
+def disallow_any_argument_type(raw_options: str) -> List[str]:
+    if not raw_options:
+        # empty string disables all options
+        return []
+    flag_options = [o.strip() for o in raw_options.split(',')]
+    for option in flag_options:
+        if option not in disallow_any_options:
+            formatted_valid_options = ', '.join(
+                "'{}'".format(o) for o in disallow_any_options)
+            message = "Invalid '--disallow-any' option '{}' (valid options are: {}).".format(
+                option, formatted_valid_options)
+            raise argparse.ArgumentError(None, message)
+    return flag_options
+
+
 FOOTER = """environment variables:
 MYPYPATH     additional module search path"""
 
@@ -190,10 +212,14 @@ def process_options(args: List[str],
                             ) -> None:
         if inverse is None:
             inverse = invert_flag_name(flag)
+
+        if help is not argparse.SUPPRESS:
+            help += " (inverse: {})".format(inverse)
+
         arg = parser.add_argument(flag,  # type: ignore  # incorrect stub for add_argument
                                   action='store_false' if default else 'store_true',
                                   dest=dest,
-                                  help=help + " (inverse: {})".format(inverse))
+                                  help=help)
         dest = arg.dest
         arg = parser.add_argument(inverse,  # type: ignore  # incorrect stub for add_argument
                                   action='store_true' if default else 'store_false',
@@ -222,6 +248,10 @@ def process_options(args: List[str],
                         help="silently ignore imports of missing modules")
     parser.add_argument('--follow-imports', choices=['normal', 'silent', 'skip', 'error'],
                         default='normal', help="how to treat imports (default normal)")
+    parser.add_argument('--disallow-any', type=disallow_any_argument_type, default=[],
+                        metavar='{{{}}}'.format(', '.join(disallow_any_options)),
+                        help="disallow various types of Any in a module. Takes a comma-separated "
+                             "list of options (defaults to all options disabled)")
     add_invertible_flag('--disallow-untyped-calls', default=False, strict_flag=True,
                         help="disallow calling functions without type annotations"
                         " from functions with type annotations")
@@ -247,14 +277,20 @@ def process_options(args: List[str],
     add_invertible_flag('--show-error-context', default=False,
                         dest='show_error_context',
                         help='Precede errors with "note:" messages explaining context')
+    add_invertible_flag('--no-implicit-optional', default=False, strict_flag=True,
+                        help="don't assume arguments with default values of None are Optional")
     parser.add_argument('-i', '--incremental', action='store_true',
-                        help="enable module cache")
+                        help="enable module cache, (inverse: --no-incremental)")
+    parser.add_argument('--no-incremental', action='store_false', dest='incremental',
+                        help=argparse.SUPPRESS)
     parser.add_argument('--quick-and-dirty', action='store_true',
                         help="use cache even if dependencies out of date "
                         "(implies --incremental)")
     parser.add_argument('--cache-dir', action='store', metavar='DIR',
                         help="store module cache info in the given folder in incremental mode "
                         "(defaults to '{}')".format(defaults.CACHE_DIR))
+    parser.add_argument('--skip-version-check', action='store_true',
+                        help="allow using cache written by older mypy version")
     add_invertible_flag('--strict-optional', default=False, strict_flag=True,
                         help="enable experimental strict Optional checks")
     parser.add_argument('--strict-optional-whitelist', metavar='GLOB', nargs='*',
@@ -287,13 +323,10 @@ def process_options(args: List[str],
         ", ".join(strict_flag_names))
     parser.add_argument('--strict', action='store_true', dest='special-opts:strict',
                         help=strict_help)
+    parser.add_argument('--shadow-file', nargs=2, metavar=('SOURCE_FILE', 'SHADOW_FILE'),
+                        dest='shadow_file',
+                        help='Typecheck SHADOW_FILE in place of SOURCE_FILE.')
     # hidden options
-    # --shadow-file a.py tmp.py will typecheck tmp.py in place of a.py.
-    # Useful for tools to make transformations to a file to get more
-    # information from a mypy run without having to change the file in-place
-    # (e.g. by adding a call to reveal_type).
-    parser.add_argument('--shadow-file', metavar='PATH', nargs=2, dest='shadow_file',
-                        help=argparse.SUPPRESS)
     # --debug-cache will disable any cache-related compressions/optimizations,
     # which will make the cache writing process output pretty-printed JSON (which
     # is easier to debug).
@@ -350,7 +383,7 @@ def process_options(args: List[str],
     parser.parse_args(args, dummy)
     config_file = dummy.config_file
     if config_file is not None and not os.path.exists(config_file):
-        parser.error("Cannot file config file '%s'" % config_file)
+        parser.error("Cannot find config file '%s'" % config_file)
 
     # Parse config file first, so command line can override.
     options = Options()
@@ -399,6 +432,9 @@ def process_options(args: List[str],
         print("Warning: --no-fast-parser no longer has any effect.  The fast parser "
               "is now mypy's default and only parser.")
 
+    if 'unannotated' in options.disallow_any:
+        options.disallow_untyped_defs = True
+
     # Check for invalid argument combinations.
     if require_targets:
         code_methods = sum(bool(c) for c in [special_opts.modules,
@@ -457,9 +493,15 @@ def process_options(args: List[str],
         targets = []
         for f in special_opts.files:
             if f.endswith(PY_EXTENSIONS):
-                targets.append(BuildSource(f, crawl_up(f)[1], None))
+                try:
+                    targets.append(BuildSource(f, crawl_up(f)[1], None))
+                except InvalidPackageName as e:
+                    fail(str(e))
             elif os.path.isdir(f):
-                sub_targets = expand_dir(f)
+                try:
+                    sub_targets = expand_dir(f)
+                except InvalidPackageName as e:
+                    fail(str(e))
                 if not sub_targets:
                     fail("There are no .py[i] files in directory '{}'"
                          .format(f))
@@ -526,10 +568,14 @@ def crawl_up(arg: str) -> Tuple[str, str]:
         dir, base = os.path.split(dir)
         if not base:
             break
+        # Ensure that base is a valid python module name
+        if not base.isidentifier():
+            raise InvalidPackageName('{} is not a valid Python package name'.format(base))
         if mod == '__init__' or not mod:
             mod = base
         else:
             mod = base + '.' + mod
+
     return dir, mod
 
 
@@ -570,9 +616,11 @@ config_types = {
     'custom_typeshed_dir': str,
     'mypy_path': lambda s: [p.strip() for p in re.split('[,:]', s)],
     'junit_xml': str,
+    'disallow_any': disallow_any_argument_type,
     # These two are for backwards compatibility
     'silent_imports': bool,
     'almost_silent': bool,
+    'plugins': lambda s: [p.strip() for p in s.split(',')],
 }
 
 SHARED_CONFIG_FILES = ('setup.cfg',)
@@ -684,6 +732,8 @@ def parse_section(prefix: str, template: Options,
         except ValueError as err:
             print("%s: %s: %s" % (prefix, key, err), file=sys.stderr)
             continue
+        if key == 'disallow_any':
+            results['disallow_untyped_defs'] = v and 'unannotated' in v
         if key == 'silent_imports':
             print("%s: silent_imports has been replaced by "
                   "ignore_missing_imports=True; follow_imports=skip" % prefix, file=sys.stderr)
diff --git a/mypy/meet.py b/mypy/meet.py
index e32997f..a3b59c2 100644
--- a/mypy/meet.py
+++ b/mypy/meet.py
@@ -31,7 +31,7 @@ def narrow_declared_type(declared: Type, narrowed: Type) -> Type:
         return declared
     if isinstance(declared, UnionType):
         return UnionType.make_simplified_union([narrow_declared_type(x, narrowed)
-                                                for x in declared.items])
+                                                for x in declared.relevant_items()])
     elif not is_overlapping_types(declared, narrowed, use_promotions=True):
         if experiments.STRICT_OPTIONAL:
             return UninhabitedType()
@@ -39,7 +39,7 @@ def narrow_declared_type(declared: Type, narrowed: Type) -> Type:
             return NoneTyp()
     elif isinstance(narrowed, UnionType):
         return UnionType.make_simplified_union([narrow_declared_type(declared, x)
-                                                for x in narrowed.items])
+                                                for x in narrowed.relevant_items()])
     elif isinstance(narrowed, AnyType):
         return narrowed
     elif isinstance(declared, (Instance, TupleType)):
@@ -84,6 +84,10 @@ def is_overlapping_types(t: Type, s: Type, use_promotions: bool = False) -> bool
         t = t.erase_to_union_or_bound()
     if isinstance(s, TypeVarType):
         s = s.erase_to_union_or_bound()
+    if isinstance(t, TypedDictType):
+        t = t.as_anonymous().fallback
+    if isinstance(s, TypedDictType):
+        s = s.as_anonymous().fallback
     if isinstance(t, Instance):
         if isinstance(s, Instance):
             # Consider two classes non-disjoint if one is included in the mro
@@ -99,10 +103,10 @@ def is_overlapping_types(t: Type, s: Type, use_promotions: bool = False) -> bool
             return t.type in s.type.mro or s.type in t.type.mro
     if isinstance(t, UnionType):
         return any(is_overlapping_types(item, s)
-                   for item in t.items)
+                   for item in t.relevant_items())
     if isinstance(s, UnionType):
         return any(is_overlapping_types(t, item)
-                   for item in s.items)
+                   for item in s.relevant_items())
     if isinstance(t, TypeType) and isinstance(s, TypeType):
         # If both types are TypeType, compare their inner types.
         return is_overlapping_types(t.item, s.item, use_promotions)
@@ -252,8 +256,9 @@ class TypeMeetVisitor(TypeVisitor[Type]):
 
     def visit_typeddict_type(self, t: TypedDictType) -> Type:
         if isinstance(self.s, TypedDictType):
-            for (_, l, r) in self.s.zip(t):
-                if not is_equivalent(l, r):
+            for (name, l, r) in self.s.zip(t):
+                if (not is_equivalent(l, r) or
+                        (name in t.required_keys) != (name in self.s.required_keys)):
                     return self.default(self.s)
             item_list = []  # type: List[Tuple[str, Type]]
             for (item_name, s_item_type, t_item_type) in self.s.zipall(t):
@@ -266,7 +271,8 @@ class TypeMeetVisitor(TypeVisitor[Type]):
             items = OrderedDict(item_list)
             mapping_value_type = join_type_list(list(items.values()))
             fallback = self.s.create_anonymous_fallback(value_type=mapping_value_type)
-            return TypedDictType(items, fallback)
+            required_keys = t.required_keys | self.s.required_keys
+            return TypedDictType(items, required_keys, fallback)
         else:
             return self.default(self.s)
 
@@ -278,7 +284,7 @@ class TypeMeetVisitor(TypeVisitor[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)
+                typ = TypeType.make_normalized(typ, line=t.line)
             return typ
         elif isinstance(self.s, Instance) and self.s.type.fullname() == 'builtins.type':
             return t
diff --git a/mypy/messages.py b/mypy/messages.py
index f6cadf0..6375f4d 100644
--- a/mypy/messages.py
+++ b/mypy/messages.py
@@ -6,8 +6,9 @@ improve code clarity and to simplify localization (in the future)."""
 import re
 import difflib
 
-from typing import cast, List, Dict, Any, Sequence, Iterable, Tuple
+from typing import cast, List, Dict, Any, Sequence, Iterable, Tuple, Optional
 
+from mypy.erasetype import erase_type
 from mypy.errors import Errors
 from mypy.types import (
     Type, CallableType, Instance, TypeVarType, TupleType, TypedDictType,
@@ -16,7 +17,8 @@ from mypy.types import (
 )
 from mypy.nodes import (
     TypeInfo, Context, MypyFile, op_methods, FuncDef, reverse_type_aliases,
-    ARG_POS, ARG_OPT, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2
+    ARG_POS, ARG_OPT, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2,
+    ReturnStmt, NameExpr, Var
 )
 
 
@@ -52,8 +54,7 @@ INCOMPATIBLE_TYPES_IN_YIELD = 'Incompatible types in yield'
 INCOMPATIBLE_TYPES_IN_YIELD_FROM = 'Incompatible types in "yield from"'
 INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION = 'Incompatible types in string interpolation'
 MUST_HAVE_NONE_RETURN_TYPE = 'The return type of "{}" must be None'
-TUPLE_INDEX_MUST_BE_AN_INT_LITERAL = 'Tuple index must be an integer literal'
-TUPLE_SLICE_MUST_BE_AN_INT_LITERAL = 'Tuple slice must be an integer literal'
+INVALID_TUPLE_INDEX_TYPE = 'Invalid tuple index type'
 TUPLE_INDEX_OUT_OF_RANGE = 'Tuple index out of range'
 NEED_ANNOTATION_FOR_VAR = 'Need type annotation for variable'
 ITERABLE_EXPECTED = 'Iterable expected'
@@ -81,12 +82,16 @@ KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE = \
 ALL_MUST_BE_SEQ_STR = 'Type of __all__ must be {}, not {}'
 INVALID_TYPEDDICT_ARGS = \
     'Expected keyword arguments, {...}, or dict(...) in TypedDict constructor'
-TYPEDDICT_ITEM_NAME_MUST_BE_STRING_LITERAL = \
-    'Expected TypedDict item name to be string literal'
+TYPEDDICT_KEY_MUST_BE_STRING_LITERAL = \
+    'Expected TypedDict key to be string literal'
 MALFORMED_ASSERT = 'Assertion is always true, perhaps remove parentheses?'
 NON_BOOLEAN_IN_CONDITIONAL = 'Condition must be a boolean'
 DUPLICATE_TYPE_SIGNATURES = 'Function has duplicate type signatures'
 GENERIC_INSTANCE_VAR_CLASS_ACCESS = 'Access to generic instance variables via class is ambiguous'
+CANNOT_ISINSTANCE_TYPEDDICT = 'Cannot use isinstance() with a TypedDict type'
+CANNOT_ISINSTANCE_NEWTYPE = 'Cannot use isinstance() with a NewType type'
+BARE_GENERIC = 'Missing type parameters for generic type'
+IMPLICIT_GENERIC_ANY_BUILTIN = 'Implicit generic "Any". Use \'{}\' and specify generic parameters'
 
 ARG_CONSTRUCTOR_NAMES = {
     ARG_POS: "Arg",
@@ -190,13 +195,8 @@ class MessageBuilder:
             if func.is_type_obj():
                 # The type of a type object type can be derived from the
                 # return type (this always works).
-                itype = cast(Instance, func.items()[0].ret_type)
-                result = self.format(itype)
-                if verbosity >= 1:
-                    # In some contexts we want to be explicit about the distinction
-                    # between type X and the type of type object X.
-                    result += ' (type object)'
-                return result
+                return self.format(TypeType.make_normalized(erase_type(func.items()[0].ret_type)),
+                                   verbosity)
             elif isinstance(func, CallableType):
                 return_type = strip_quotes(self.format(func.ret_type))
                 if func.is_ellipsis_args:
@@ -300,12 +300,15 @@ class MessageBuilder:
                 return 'tuple(length {})'.format(len(items))
         elif isinstance(typ, TypedDictType):
             # If the TypedDictType is named, return the name
-            if typ.fallback.type.fullname() != 'typing.Mapping':
+            if not typ.is_anonymous():
                 return self.format_simple(typ.fallback)
             items = []
             for (item_name, item_type) in typ.items.items():
-                items.append('{}={}'.format(item_name, strip_quotes(self.format(item_type))))
-            s = '"TypedDict({})"'.format(', '.join(items))
+                modifier = '' if item_name in typ.required_keys else '?'
+                items.append('{!r}{}: {}'.format(item_name,
+                                                 modifier,
+                                                 strip_quotes(self.format(item_type))))
+            s = '"TypedDict({{{}}})"'.format(', '.join(items))
             return s
         elif isinstance(typ, UnionType):
             # Only print Unions as Optionals if the Optional wouldn't have to contain another Union
@@ -366,72 +369,84 @@ class MessageBuilder:
     # get some information as arguments, and they build an error message based
     # on them.
 
-    def has_no_attr(self, typ: Type, member: str, context: Context) -> Type:
+    def has_no_attr(self, original_type: Type, typ: Type, member: str, context: Context) -> Type:
         """Report a missing or non-accessible member.
 
-        The type argument is the base type. If member corresponds to
-        an operator, use the corresponding operator name in the
-        messages. Return type Any.
+        original_type is the top-level type on which the error occurred.
+        typ is the actual type that is missing the member. These can be
+        different, e.g., in a union, original_type will be the union and typ
+        will be the specific item in the union that does not have the member
+        attribute.
+
+        If member corresponds to an operator, use the corresponding operator
+        name in the messages. Return type Any.
         """
-        if (isinstance(typ, Instance) and
-                typ.type.has_readable_member(member)):
+        if (isinstance(original_type, Instance) and
+                original_type.type.has_readable_member(member)):
             self.fail('Member "{}" is not assignable'.format(member), context)
         elif member == '__contains__':
             self.fail('Unsupported right operand type for in ({})'.format(
-                self.format(typ)), context)
+                self.format(original_type)), context)
         elif member in op_methods.values():
             # Access to a binary operator member (e.g. _add). This case does
             # not handle indexing operations.
             for op, method in op_methods.items():
                 if method == member:
-                    self.unsupported_left_operand(op, typ, context)
+                    self.unsupported_left_operand(op, original_type, context)
                     break
         elif member == '__neg__':
             self.fail('Unsupported operand type for unary - ({})'.format(
-                self.format(typ)), context)
+                self.format(original_type)), context)
         elif member == '__pos__':
             self.fail('Unsupported operand type for unary + ({})'.format(
-                self.format(typ)), context)
+                self.format(original_type)), context)
         elif member == '__invert__':
             self.fail('Unsupported operand type for ~ ({})'.format(
-                self.format(typ)), context)
+                self.format(original_type)), context)
         elif member == '__getitem__':
             # Indexed get.
             # TODO: Fix this consistently in self.format
-            if isinstance(typ, CallableType) and typ.is_type_obj():
+            if isinstance(original_type, CallableType) and original_type.is_type_obj():
                 self.fail('The type {} is not generic and not indexable'.format(
-                    self.format(typ)), context)
+                    self.format(original_type)), context)
             else:
                 self.fail('Value of type {} is not indexable'.format(
-                    self.format(typ)), context)
+                    self.format(original_type)), context)
         elif member == '__setitem__':
             # Indexed set.
             self.fail('Unsupported target for indexed assignment', context)
         elif member == '__call__':
-            if isinstance(typ, Instance) and (typ.type.fullname() == 'builtins.function'):
+            if isinstance(original_type, Instance) and \
+                    (original_type.type.fullname() == 'builtins.function'):
                 # "'function' not callable" is a confusing error message.
                 # Explain that the problem is that the type of the function is not known.
                 self.fail('Cannot call function of unknown type', context)
             else:
-                self.fail('{} not callable'.format(self.format(typ)), context)
+                self.fail('{} not callable'.format(self.format(original_type)), context)
         else:
             # The non-special case: a missing ordinary attribute.
             if not self.disable_type_names:
                 failed = False
-                if isinstance(typ, Instance) and typ.type.names:
-                    alternatives = set(typ.type.names.keys())
+                if isinstance(original_type, Instance) and original_type.type.names:
+                    alternatives = set(original_type.type.names.keys())
                     matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives]
                     matches.extend(best_matches(member, alternatives)[:3])
                     if matches:
                         self.fail('{} has no attribute "{}"; maybe {}?'.format(
-                            self.format(typ), member, pretty_or(matches)), context)
+                            self.format(original_type), member, pretty_or(matches)), context)
                         failed = True
                 if not failed:
-                    self.fail('{} has no attribute "{}"'.format(self.format(typ),
+                    self.fail('{} has no attribute "{}"'.format(self.format(original_type),
                                                                 member), context)
-            else:
-                self.fail('Some element of union has no attribute "{}"'.format(
-                    member), context)
+            elif isinstance(original_type, UnionType):
+                # The checker passes "object" in lieu of "None" for attribute
+                # checks, so we manually convert it back.
+                typ_format = self.format(typ)
+                if typ_format == '"object"' and \
+                        any(type(item) == NoneTyp for item in original_type.items):
+                    typ_format = '"None"'
+                self.fail('Item {} of {} has no attribute "{}"'.format(
+                    typ_format, self.format(original_type), member), context)
         return AnyType()
 
     def unsupported_operand_types(self, op: str, left_type: Any,
@@ -529,13 +544,13 @@ class MessageBuilder:
             name = callee.name[1:-1]
             n -= 1
             msg = '{} item {} has incompatible type {}'.format(
-                name.title(), n, self.format_simple(arg_type))
+                name.title(), n, self.format(arg_type))
         elif callee.name == '<dict>':
             name = callee.name[1:-1]
             n -= 1
             key_type, value_type = cast(TupleType, arg_type).items
             msg = '{} entry {} has incompatible type {}: {}'.format(
-                name.title(), n, self.format_simple(key_type), self.format_simple(value_type))
+                name.title(), n, self.format(key_type), self.format(value_type))
         elif callee.name == '<list-comprehension>':
             msg = 'List comprehension has incompatible type List[{}]'.format(
                 strip_quotes(self.format(arg_type)))
@@ -550,7 +565,7 @@ class MessageBuilder:
                 self.format(callee.arg_types[n - 1]))
         elif callee.name == '<generator>':
             msg = 'Generator has incompatible item type {}'.format(
-                self.format_simple(arg_type))
+                self.format(arg_type))
         else:
             try:
                 expected_type = callee.arg_types[m - 1]
@@ -580,7 +595,8 @@ class MessageBuilder:
             else:
                 msg = 'Missing positional arguments'
             if callee.name and diff and all(d is not None for d in diff):
-                msg += ' "{}" in call to {}'.format('", "'.join(diff), callee.name)
+                msg += ' "{}" in call to {}'.format('", "'.join(cast(List[str], diff)),
+                                                    callee.name)
         else:
             msg = 'Too few arguments'
             if callee.name:
@@ -612,13 +628,11 @@ class MessageBuilder:
         if callee.name:
             msg += ' for {}'.format(callee.name)
         self.fail(msg, context)
-        if callee.definition:
-            fullname = callee.definition.fullname()
-            if fullname is not None and '.' in fullname:
-                module_name = fullname.rsplit('.', 1)[0]
-                path = self.modules[module_name].path
-                self.note('{} defined here'.format(callee.name), callee.definition,
-                          file=path, origin=context)
+        module = find_defining_module(self.modules, callee)
+        if module:
+            assert callee.definition is not None
+            self.note('{} defined here'.format(callee.name), callee.definition,
+                      file=module.path, origin=context)
 
     def duplicate_argument_value(self, callee: CallableType, index: int,
                                  context: Context) -> None:
@@ -628,9 +642,11 @@ class MessageBuilder:
 
     def does_not_return_value(self, callee_type: Type, context: Context) -> None:
         """Report an error about use of an unusable type."""
-        if isinstance(callee_type, FunctionLike) and callee_type.get_name() is not None:
-            self.fail('{} does not return a value'.format(
-                capitalize(callee_type.get_name())), context)
+        name = None  # type: Optional[str]
+        if isinstance(callee_type, FunctionLike):
+            name = callee_type.get_name()
+        if name is not None:
+            self.fail('{} does not return a value'.format(capitalize(name)), context)
         else:
             self.fail('Function does not return a value', context)
 
@@ -735,12 +751,16 @@ class MessageBuilder:
     def invalid_var_arg(self, typ: Type, context: Context) -> None:
         self.fail('List or tuple expected as variable arguments', context)
 
-    def invalid_keyword_var_arg(self, typ: Type, context: Context) -> None:
-        if isinstance(typ, Instance) and (typ.type.fullname() == 'builtins.dict'):
+    def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None:
+        if isinstance(typ, Instance) and is_mapping:
             self.fail('Keywords must be strings', context)
         else:
-            self.fail('Argument after ** must be a dictionary',
-                      context)
+            suffix = ''
+            if isinstance(typ, Instance):
+                suffix = ', not {}'.format(self.format(typ))
+            self.fail(
+                'Argument after ** must be a mapping{}'.format(suffix),
+                context)
 
     def undefined_in_superclass(self, member: str, context: Context) -> None:
         self.fail('"{}" undefined in superclass'.format(member), context)
@@ -863,31 +883,84 @@ class MessageBuilder:
     def redundant_cast(self, typ: Type, context: Context) -> None:
         self.note('Redundant cast to {}'.format(self.format(typ)), context)
 
-    def typeddict_instantiated_with_unexpected_items(self,
-                                                     expected_item_names: List[str],
-                                                     actual_item_names: List[str],
-                                                     context: Context) -> None:
-        self.fail('Expected items {} but found {}.'.format(
-            expected_item_names, actual_item_names), context)
-
-    def typeddict_item_name_must_be_string_literal(self,
-                                                   typ: TypedDictType,
-                                                   context: Context,
-                                                   ) -> None:
-        self.fail('Cannot prove expression is a valid item name; expected one of {}'.format(
-            format_item_name_list(typ.items.keys())), context)
-
-    def typeddict_item_name_not_found(self,
-                                      typ: TypedDictType,
-                                      item_name: str,
-                                      context: Context,
-                                      ) -> None:
-        self.fail('\'{}\' is not a valid item name; expected one of {}'.format(
-            item_name, format_item_name_list(typ.items.keys())), context)
+    def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None:
+        self.fail("{} becomes {} due to an unfollowed import".format(prefix, self.format(typ)),
+                  ctx)
+
+    def explicit_any(self, ctx: Context) -> None:
+        self.fail('Explicit "Any" is not allowed', ctx)
+
+    def unexpected_typeddict_keys(
+            self,
+            typ: TypedDictType,
+            expected_keys: List[str],
+            actual_keys: List[str],
+            context: Context) -> None:
+        actual_set = set(actual_keys)
+        expected_set = set(expected_keys)
+        if not typ.is_anonymous():
+            # Generate simpler messages for some common special cases.
+            if actual_set < expected_set:
+                # Use list comprehension instead of set operations to preserve order.
+                missing = [key for key in expected_keys if key not in actual_set]
+                self.fail('{} missing for TypedDict {}'.format(
+                    format_key_list(missing, short=True).capitalize(), self.format(typ)),
+                    context)
+                return
+            else:
+                extra = [key for key in actual_keys if key not in expected_set]
+                if extra:
+                    # If there are both extra and missing keys, only report extra ones for
+                    # simplicity.
+                    self.fail('Extra {} for TypedDict {}'.format(
+                        format_key_list(extra, short=True), self.format(typ)),
+                        context)
+                    return
+        if not expected_keys:
+            expected = '(no keys)'
+        else:
+            expected = format_key_list(expected_keys)
+        found = format_key_list(actual_keys, short=True)
+        if actual_keys and actual_set < expected_set:
+            found = 'only {}'.format(found)
+        self.fail('Expected {} but found {}'.format(expected, found), context)
+
+    def typeddict_key_must_be_string_literal(
+            self,
+            typ: TypedDictType,
+            context: Context) -> None:
+        self.fail(
+            'TypedDict key must be a string literal; expected one of {}'.format(
+                format_item_name_list(typ.items.keys())), context)
+
+    def typeddict_key_not_found(
+            self,
+            typ: TypedDictType,
+            item_name: str,
+            context: Context) -> None:
+        if typ.is_anonymous():
+            self.fail('\'{}\' is not a valid TypedDict key; expected one of {}'.format(
+                item_name, format_item_name_list(typ.items.keys())), context)
+        else:
+            self.fail("TypedDict {} has no key '{}'".format(self.format(typ), item_name), context)
 
     def type_arguments_not_allowed(self, context: Context) -> None:
         self.fail('Parameterized generics cannot be used with class or instance checks', context)
 
+    def disallowed_any_type(self, typ: Type, context: Context) -> None:
+        if isinstance(typ, AnyType):
+            message = 'Expression has type "Any"'
+        else:
+            message = 'Expression type contains "Any" (has type {})'.format(self.format(typ))
+        self.fail(message, context)
+
+    def untyped_decorated_function(self, typ: Type, context: Context) -> None:
+        if isinstance(typ, AnyType):
+            self.fail("Function is untyped after decorator transformation", context)
+        else:
+            self.fail('Type of decorated function contains type "Any" ({})'.format(
+                self.format(typ)), context)
+
 
 def capitalize(s: str) -> str:
     """Capitalize the first character of a string."""
@@ -934,9 +1007,9 @@ def format_string_list(s: Iterable[str]) -> str:
 def format_item_name_list(s: Iterable[str]) -> str:
     l = list(s)
     if len(l) <= 5:
-        return '[' + ', '.join(["'%s'" % name for name in l]) + ']'
+        return '(' + ', '.join(["'%s'" % name for name in l]) + ')'
     else:
-        return '[' + ', '.join(["'%s'" % name for name in l[:5]]) + ', ...]'
+        return '(' + ', '.join(["'%s'" % name for name in l[:5]]) + ', ...)'
 
 
 def callable_name(type: CallableType) -> str:
@@ -946,6 +1019,21 @@ def callable_name(type: CallableType) -> str:
         return 'function'
 
 
+def find_defining_module(modules: Dict[str, MypyFile], typ: CallableType) -> Optional[MypyFile]:
+    if not typ.definition:
+        return None
+    fullname = typ.definition.fullname()
+    if fullname is not None and '.' in fullname:
+        for i in range(fullname.count('.')):
+            module_name = fullname.rsplit('.', i + 1)[0]
+            try:
+                return modules[module_name]
+            except KeyError:
+                pass
+        assert False, "Couldn't determine module from CallableType"
+    return None
+
+
 def temp_message_builder() -> MessageBuilder:
     """Return a message builder usable for throwaway errors (which may not format properly)."""
     return MessageBuilder(Errors(), {})
@@ -970,3 +1058,42 @@ def pretty_or(args: List[str]) -> str:
     if len(quoted) == 2:
         return "{} or {}".format(quoted[0], quoted[1])
     return ", ".join(quoted[:-1]) + ", or " + quoted[-1]
+
+
+def make_inferred_type_note(context: Context, subtype: Type,
+                            supertype: Type, supertype_str: str) -> str:
+    """Explain that the user may have forgotten to type a variable.
+
+    The user does not expect an error if the inferred container type is the same as the return
+    type of a function and the argument type(s) are a subtype of the argument type(s) of the
+    return type. This note suggests that they add a type annotation with the return type instead
+    of relying on the inferred type.
+    """
+    from mypy.subtypes import is_subtype
+    if (isinstance(subtype, Instance) and
+            isinstance(supertype, Instance) and
+            subtype.type.fullname() == supertype.type.fullname() and
+            subtype.args and
+            supertype.args and
+            isinstance(context, ReturnStmt) and
+            isinstance(context.expr, NameExpr) and
+            isinstance(context.expr.node, Var) and
+            context.expr.node.is_inferred):
+        for subtype_arg, supertype_arg in zip(subtype.args, supertype.args):
+            if not is_subtype(subtype_arg, supertype_arg):
+                return ''
+        var_name = context.expr.name
+        return 'Perhaps you need a type annotation for "{}"? Suggestion: {}'.format(
+            var_name, supertype_str)
+    return ''
+
+
+def format_key_list(keys: List[str], *, short: bool = False) -> str:
+    reprs = [repr(key) for key in keys]
+    td = '' if short else 'TypedDict '
+    if len(keys) == 0:
+        return 'no {}keys'.format(td)
+    elif len(keys) == 1:
+        return '{}key {}'.format(td, reprs[0])
+    else:
+        return '{}keys ({})'.format(td, ', '.join(reprs))
diff --git a/mypy/nodes.py b/mypy/nodes.py
index 05901d0..6cc75f5 100644
--- a/mypy/nodes.py
+++ b/mypy/nodes.py
@@ -2,6 +2,7 @@
 
 import os
 from abc import abstractmethod
+from collections import OrderedDict
 
 from typing import (
     Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional, Callable,
@@ -14,11 +15,35 @@ from mypy.util import short_type
 
 class Context:
     """Base type for objects that are valid as error message locations."""
-    @abstractmethod
-    def get_line(self) -> int: pass
 
-    @abstractmethod
-    def get_column(self) -> int: pass
+    line = -1
+    column = -1
+
+    def __init__(self, line: int = -1, column: int = -1) -> None:
+        self.line = line
+        self.column = column
+
+    def set_line(self, target: Union['Context', int], column: int = None) -> None:
+        """If target is a node, pull line (and column) information
+        into this node. If column is specified, this will override any column
+        information coming from a node.
+        """
+        if isinstance(target, int):
+            self.line = target
+        else:
+            self.line = target.line
+            self.column = target.column
+
+        if column is not None:
+            self.column = column
+
+    def get_line(self) -> int:
+        """Don't use. Use x.line."""
+        return self.line
+
+    def get_column(self) -> int:
+        """Don't use. Use x.column."""
+        return self.column
 
 
 if False:
@@ -112,37 +137,12 @@ Key = tuple
 class Node(Context):
     """Common base class for all non-type parse tree nodes."""
 
-    line = -1
-    column = -1
-
     def __str__(self) -> str:
         ans = self.accept(mypy.strconv.StrConv())
         if ans is None:
             return repr(self)
         return ans
 
-    def set_line(self, target: Union['Node', int], column: int = None) -> None:
-        """If target is a node, pull line (and column) information
-        into this node. If column is specified, this will override any column
-        information coming from a node.
-        """
-        if isinstance(target, int):
-            self.line = target
-        else:
-            self.line = target.line
-            self.column = target.column
-
-        if column is not None:
-            self.column = column
-
-    def get_line(self) -> int:
-        # TODO this should be just 'line'
-        return self.line
-
-    def get_column(self) -> int:
-        # TODO this should be just 'column'
-        return self.column
-
     def accept(self, visitor: NodeVisitor[T]) -> T:
         raise RuntimeError('Not implemented')
 
@@ -156,7 +156,7 @@ class Statement(Node):
 class Expression(Node):
     """An expression node."""
     literal = LITERAL_NO
-    literal_hash = None  # type: Key
+    literal_hash = None  # type: Optional[Key]
 
     def accept(self, visitor: ExpressionVisitor[T]) -> T:
         raise RuntimeError('Not implemented')
@@ -468,7 +468,7 @@ class Argument(Node):
         assign = AssignmentStmt([lvalue], rvalue)
         return assign
 
-    def set_line(self, target: Union[Node, int], column: int = None) -> None:
+    def set_line(self, target: Union[Context, int], column: int = None) -> None:
         super().set_line(target, column)
 
         if self.initializer:
@@ -525,7 +525,7 @@ class FuncItem(FuncBase):
     def max_fixed_argc(self) -> int:
         return self.max_pos
 
-    def set_line(self, target: Union[Node, int], column: int = None) -> None:
+    def set_line(self, target: Union[Context, int], column: int = None) -> None:
         super().set_line(target, column)
         for arg in self.arguments:
             arg.set_line(self.line, self.column)
@@ -731,6 +731,8 @@ class ClassDef(Statement):
     info = None  # type: TypeInfo  # Related TypeInfo
     metaclass = ''  # type: Optional[str]
     decorators = None  # type: List[Expression]
+    keywords = None  # type: OrderedDict[str, Expression]
+    analyzed = None  # type: Optional[Expression]
     has_incompatible_baseclass = False
 
     def __init__(self,
@@ -738,13 +740,15 @@ class ClassDef(Statement):
                  defs: 'Block',
                  type_vars: List['mypy.types.TypeVarDef'] = None,
                  base_type_exprs: List[Expression] = None,
-                 metaclass: str = None) -> None:
+                 metaclass: str = None,
+                 keywords: List[Tuple[str, Expression]] = None) -> None:
         self.name = name
         self.defs = defs
         self.type_vars = type_vars or []
         self.base_type_exprs = base_type_exprs or []
         self.metaclass = metaclass
         self.decorators = []
+        self.keywords = OrderedDict(keywords or [])
 
     def accept(self, visitor: StatementVisitor[T]) -> T:
         return visitor.visit_class_def(self)
@@ -753,7 +757,7 @@ class ClassDef(Statement):
         return self.info.is_generic()
 
     def serialize(self) -> JsonDict:
-        # Not serialized: defs, base_type_exprs, decorators
+        # Not serialized: defs, base_type_exprs, decorators, analyzed (for named tuples etc.)
         return {'.class': 'ClassDef',
                 'name': self.name,
                 'fullname': self.fullname,
@@ -1439,6 +1443,10 @@ class OpExpr(Expression):
     right = None  # type: Expression
     # Inferred type for the operator method type (when relevant).
     method_type = None  # type: Optional[mypy.types.Type]
+    # Is the right side going to be evaluated every time?
+    right_always = False
+    # Is the right side unreachable?
+    right_unreachable = False
 
     def __init__(self, op: str, left: Expression, right: Expression) -> None:
         self.op = op
@@ -1804,11 +1812,12 @@ class TypeAliasExpr(Expression):
     # (not in a type context like type annotation or base class).
     in_runtime = False  # type: bool
 
-    def __init__(self, type: 'mypy.types.Type', fallback: 'mypy.types.Type' = None,
-                 in_runtime: bool = False) -> None:
+    def __init__(self, type: 'mypy.types.Type', tvars: List[str],
+                 fallback: 'mypy.types.Type' = None, in_runtime: bool = False) -> None:
         self.type = type
         self.fallback = fallback
         self.in_runtime = in_runtime
+        self.tvars = tvars
 
     def accept(self, visitor: ExpressionVisitor[T]) -> T:
         return visitor.visit_type_alias_expr(self)
@@ -1946,7 +1955,7 @@ class TypeInfo(SymbolNode):
     mro = None  # type: List[TypeInfo]
 
     declared_metaclass = None  # type: Optional[mypy.types.Instance]
-    metaclass_type = None  # type: mypy.types.Instance
+    metaclass_type = None  # type: Optional[mypy.types.Instance]
 
     subtypes = None  # type: Set[TypeInfo] # Direct subclasses encountered so far
     names = None  # type: SymbolTable      # Names defined directly in this type
@@ -2036,6 +2045,12 @@ class TypeInfo(SymbolNode):
                 return n
         return None
 
+    def get_containing_type_info(self, name: str) -> Optional['TypeInfo']:
+        for cls in self.mro:
+            if name in cls.names:
+                return cls
+        return None
+
     def __getitem__(self, name: str) -> 'SymbolTableNode':
         n = self.get(name)
         if n:
@@ -2229,7 +2244,10 @@ class FakeInfo(TypeInfo):
     #    pass cleanly.
     # 2. If NOT_READY value is accidentally used somewhere, it will be obvious where the value
     #    is from, whereas a 'None' value could come from anywhere.
-    def __getattr__(self, attr: str) -> None:
+    def __init__(self, *args: Any, **kwargs: Any) -> None:
+        pass
+
+    def __getattribute__(self, attr: str) -> None:
         raise AssertionError('De-serialization failure: TypeInfo not fixed')
 
 
@@ -2250,6 +2268,9 @@ class SymbolTableNode:
     mod_id = ''  # type: Optional[str]
     # If this not None, override the type of the 'node' attribute.
     type_override = None  # type: Optional[mypy.types.Type]
+    # For generic aliases this stores the (qualified) names of type variables.
+    # (For example see testGenericAliasWithTypeVarsFromDifferentModules.)
+    alias_tvars = None  # type: Optional[List[str]]
     # If False, this name won't be imported via 'from <module> import *'.
     # This has no effect on names within classes.
     module_public = True
@@ -2261,13 +2282,15 @@ class SymbolTableNode:
 
     def __init__(self, kind: int, node: Optional[SymbolNode], mod_id: str = None,
                  typ: 'mypy.types.Type' = None,
-                 module_public: bool = True, normalized: bool = False) -> None:
+                 module_public: bool = True, normalized: bool = False,
+                 alias_tvars: Optional[List[str]] = None) -> None:
         self.kind = kind
         self.node = node
         self.type_override = typ
         self.mod_id = mod_id
         self.module_public = module_public
         self.normalized = normalized
+        self.alias_tvars = alias_tvars
 
     @property
     def fullname(self) -> Optional[str]:
@@ -2325,6 +2348,7 @@ class SymbolTableNode:
                 data['node'] = self.node.serialize()
             if self.type_override is not None:
                 data['type_override'] = self.type_override.serialize()
+                data['alias_tvars'] = self.alias_tvars
         return data
 
     @classmethod
@@ -2343,6 +2367,8 @@ class SymbolTableNode:
             if 'type_override' in data:
                 typ = mypy.types.deserialize_type(data['type_override'])
             stnode = SymbolTableNode(kind, node, typ=typ)
+            if 'alias_tvars' in data:
+                stnode.alias_tvars = data['alias_tvars']
         if 'module_public' in data:
             stnode.module_public = data['module_public']
         return stnode
@@ -2489,9 +2515,9 @@ def check_arg_kinds(arg_kinds: List[int], nodes: List[T], fail: Callable[[str, T
             is_kw_arg = True
 
 
-def check_arg_names(names: List[str], nodes: List[T], fail: Callable[[str, T], None],
+def check_arg_names(names: List[Optional[str]], nodes: List[T], fail: Callable[[str, T], None],
                     description: str = 'function definition') -> None:
-    seen_names = set()  # type: Set[str]
+    seen_names = set()  # type: Set[Optional[str]]
     for name, node in zip(names, nodes):
         if name is not None and name in seen_names:
             fail("Duplicate argument '{}' in {}".format(name, description), node)
diff --git a/mypy/options.py b/mypy/options.py
index 8c87642..af7837d 100644
--- a/mypy/options.py
+++ b/mypy/options.py
@@ -2,7 +2,7 @@ import fnmatch
 import pprint
 import sys
 
-from typing import Any, Mapping, Optional, Tuple, List, Pattern, Dict
+from typing import Mapping, Optional, Tuple, List, Pattern, Dict
 
 from mypy import defaults
 
@@ -19,6 +19,7 @@ class Options:
     PER_MODULE_OPTIONS = {
         "ignore_missing_imports",
         "follow_imports",
+        "disallow_any",
         "disallow_untyped_calls",
         "disallow_untyped_defs",
         "check_untyped_defs",
@@ -29,9 +30,11 @@ class Options:
         "warn_return_any",
         "ignore_errors",
         "strict_boolean",
+        "no_implicit_optional",
+        "strict_optional",
     }
 
-    OPTIONS_AFFECTING_CACHE = PER_MODULE_OPTIONS | {"strict_optional", "quick_and_dirty"}
+    OPTIONS_AFFECTING_CACHE = (PER_MODULE_OPTIONS | {"quick_and_dirty", "platform"})
 
     def __init__(self) -> None:
         # -- build options --
@@ -44,6 +47,7 @@ class Options:
         self.report_dirs = {}  # type: Dict[str, str]
         self.ignore_missing_imports = False
         self.follow_imports = 'normal'  # normal|silent|skip|error
+        self.disallow_any = []  # type: List[str]
 
         # Disallow calling untyped functions from typed ones
         self.disallow_untyped_calls = False
@@ -92,6 +96,9 @@ class Options:
         # Alternate way to show/hide strict-None-checking related errors
         self.show_none_errors = True
 
+        # Don't assume arguments with default values of None are Optional
+        self.no_implicit_optional = False
+
         # Use script name instead of __main__
         self.scripts_are_modules = False
 
@@ -106,6 +113,10 @@ class Options:
         self.cache_dir = defaults.CACHE_DIR
         self.debug_cache = False
         self.quick_and_dirty = False
+        self.skip_version_check = False
+
+        # Paths of user plugins
+        self.plugins = []  # type: List[str]
 
         # Per-module options (raw)
         self.per_module_options = {}  # type: Dict[Pattern[str], Dict[str, object]]
diff --git a/mypy/parse.py b/mypy/parse.py
index 13fd58b..2e02269 100644
--- a/mypy/parse.py
+++ b/mypy/parse.py
@@ -22,12 +22,10 @@ def parse(source: Union[str, bytes],
         return mypy.fastparse.parse(source,
                                     fnam=fnam,
                                     errors=errors,
-                                    pyversion=options.python_version,
-                                    custom_typing_module=options.custom_typing_module)
+                                    options=options)
     else:
         import mypy.fastparse2
         return mypy.fastparse2.parse(source,
                                      fnam=fnam,
                                      errors=errors,
-                                     pyversion=options.python_version,
-                                     custom_typing_module=options.custom_typing_module)
+                                     options=options)
diff --git a/mypy/plugin.py b/mypy/plugin.py
new file mode 100644
index 0000000..b362cbf
--- /dev/null
+++ b/mypy/plugin.py
@@ -0,0 +1,334 @@
+"""Plugin system for extending mypy."""
+
+from collections import OrderedDict
+from abc import abstractmethod
+from typing import Callable, List, Tuple, Optional, NamedTuple, TypeVar
+
+from mypy.nodes import Expression, StrExpr, IntExpr, UnaryExpr, Context, DictExpr
+from mypy.types import (
+    Type, Instance, CallableType, TypedDictType, UnionType, NoneTyp, FunctionLike, TypeVarType,
+    AnyType, TypeList, UnboundType
+)
+from mypy.messages import MessageBuilder
+from mypy.options import Options
+
+
+class AnalyzerPluginInterface:
+    """Interface for accessing semantic analyzer functionality in plugins."""
+
+    @abstractmethod
+    def fail(self, msg: str, ctx: Context) -> None:
+        raise NotImplementedError
+
+    @abstractmethod
+    def named_type(self, name: str, args: List[Type]) -> Instance:
+        raise NotImplementedError
+
+    @abstractmethod
+    def analyze_type(self, typ: Type) -> Type:
+        raise NotImplementedError
+
+    @abstractmethod
+    def analyze_callable_args(self, arglist: TypeList) -> Optional[Tuple[List[Type],
+                                                                         List[int],
+                                                                         List[Optional[str]]]]:
+        raise NotImplementedError
+
+
+# A context for a hook that semantically analyzes an unbound type.
+AnalyzeTypeContext = NamedTuple(
+    'AnalyzeTypeContext', [
+        ('type', UnboundType),  # Type to analyze
+        ('context', Context),
+        ('api', AnalyzerPluginInterface)])
+
+
+class CheckerPluginInterface:
+    """Interface for accessing type checker functionality in plugins."""
+
+    msg = None  # type: MessageBuilder
+
+    @abstractmethod
+    def named_generic_type(self, name: str, args: List[Type]) -> Instance:
+        raise NotImplementedError
+
+
+# A context for a function hook that infers the return type of a function with
+# a special signature.
+#
+# A no-op callback would just return the inferred return type, but a useful
+# callback at least sometimes can infer a more precise type.
+FunctionContext = NamedTuple(
+    'FunctionContext', [
+        ('arg_types', List[List[Type]]),   # List of actual caller types for each formal argument
+        ('default_return_type', Type),     # Return type inferred from signature
+        ('args', List[List[Expression]]),  # Actual expressions for each formal argument
+        ('context', Context),
+        ('api', CheckerPluginInterface)])
+
+# A context for a method signature hook that infers a better signature for a
+# method.  Note that argument types aren't available yet.  If you need them,
+# you have to use a method hook instead.
+MethodSigContext = NamedTuple(
+    'MethodSigContext', [
+        ('type', Type),                       # Base object type for method call
+        ('args', List[List[Expression]]),     # Actual expressions for each formal argument
+        ('default_signature', CallableType),  # Original signature of the method
+        ('context', Context),
+        ('api', CheckerPluginInterface)])
+
+# A context for a method hook that infers the return type of a method with a
+# special signature.
+#
+# This is very similar to FunctionContext (only differences are documented).
+MethodContext = NamedTuple(
+    'MethodContext', [
+        ('type', Type),                    # Base object type for method call
+        ('arg_types', List[List[Type]]),
+        ('default_return_type', Type),
+        ('args', List[List[Expression]]),
+        ('context', Context),
+        ('api', CheckerPluginInterface)])
+
+# A context for an attribute type hook that infers the type of an attribute.
+AttributeContext = NamedTuple(
+    'AttributeContext', [
+        ('type', Type),                # Type of object with attribute
+        ('default_attr_type', Type),  # Original attribute type
+        ('context', Context),
+        ('api', CheckerPluginInterface)])
+
+
+class Plugin:
+    """Base class of all type checker plugins.
+
+    This defines a no-op plugin.  Subclasses can override some methods to
+    provide some actual functionality.
+
+    All get_ methods are treated as pure functions (you should assume that
+    results might be cached).
+
+    Look at the comments of various *Context objects for descriptions of
+    various hooks.
+    """
+
+    def __init__(self, options: Options) -> None:
+        self.options = options
+        self.python_version = options.python_version
+
+    def get_type_analyze_hook(self, fullname: str
+                              ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
+        return None
+
+    def get_function_hook(self, fullname: str
+                          ) -> Optional[Callable[[FunctionContext], Type]]:
+        return None
+
+    def get_method_signature_hook(self, fullname: str
+                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:
+        return None
+
+    def get_method_hook(self, fullname: str
+                        ) -> Optional[Callable[[MethodContext], Type]]:
+        return None
+
+    def get_attribute_hook(self, fullname: str
+                           ) -> Optional[Callable[[AttributeContext], Type]]:
+        return None
+
+    # TODO: metaclass / class decorator hook
+
+
+T = TypeVar('T')
+
+
+class ChainedPlugin(Plugin):
+    """A plugin that represents a sequence of chained plugins.
+
+    Each lookup method returns the hook for the first plugin that
+    reports a match.
+
+    This class should not be subclassed -- use Plugin as the base class
+    for all plugins.
+    """
+
+    # TODO: Support caching of lookup results (through a LRU cache, for example).
+
+    def __init__(self, options: Options, plugins: List[Plugin]) -> None:
+        """Initialize chained plugin.
+
+        Assume that the child plugins aren't mutated (results may be cached).
+        """
+        super().__init__(options)
+        self._plugins = plugins
+
+    def get_type_analyze_hook(self, fullname: str
+                              ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
+        return self._find_hook(lambda plugin: plugin.get_type_analyze_hook(fullname))
+
+    def get_function_hook(self, fullname: str
+                          ) -> Optional[Callable[[FunctionContext], Type]]:
+        return self._find_hook(lambda plugin: plugin.get_function_hook(fullname))
+
+    def get_method_signature_hook(self, fullname: str
+                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:
+        return self._find_hook(lambda plugin: plugin.get_method_signature_hook(fullname))
+
+    def get_method_hook(self, fullname: str
+                        ) -> Optional[Callable[[MethodContext], Type]]:
+        return self._find_hook(lambda plugin: plugin.get_method_hook(fullname))
+
+    def get_attribute_hook(self, fullname: str
+                           ) -> Optional[Callable[[AttributeContext], Type]]:
+        return self._find_hook(lambda plugin: plugin.get_attribute_hook(fullname))
+
+    def _find_hook(self, lookup: Callable[[Plugin], T]) -> Optional[T]:
+        for plugin in self._plugins:
+            hook = lookup(plugin)
+            if hook:
+                return hook
+        return None
+
+
+class DefaultPlugin(Plugin):
+    """Type checker plugin that is enabled by default."""
+
+    def get_function_hook(self, fullname: str
+                          ) -> Optional[Callable[[FunctionContext], Type]]:
+        if fullname == 'contextlib.contextmanager':
+            return contextmanager_callback
+        elif fullname == 'builtins.open' and self.python_version[0] == 3:
+            return open_callback
+        return None
+
+    def get_method_signature_hook(self, fullname: str
+                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:
+        if fullname == 'typing.Mapping.get':
+            return typed_dict_get_signature_callback
+        return None
+
+    def get_method_hook(self, fullname: str
+                        ) -> Optional[Callable[[MethodContext], Type]]:
+        if fullname == 'typing.Mapping.get':
+            return typed_dict_get_callback
+        elif fullname == 'builtins.int.__pow__':
+            return int_pow_callback
+        return None
+
+
+def open_callback(ctx: FunctionContext) -> Type:
+    """Infer a better return type for 'open'.
+
+    Infer TextIO or BinaryIO as the return value if the mode argument is not
+    given or is a literal.
+    """
+    mode = None
+    if not ctx.arg_types or len(ctx.arg_types[1]) != 1:
+        mode = 'r'
+    elif isinstance(ctx.args[1][0], StrExpr):
+        mode = ctx.args[1][0].value
+    if mode is not None:
+        assert isinstance(ctx.default_return_type, Instance)
+        if 'b' in mode:
+            return ctx.api.named_generic_type('typing.BinaryIO', [])
+        else:
+            return ctx.api.named_generic_type('typing.TextIO', [])
+    return ctx.default_return_type
+
+
+def contextmanager_callback(ctx: FunctionContext) -> Type:
+    """Infer a better return type for 'contextlib.contextmanager'."""
+    # Be defensive, just in case.
+    if ctx.arg_types and len(ctx.arg_types[0]) == 1:
+        arg_type = ctx.arg_types[0][0]
+        if (isinstance(arg_type, CallableType)
+                and isinstance(ctx.default_return_type, CallableType)):
+            # The stub signature doesn't preserve information about arguments so
+            # add them back here.
+            return ctx.default_return_type.copy_modified(
+                arg_types=arg_type.arg_types,
+                arg_kinds=arg_type.arg_kinds,
+                arg_names=arg_type.arg_names,
+                variables=arg_type.variables,
+                is_ellipsis_args=arg_type.is_ellipsis_args)
+    return ctx.default_return_type
+
+
+def typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType:
+    """Try to infer a better signature type for TypedDict.get.
+
+    This is used to get better type context for the second argument that
+    depends on a TypedDict value type.
+    """
+    signature = ctx.default_signature
+    if (isinstance(ctx.type, TypedDictType)
+            and len(ctx.args) == 2
+            and len(ctx.args[0]) == 1
+            and isinstance(ctx.args[0][0], StrExpr)
+            and len(signature.arg_types) == 2
+            and len(signature.variables) == 1
+            and len(ctx.args[1]) == 1):
+        key = ctx.args[0][0].value
+        value_type = ctx.type.items.get(key)
+        ret_type = signature.ret_type
+        if value_type:
+            default_arg = ctx.args[1][0]
+            if (isinstance(value_type, TypedDictType)
+                    and isinstance(default_arg, DictExpr)
+                    and len(default_arg.items) == 0):
+                # Caller has empty dict {} as default for typed dict.
+                value_type = value_type.copy_modified(required_keys=set())
+            # Tweak the signature to include the value type as context. It's
+            # only needed for type inference since there's a union with a type
+            # variable that accepts everything.
+            tv = TypeVarType(signature.variables[0])
+            return signature.copy_modified(
+                arg_types=[signature.arg_types[0],
+                           UnionType.make_simplified_union([value_type, tv])],
+                ret_type=ret_type)
+    return signature
+
+
+def typed_dict_get_callback(ctx: MethodContext) -> Type:
+    """Infer a precise return type for TypedDict.get with literal first argument."""
+    if (isinstance(ctx.type, TypedDictType)
+            and len(ctx.arg_types) >= 1
+            and len(ctx.arg_types[0]) == 1):
+        if isinstance(ctx.args[0][0], StrExpr):
+            key = ctx.args[0][0].value
+            value_type = ctx.type.items.get(key)
+            if value_type:
+                if len(ctx.arg_types) == 1:
+                    return UnionType.make_simplified_union([value_type, NoneTyp()])
+                elif (len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1
+                      and len(ctx.args[1]) == 1):
+                    default_arg = ctx.args[1][0]
+                    if (isinstance(default_arg, DictExpr) and len(default_arg.items) == 0
+                            and isinstance(value_type, TypedDictType)):
+                        # Special case '{}' as the default for a typed dict type.
+                        return value_type.copy_modified(required_keys=set())
+                    else:
+                        return UnionType.make_simplified_union([value_type, ctx.arg_types[1][0]])
+            else:
+                ctx.api.msg.typeddict_key_not_found(ctx.type, key, ctx.context)
+                return AnyType()
+    return ctx.default_return_type
+
+
+def int_pow_callback(ctx: MethodContext) -> Type:
+    """Infer a more precise return type for int.__pow__."""
+    if (len(ctx.arg_types) == 1
+            and len(ctx.arg_types[0]) == 1):
+        arg = ctx.args[0][0]
+        if isinstance(arg, IntExpr):
+            exponent = arg.value
+        elif isinstance(arg, UnaryExpr) and arg.op == '-' and isinstance(arg.expr, IntExpr):
+            exponent = -arg.expr.value
+        else:
+            # Right operand not an int literal or a negated literal -- give up.
+            return ctx.default_return_type
+        if exponent >= 0:
+            return ctx.api.named_generic_type('builtins.int', [])
+        else:
+            return ctx.api.named_generic_type('builtins.float', [])
+    return ctx.default_return_type
diff --git a/mypy/report.py b/mypy/report.py
index 74b44ac..a221a25 100644
--- a/mypy/report.py
+++ b/mypy/report.py
@@ -1,13 +1,12 @@
 """Classes for producing HTML reports about imprecision."""
 
 from abc import ABCMeta, abstractmethod
-import cgi
 import json
 import os
 import shutil
 import tokenize
 from operator import attrgetter
-
+from urllib.request import pathname2url
 from typing import Any, Callable, Dict, List, Optional, Tuple, cast
 
 import time
@@ -144,6 +143,74 @@ class LineCountReporter(AbstractReporter):
 register_reporter('linecount', LineCountReporter)
 
 
+class AnyExpressionsReporter(AbstractReporter):
+    def __init__(self, reports: Reports, output_dir: str) -> None:
+        super().__init__(reports, output_dir)
+        self.counts = {}  # type: Dict[str, Tuple[int, int]]
+        stats.ensure_dir_exists(output_dir)
+
+    def on_file(self,
+                tree: MypyFile,
+                type_map: Dict[Expression, Type],
+                options: Options) -> None:
+        visitor = stats.StatisticsVisitor(inferred=True, filename=tree.fullname(),
+                                          typemap=type_map, all_nodes=True)
+        tree.accept(visitor)
+        num_unanalyzed_lines = list(visitor.line_map.values()).count(stats.TYPE_UNANALYZED)
+        # count each line of dead code as one expression of type "Any"
+        num_any = visitor.num_any + num_unanalyzed_lines
+        num_total = visitor.num_imprecise + visitor.num_precise + num_any
+        if num_total > 0:
+            self.counts[tree.fullname()] = (num_any, num_total)
+
+    def on_finish(self) -> None:
+        total_any = sum(num_any for num_any, _ in self.counts.values())
+        total_expr = sum(total for _, total in self.counts.values())
+        total_coverage = 100.0
+        if total_expr > 0:
+            total_coverage = (float(total_expr - total_any) / float(total_expr)) * 100
+
+        any_column_name = "Anys"
+        total_column_name = "Exprs"
+        file_column_name = "Name"
+        total_row_name = "Total"
+        coverage_column_name = "Coverage"
+        # find the longest filename all files
+        name_width = max([len(file) for file in self.counts] +
+                         [len(file_column_name), len(total_row_name)])
+        # totals are the largest numbers in their column - no need to look at others
+        min_column_distance = 3  # minimum distance between numbers in two columns
+        any_width = max(len(str(total_any)) + min_column_distance, len(any_column_name))
+        exprs_width = max(len(str(total_expr)) + min_column_distance, len(total_column_name))
+        coverage_width = len(coverage_column_name) + min_column_distance
+        header = '{:{name_width}} {:>{any_width}} {:>{total_width}} {:>{coverage_width}}'.format(
+            file_column_name, any_column_name, total_column_name, coverage_column_name,
+            name_width=name_width, any_width=any_width, total_width=exprs_width,
+            coverage_width=coverage_width)
+
+        with open(os.path.join(self.output_dir, 'any-exprs.txt'), 'w') as f:
+            f.write(header + '\n')
+            separator = '-' * len(header) + '\n'
+            f.write(separator)
+            coverage_width -= 1  # subtract one for '%'
+            for file in sorted(self.counts):
+                (num_any, num_total) = self.counts[file]
+                coverage = (float(num_total - num_any) / float(num_total)) * 100
+                f.write('{:{name_width}} {:{any_width}} {:{total_width}} '
+                        '{:>{coverage_width}.2f}%\n'.
+                        format(file, num_any, num_total, coverage, name_width=name_width,
+                               any_width=any_width, total_width=exprs_width,
+                               coverage_width=coverage_width))
+            f.write(separator)
+            f.write('{:{name_width}} {:{any_width}} {:{total_width}} {:>{coverage_width}.2f}%\n'
+                    .format(total_row_name, total_any, total_expr, total_coverage,
+                            name_width=name_width, any_width=any_width, total_width=exprs_width,
+                            coverage_width=coverage_width))
+
+
+register_reporter('any-exprs', AnyExpressionsReporter)
+
+
 class LineCoverageVisitor(TraverserVisitor):
     def __init__(self, source: List[str]) -> None:
         self.source = source
@@ -320,7 +387,8 @@ class MemoryXmlReporter(AbstractReporter):
         if 'stubs' in path.split('/'):
             return
 
-        visitor = stats.StatisticsVisitor(inferred=True, typemap=type_map, all_nodes=True)
+        visitor = stats.StatisticsVisitor(inferred=True, filename=tree.fullname(),
+                                          typemap=type_map, all_nodes=True)
         tree.accept(visitor)
 
         root = etree.Element('mypy-report-file', name=path, module=tree._fullname)
@@ -334,11 +402,11 @@ class MemoryXmlReporter(AbstractReporter):
                 etree.SubElement(root, 'line',
                                  number=str(lineno),
                                  precision=stats.precision_names[status],
-                                 content=line_text[:-1])
+                                 content=line_text.rstrip('\n'))
         # Assumes a layout similar to what XmlReporter uses.
         xslt_path = os.path.relpath('mypy-html.xslt', path)
         transform_pi = etree.ProcessingInstruction('xml-stylesheet',
-                'type="text/xsl" href="%s"' % cgi.escape(xslt_path, True))
+                'type="text/xsl" href="%s"' % pathname2url(xslt_path))
         root.addprevious(transform_pi)
         self.schema.assertValid(doc)
 
@@ -361,7 +429,7 @@ class MemoryXmlReporter(AbstractReporter):
                              module=file_info.module)
         xslt_path = os.path.relpath('mypy-html.xslt', '.')
         transform_pi = etree.ProcessingInstruction('xml-stylesheet',
-                'type="text/xsl" href="%s"' % cgi.escape(xslt_path, True))
+                'type="text/xsl" href="%s"' % pathname2url(xslt_path))
         root.addprevious(transform_pi)
         self.schema.assertValid(doc)
 
@@ -425,7 +493,8 @@ class CoberturaXmlReporter(AbstractReporter):
                 type_map: Dict[Expression, Type],
                 options: Options) -> None:
         path = os.path.relpath(tree.path)
-        visitor = stats.StatisticsVisitor(inferred=True, typemap=type_map, all_nodes=True)
+        visitor = stats.StatisticsVisitor(inferred=True, filename=tree.fullname(),
+                                          typemap=type_map, all_nodes=True)
         tree.accept(visitor)
 
         class_name = os.path.basename(path)
diff --git a/mypy/semanal.py b/mypy/semanal.py
index 2d01ca2..bcbe495 100644
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -47,7 +47,7 @@ from collections import OrderedDict
 from contextlib import contextmanager
 
 from typing import (
-    List, Dict, Set, Tuple, cast, TypeVar, Union, Optional, Callable, Iterator,
+    List, Dict, Set, Tuple, cast, TypeVar, Union, Optional, Callable, Iterator, Iterable
 )
 
 from mypy.nodes import (
@@ -75,21 +75,23 @@ from mypy.typevars import has_no_typevars, fill_typevars
 from mypy.visitor import NodeVisitor
 from mypy.traverser import TraverserVisitor
 from mypy.errors import Errors, report_internal_error
-from mypy.messages import CANNOT_ASSIGN_TO_TYPE
+from mypy.messages import CANNOT_ASSIGN_TO_TYPE, MessageBuilder
 from mypy.types import (
-    NoneTyp, CallableType, Overloaded, Instance, Type, TypeVarType, AnyType,
-    FunctionLike, UnboundType, TypeList, TypeVarDef, TypeType,
-    TupleType, UnionType, StarType, EllipsisType, function_type, TypedDictType,
-    TypeQuery
+    FunctionLike, UnboundType, TypeVarDef, TypeType, TupleType, UnionType, StarType, function_type,
+    TypedDictType, NoneTyp, CallableType, Overloaded, Instance, Type, TypeVarType, AnyType,
+    TypeTranslator,
 )
 from mypy.nodes import implicit_module_attrs
 from mypy.typeanal import (
     TypeAnalyser, TypeAnalyserPass3, analyze_type_alias, no_subscript_builtin_alias,
-    TypeVariableQuery, TypeVarList, remove_dups,
+    TypeVariableQuery, TypeVarList, remove_dups, has_any_from_unimported_type,
+    check_for_explicit_any, collect_any_types,
 )
 from mypy.exprtotype import expr_to_unanalyzed_type, TypeTranslationError
 from mypy.sametypes import is_same_type
 from mypy.options import Options
+from mypy import experiments, messages
+from mypy.plugin import Plugin
 from mypy import join
 
 
@@ -156,6 +158,28 @@ FUNCTION_BOTH_PHASES = 0  # Everthing in one go
 FUNCTION_FIRST_PHASE_POSTPONE_SECOND = 1  # Add to symbol table but postpone body
 FUNCTION_SECOND_PHASE = 2  # Only analyze body
 
+# Matches "_prohibited" in typing.py, but adds __annotations__, which works at runtime but can't
+# easily be supported in a static checker.
+NAMEDTUPLE_PROHIBITED_NAMES = ('__new__', '__init__', '__slots__', '__getnewargs__',
+                               '_fields', '_field_defaults', '_field_types',
+                               '_make', '_replace', '_asdict', '_source',
+                               '__annotations__')
+
+# Map from the full name of a missing definition to the test fixture (under
+# test-data/unit/fixtures/) that provides the definition. This is used for
+# generating better error messages when running mypy tests only.
+SUGGESTED_TEST_FIXTURES = {
+    'typing.List': 'list.pyi',
+    'typing.Dict': 'dict.pyi',
+    'typing.Set': 'set.pyi',
+    'builtins.bool': 'bool.pyi',
+    'builtins.Exception': 'exception.pyi',
+    'builtins.BaseException': 'exception.pyi',
+    'builtins.isinstance': 'isinstancelist.pyi',
+    'builtins.property': 'property.pyi',
+    'builtins.classmethod': 'classmethod.pyi',
+}
+
 
 class SemanticAnalyzer(NodeVisitor):
     """Semantically analyze parsed mypy files.
@@ -206,13 +230,16 @@ class SemanticAnalyzer(NodeVisitor):
     loop_depth = 0         # Depth of breakable loops
     cur_mod_id = ''        # Current module id (or None) (phase 2)
     is_stub_file = False   # Are we analyzing a stub file?
+    is_typeshed_stub_file = False  # Are we analyzing a typeshed stub file?
     imports = None  # type: Set[str]  # Imported modules (during phase 2 analysis)
     errors = None  # type: Errors     # Keeps track of generated errors
+    plugin = None  # type: Plugin     # Mypy plugin for special casing of library features
 
     def __init__(self,
                  modules: Dict[str, MypyFile],
                  missing_modules: Set[str],
-                 lib_path: List[str], errors: Errors) -> None:
+                 lib_path: List[str], errors: Errors,
+                 plugin: Plugin) -> None:
         """Construct semantic analyzer.
 
         Use lib_path to search for modules, and report analysis errors
@@ -229,44 +256,56 @@ class SemanticAnalyzer(NodeVisitor):
         self.lib_path = lib_path
         self.errors = errors
         self.modules = modules
+        self.msg = MessageBuilder(errors, modules)
         self.missing_modules = missing_modules
         self.postpone_nested_functions_stack = [FUNCTION_BOTH_PHASES]
         self.postponed_functions_stack = []
         self.all_exports = set()  # type: Set[str]
+        self.plugin = plugin
 
-    def visit_file(self, file_node: MypyFile, fnam: str, options: Options) -> None:
+    def visit_file(self, file_node: MypyFile, fnam: str, options: Options,
+                   patches: List[Callable[[], None]]) -> None:
+        """Run semantic analysis phase 2 over a file.
+
+        Add callbacks by mutating the patches list argument. They will be called
+        after all semantic analysis phases but before type checking.
+        """
         self.options = options
         self.errors.set_file(fnam, file_node.fullname())
         self.cur_mod_node = file_node
         self.cur_mod_id = file_node.fullname()
         self.is_stub_file = fnam.lower().endswith('.pyi')
+        self.is_typeshed_stub_file = self.errors.is_typeshed_file(file_node.path)
         self.globals = file_node.names
+        self.patches = patches
 
-        if 'builtins' in self.modules:
-            self.globals['__builtins__'] = SymbolTableNode(
-                MODULE_REF, self.modules['builtins'], self.cur_mod_id)
+        with experiments.strict_optional_set(options.strict_optional):
+            if 'builtins' in self.modules:
+                self.globals['__builtins__'] = SymbolTableNode(
+                    MODULE_REF, self.modules['builtins'], self.cur_mod_id)
 
-        for name in implicit_module_attrs:
-            v = self.globals[name].node
-            if isinstance(v, Var):
-                v.type = self.anal_type(v.type)
-                v.is_ready = True
+            for name in implicit_module_attrs:
+                v = self.globals[name].node
+                if isinstance(v, Var):
+                    v.type = self.anal_type(v.type)
+                    v.is_ready = True
 
-        defs = file_node.defs
-        for d in defs:
-            self.accept(d)
+            defs = file_node.defs
+            for d in defs:
+                self.accept(d)
 
-        if self.cur_mod_id == 'builtins':
-            remove_imported_names_from_symtable(self.globals, 'builtins')
-            for alias_name in type_aliases:
-                self.globals.pop(alias_name.split('.')[-1], None)
+            if self.cur_mod_id == 'builtins':
+                remove_imported_names_from_symtable(self.globals, 'builtins')
+                for alias_name in type_aliases:
+                    self.globals.pop(alias_name.split('.')[-1], None)
 
-        if '__all__' in self.globals:
-            for name, g in self.globals.items():
-                if name not in self.all_exports:
-                    g.module_public = False
+            if '__all__' in self.globals:
+                for name, g in self.globals.items():
+                    if name not in self.all_exports:
+                        g.module_public = False
 
-        del self.options
+            del self.options
+            del self.patches
 
     def refresh_partial(self, node: Union[MypyFile, FuncItem]) -> None:
         """Refresh a stale target in fine-grained incremental mode."""
@@ -302,9 +341,10 @@ class SemanticAnalyzer(NodeVisitor):
         self.cur_mod_node = file_node
         self.cur_mod_id = file_node.fullname()
         self.is_stub_file = fnam.lower().endswith('.pyi')
+        self.is_typeshed_stub_file = self.errors.is_typeshed_file(file_node.path)
         self.globals = file_node.names
         if active_type:
-            self.enter_class(active_type.defn)
+            self.enter_class(active_type.defn.info)
             # TODO: Bind class type vars
 
         yield
@@ -321,6 +361,8 @@ class SemanticAnalyzer(NodeVisitor):
             self.function_stack.append(defn)
             # First phase of analysis for function.
             self.errors.push_function(defn.name())
+            if not defn._fullname:
+                defn._fullname = self.qualified_name(defn.name())
             if defn.type:
                 assert isinstance(defn.type, CallableType)
                 self.update_function_type_variables(defn.type, defn)
@@ -540,9 +582,10 @@ class SemanticAnalyzer(NodeVisitor):
                         first_item.var.is_settable_property = True
                         # Get abstractness from the original definition.
                         item.func.is_abstract = first_item.func.is_abstract
-                item.func.accept(self)
             else:
                 self.fail("Decorated property not supported", item)
+            if isinstance(item, Decorator):
+                item.func.accept(self)
 
     def analyze_function(self, defn: FuncItem) -> None:
         is_method = self.is_class_scope()
@@ -628,14 +671,40 @@ class SemanticAnalyzer(NodeVisitor):
     def analyze_class_body(self, defn: ClassDef) -> Iterator[bool]:
         with self.tvar_scope_frame(self.tvar_scope.class_frame()):
             self.clean_up_bases_and_infer_type_variables(defn)
+            self.analyze_class_keywords(defn)
             if self.analyze_typeddict_classdef(defn):
                 yield False
                 return
-            if self.analyze_namedtuple_classdef(defn):
-                # just analyze the class body so we catch type errors in default values
-                self.enter_class(defn)
+            named_tuple_info = self.analyze_namedtuple_classdef(defn)
+            if named_tuple_info is not None:
+                # Temporarily clear the names dict so we don't get errors about duplicate names
+                # that were already set in build_namedtuple_typeinfo.
+                nt_names = named_tuple_info.names
+                named_tuple_info.names = SymbolTable()
+                # This is needed for the cls argument to classmethods to get bound correctly.
+                named_tuple_info.names['__init__'] = nt_names['__init__']
+
+                self.enter_class(named_tuple_info)
+
                 yield True
+
                 self.leave_class()
+
+                # make sure we didn't use illegal names, then reset the names in the typeinfo
+                for prohibited in NAMEDTUPLE_PROHIBITED_NAMES:
+                    if prohibited in named_tuple_info.names:
+                        if nt_names.get(prohibited) is named_tuple_info.names[prohibited]:
+                            continue
+                        self.fail('Cannot overwrite NamedTuple attribute "{}"'.format(prohibited),
+                                  named_tuple_info.names[prohibited].node)
+
+                # Restore the names in the original symbol table. This ensures that the symbol
+                # table contains the field objects created by build_namedtuple_typeinfo. Exclude
+                # __doc__, which can legally be overwritten by the class.
+                named_tuple_info.names.update({
+                    key: value for key, value in nt_names.items()
+                    if key not in named_tuple_info.names or key != '__doc__'
+                })
             else:
                 self.setup_class_def_analysis(defn)
                 self.analyze_base_classes(defn)
@@ -644,7 +713,7 @@ class SemanticAnalyzer(NodeVisitor):
                 for decorator in defn.decorators:
                     self.analyze_class_decorator(defn, decorator)
 
-                self.enter_class(defn)
+                self.enter_class(defn.info)
                 yield True
 
                 self.calculate_abstract_status(defn.info)
@@ -652,13 +721,17 @@ class SemanticAnalyzer(NodeVisitor):
 
                 self.leave_class()
 
-    def enter_class(self, defn: ClassDef) -> None:
+    def analyze_class_keywords(self, defn: ClassDef) -> None:
+        for value in defn.keywords.values():
+            value.accept(self)
+
+    def enter_class(self, info: TypeInfo) -> None:
         # Remember previous active class
         self.type_stack.append(self.type)
         self.locals.append(None)  # Add class scope
         self.block_depth.append(-1)  # The class body increments this to 0
         self.postpone_nested_functions_stack.append(FUNCTION_BOTH_PHASES)
-        self.type = defn.info
+        self.type = info
 
     def leave_class(self) -> None:
         """ Restore analyzer state. """
@@ -726,8 +799,12 @@ class SemanticAnalyzer(NodeVisitor):
         Now we will remove Generic[T] from bases of Foo and infer that the
         type variable 'T' is a type argument of Foo.
 
+        We also process six.with_metaclass() here.
+
         Note that this is performed *before* semantic analysis.
         """
+        # First process six.with_metaclass if present and well-formed
+        defn.base_type_exprs, defn.metaclass = self.check_with_metaclass(defn)
         removed = []  # type: List[int]
         declared_tvars = []  # type: TypeVarList
         for i, base_expr in enumerate(defn.base_type_exprs):
@@ -810,7 +887,7 @@ class SemanticAnalyzer(NodeVisitor):
                 tvars.extend(base_tvars)
         return remove_dups(tvars)
 
-    def analyze_namedtuple_classdef(self, defn: ClassDef) -> bool:
+    def analyze_namedtuple_classdef(self, defn: ClassDef) -> Optional[TypeInfo]:
         # special case for NamedTuple
         for base_expr in defn.base_type_exprs:
             if isinstance(base_expr, RefExpr):
@@ -820,21 +897,18 @@ class SemanticAnalyzer(NodeVisitor):
                     if node is not None:
                         node.kind = GDEF  # TODO in process_namedtuple_definition also applies here
                         items, types, default_items = self.check_namedtuple_classdef(defn)
-                        node.node = self.build_namedtuple_typeinfo(
+                        info = self.build_namedtuple_typeinfo(
                             defn.name, items, types, default_items)
-                        # We only really need the assignments in the body to be type checked later;
-                        # attempting to type check methods may lead to crashes because NamedTuples
-                        # do not have a fully functional TypeInfo.
-                        # TODO remove this hack and add full support for NamedTuple methods
-                        defn.defs.body = [stmt for stmt in defn.defs.body
-                                          if isinstance(stmt, AssignmentStmt)]
-                        return True
-        return False
+                        node.node = info
+                        defn.info = info
+                        defn.analyzed = NamedTupleExpr(info)
+                        return info
+        return None
 
     def check_namedtuple_classdef(
             self, defn: ClassDef) -> Tuple[List[str], List[Type], Dict[str, Expression]]:
         NAMEDTUP_CLASS_ERROR = ('Invalid statement in NamedTuple definition; '
-                               'expected "field_name: field_type"')
+                                'expected "field_name: field_type [= default]"')
         if self.options.python_version < (3, 6):
             self.fail('NamedTuple class syntax is only supported in Python 3.6', defn)
             return [], [], {}
@@ -846,10 +920,18 @@ class SemanticAnalyzer(NodeVisitor):
         for stmt in defn.defs.body:
             if not isinstance(stmt, AssignmentStmt):
                 # Still allow pass or ... (for empty namedtuples).
-                if (not isinstance(stmt, PassStmt) and
-                    not (isinstance(stmt, ExpressionStmt) and
-                         isinstance(stmt.expr, EllipsisExpr))):
-                    self.fail(NAMEDTUP_CLASS_ERROR, stmt)
+                if (isinstance(stmt, PassStmt) or
+                    (isinstance(stmt, ExpressionStmt) and
+                        isinstance(stmt.expr, EllipsisExpr))):
+                    continue
+                # Also allow methods, including decorated ones.
+                if isinstance(stmt, (Decorator, FuncBase)):
+                    continue
+                # And docstrings.
+                if (isinstance(stmt, ExpressionStmt) and
+                        isinstance(stmt.expr, StrExpr)):
+                    continue
+                self.fail(NAMEDTUP_CLASS_ERROR, stmt)
             elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr):
                 # An assignment, but an invalid one.
                 self.fail(NAMEDTUP_CLASS_ERROR, stmt)
@@ -902,6 +984,7 @@ class SemanticAnalyzer(NodeVisitor):
 
         base_types = []  # type: List[Instance]
         info = defn.info
+
         for base_expr in defn.base_type_exprs:
             try:
                 base = self.expr_to_analyzed_type(base_expr)
@@ -931,6 +1014,14 @@ class SemanticAnalyzer(NodeVisitor):
             else:
                 self.fail('Invalid base class', base_expr)
                 info.fallback_to_any = True
+            if 'unimported' in self.options.disallow_any and has_any_from_unimported_type(base):
+                if isinstance(base_expr, (NameExpr, MemberExpr)):
+                    prefix = "Base type {}".format(base_expr.name)
+                else:
+                    prefix = "Base type"
+                self.msg.unimported_type_becomes_any(prefix, base, base_expr)
+            check_for_explicit_any(base, self.options, self.is_typeshed_stub_file, self.msg,
+                                   context=base_expr)
 
         # Add 'object' as implicit base if there is no other base class.
         if (not base_types and defn.fullname != 'builtins.object'):
@@ -953,6 +1044,27 @@ class SemanticAnalyzer(NodeVisitor):
         if defn.info.is_enum and defn.type_vars:
             self.fail("Enum class cannot be generic", defn)
 
+    def check_with_metaclass(self, defn: ClassDef) -> Tuple[List[Expression], Optional[str]]:
+        # Special-case six.with_metaclass(M, B1, B2, ...).
+        base_type_exprs, metaclass = defn.base_type_exprs, defn.metaclass
+        if metaclass is None and len(base_type_exprs) == 1:
+            base_expr = base_type_exprs[0]
+            if isinstance(base_expr, CallExpr) and isinstance(base_expr.callee, RefExpr):
+                base_expr.callee.accept(self)
+                if (base_expr.callee.fullname == 'six.with_metaclass'
+                        and len(base_expr.args) >= 1
+                        and all(kind == ARG_POS for kind in base_expr.arg_kinds)):
+                    metaclass_expr = base_expr.args[0]
+                    if isinstance(metaclass_expr, NameExpr):
+                        metaclass = metaclass_expr.name
+                    elif isinstance(metaclass_expr, MemberExpr):
+                        metaclass = get_member_expr_fullname(metaclass_expr)
+                    else:
+                        self.fail("Dynamic metaclass not supported for '%s'" % defn.name,
+                                  metaclass_expr)
+                    return (base_expr.args[1:], metaclass)
+        return (base_type_exprs, metaclass)
+
     def expr_to_analyzed_type(self, expr: Expression) -> Type:
         if isinstance(expr, CallExpr):
             expr.accept(self)
@@ -1113,8 +1225,10 @@ class SemanticAnalyzer(NodeVisitor):
                         isinstance(defn.base_type_exprs[0], RefExpr) and
                         defn.base_type_exprs[0].fullname == 'mypy_extensions.TypedDict'):
                     # Building a new TypedDict
-                    fields, types = self.check_typeddict_classdef(defn)
-                    node.node = self.build_typeddict_typeinfo(defn.name, fields, types)
+                    fields, types, required_keys = self.check_typeddict_classdef(defn)
+                    info = self.build_typeddict_typeinfo(defn.name, fields, types, required_keys)
+                    node.node = info
+                    defn.analyzed = TypedDictExpr(info)
                     return True
                 # Extending/merging existing TypedDicts
                 if any(not isinstance(expr, RefExpr) or
@@ -1122,36 +1236,43 @@ class SemanticAnalyzer(NodeVisitor):
                        not self.is_typeddict(expr) for expr in defn.base_type_exprs):
                     self.fail("All bases of a new TypedDict must be TypedDict types", defn)
                 typeddict_bases = list(filter(self.is_typeddict, defn.base_type_exprs))
-                newfields = []  # type: List[str]
-                newtypes = []  # type: List[Type]
-                tpdict = None  # type: OrderedDict[str, Type]
+                keys = []  # type: List[str]
+                types = []
+                required_keys = set()
                 for base in typeddict_bases:
                     assert isinstance(base, RefExpr)
                     assert isinstance(base.node, TypeInfo)
                     assert isinstance(base.node.typeddict_type, TypedDictType)
-                    tpdict = base.node.typeddict_type.items
-                    newdict = tpdict.copy()
-                    for key in tpdict:
-                        if key in newfields:
+                    base_typed_dict = base.node.typeddict_type
+                    base_items = base_typed_dict.items
+                    valid_items = base_items.copy()
+                    for key in base_items:
+                        if key in keys:
                             self.fail('Cannot overwrite TypedDict field "{}" while merging'
                                       .format(key), defn)
-                            newdict.pop(key)
-                    newfields.extend(newdict.keys())
-                    newtypes.extend(newdict.values())
-                fields, types = self.check_typeddict_classdef(defn, newfields)
-                newfields.extend(fields)
-                newtypes.extend(types)
-                node.node = self.build_typeddict_typeinfo(defn.name, newfields, newtypes)
+                            valid_items.pop(key)
+                    keys.extend(valid_items.keys())
+                    types.extend(valid_items.values())
+                    required_keys.update(base_typed_dict.required_keys)
+                new_keys, new_types, new_required_keys = self.check_typeddict_classdef(defn, keys)
+                keys.extend(new_keys)
+                types.extend(new_types)
+                required_keys.update(new_required_keys)
+                info = self.build_typeddict_typeinfo(defn.name, keys, types, required_keys)
+                node.node = info
+                defn.analyzed = TypedDictExpr(info)
                 return True
         return False
 
     def check_typeddict_classdef(self, defn: ClassDef,
-                                 oldfields: List[str] = None) -> Tuple[List[str], List[Type]]:
+                                 oldfields: List[str] = None) -> Tuple[List[str],
+                                                                       List[Type],
+                                                                       Set[str]]:
         TPDICT_CLASS_ERROR = ('Invalid statement in TypedDict definition; '
                               'expected "field_name: field_type"')
         if self.options.python_version < (3, 6):
             self.fail('TypedDict class syntax is only supported in Python 3.6', defn)
-            return [], []
+            return [], [], set()
         fields = []  # type: List[str]
         types = []  # type: List[Type]
         for stmt in defn.defs.body:
@@ -1182,7 +1303,14 @@ class SemanticAnalyzer(NodeVisitor):
                 elif not isinstance(stmt.rvalue, TempNode):
                     # x: int assigns rvalue to TempNode(AnyType())
                     self.fail('Right hand side values are not supported in TypedDict', stmt)
-        return fields, types
+        total = True
+        if 'total' in defn.keywords:
+            total = self.parse_bool(defn.keywords['total'])
+            if total is None:
+                self.fail('Value of "total" must be True or False', defn)
+                total = True
+        required_keys = set(fields) if total else set()
+        return fields, types, required_keys
 
     def visit_import(self, i: Import) -> None:
         for id, as_id in i.ids:
@@ -1267,7 +1395,8 @@ class SemanticAnalyzer(NodeVisitor):
                                          self.cur_mod_id,
                                          node.type_override,
                                          module_public=module_public,
-                                         normalized=node.normalized)
+                                         normalized=node.normalized,
+                                         alias_tvars=node.alias_tvars)
                 self.add_symbol(imported_id, symbol, imp)
             elif module and not missing:
                 # Missing attribute.
@@ -1304,20 +1433,32 @@ class SemanticAnalyzer(NodeVisitor):
     def normalize_type_alias(self, node: SymbolTableNode,
                              ctx: Context) -> SymbolTableNode:
         normalized = False
-        if node.fullname in type_aliases:
+        fullname = node.fullname
+        if fullname in type_aliases:
             # Node refers to an aliased type such as typing.List; normalize.
-            node = self.lookup_qualified(type_aliases[node.fullname], ctx)
+            node = self.lookup_qualified(type_aliases[fullname], ctx)
+            if node is None:
+                self.add_fixture_note(fullname, ctx)
+                return None
             normalized = True
-        if node.fullname in collections_type_aliases:
+        if fullname in collections_type_aliases:
             # Similar, but for types from the collections module like typing.DefaultDict
             self.add_module_symbol('collections', '__mypy_collections__', False, ctx)
-            node = self.lookup_qualified(collections_type_aliases[node.fullname], ctx)
+            node = self.lookup_qualified(collections_type_aliases[fullname], ctx)
             normalized = True
         if normalized:
             node = SymbolTableNode(node.kind, node.node,
-                                   node.mod_id, node.type_override, normalized=True)
+                                   node.mod_id, node.type_override,
+                                   normalized=True, alias_tvars=node.alias_tvars)
         return node
 
+    def add_fixture_note(self, fullname: str, ctx: Context) -> None:
+        self.note('Maybe your test fixture does not define "{}"?'.format(fullname), ctx)
+        if fullname in SUGGESTED_TEST_FIXTURES:
+            self.note(
+                'Consider adding [builtins fixtures/{}] to your test description'.format(
+                    SUGGESTED_TEST_FIXTURES[fullname]), ctx)
+
     def correct_relative_import(self, node: Union[ImportFrom, ImportAll]) -> str:
         if node.relative == 0:
             return node.id
@@ -1352,7 +1493,8 @@ class SemanticAnalyzer(NodeVisitor):
                     self.add_symbol(name, SymbolTableNode(node.kind, node.node,
                                                           self.cur_mod_id,
                                                           node.type_override,
-                                                          normalized=node.normalized), i)
+                                                          normalized=node.normalized,
+                                                          alias_tvars=node.alias_tvars), i)
         else:
             # Don't add any dummy symbols for 'from x import *' if 'x' is unknown.
             pass
@@ -1364,7 +1506,7 @@ class SemanticAnalyzer(NodeVisitor):
         else:
             var._fullname = self.qualified_name(name)
         var.is_ready = True
-        var.type = AnyType()
+        var.type = AnyType(from_unimported_type=is_import)
         var.is_suppressed_import = is_import
         self.add_symbol(name, SymbolTableNode(GDEF, var, self.cur_mod_id), context)
 
@@ -1394,6 +1536,9 @@ class SemanticAnalyzer(NodeVisitor):
                             self.lookup_fully_qualified,
                             tvar_scope,
                             self.fail,
+                            self.plugin,
+                            self.options,
+                            self.is_typeshed_stub_file,
                             aliasing=aliasing,
                             allow_tuple_literal=allow_tuple_literal,
                             allow_unnormalized=self.is_stub_file)
@@ -1421,26 +1566,11 @@ class SemanticAnalyzer(NodeVisitor):
             allow_tuple_literal = isinstance(s.lvalues[-1], (TupleExpr, ListExpr))
             s.type = self.anal_type(s.type, allow_tuple_literal=allow_tuple_literal)
         else:
-            # For simple assignments, allow binding type aliases.
-            # Also set the type if the rvalue is a simple literal.
+            # Set the type if the rvalue is a simple literal.
             if (s.type is None and len(s.lvalues) == 1 and
                     isinstance(s.lvalues[0], NameExpr)):
                 if s.lvalues[0].is_def:
                     s.type = self.analyze_simple_literal_type(s.rvalue)
-                res = analyze_type_alias(s.rvalue,
-                                         self.lookup_qualified,
-                                         self.lookup_fully_qualified,
-                                         self.tvar_scope,
-                                         self.fail, allow_unnormalized=True)
-                if res and (not isinstance(res, Instance) or res.args):
-                    # TODO: What if this gets reassigned?
-                    name = s.lvalues[0]
-                    node = self.lookup(name.name, name)
-                    node.kind = TYPE_ALIAS
-                    node.type_override = res
-                    if isinstance(s.rvalue, IndexExpr):
-                        s.rvalue.analyzed = TypeAliasExpr(res,
-                                                          fallback=self.alias_fallback(res))
         if s.type:
             # Store type into nodes.
             for lvalue in s.lvalues:
@@ -1451,6 +1581,8 @@ class SemanticAnalyzer(NodeVisitor):
         self.process_namedtuple_definition(s)
         self.process_typeddict_definition(s)
         self.process_enum_call(s)
+        if not s.type:
+            self.process_module_assignment(s.lvalues, s.rvalue, 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
@@ -1492,26 +1624,79 @@ class SemanticAnalyzer(NodeVisitor):
         fb_info.mro = [fb_info, self.object_type().type]
         return Instance(fb_info, [])
 
+    def analyze_alias(self, rvalue: Expression,
+                      allow_unnormalized: bool) -> Tuple[Optional[Type], List[str]]:
+        """Check if 'rvalue' represents a valid type allowed for aliasing
+        (e.g. not a type variable). If yes, return the corresponding type and a list of
+        qualified type variable names for generic aliases.
+        If 'allow_unnormalized' is True, allow types like builtins.list[T].
+        """
+        res = analyze_type_alias(rvalue,
+                                 self.lookup_qualified,
+                                 self.lookup_fully_qualified,
+                                 self.tvar_scope,
+                                 self.fail,
+                                 self.plugin,
+                                 self.options,
+                                 self.is_typeshed_stub_file,
+                                 allow_unnormalized=True)
+        if res:
+            alias_tvars = [name for (name, _) in
+                           res.accept(TypeVariableQuery(self.lookup_qualified, self.tvar_scope))]
+        else:
+            alias_tvars = []
+        return res, alias_tvars
+
     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.
-        if (len(s.lvalues) == 1 and not self.is_func_scope() and not self.type
+        """Check if assignment creates a type alias and set it up as needed.
+        For simple aliases like L = List we use a simpler mechanism, just copying TypeInfo.
+        For subscripted (including generic) aliases the resulting types are stored
+        in rvalue.analyzed.
+        """
+        # Type aliases are created only at module scope and class scope (for subscripted types),
+        # at function scope assignments always create local variables with type object types.
+        lvalue = s.lvalues[0]
+        if not isinstance(lvalue, NameExpr):
+            return
+        if (len(s.lvalues) == 1 and not self.is_func_scope() and
+                not (self.type and isinstance(s.rvalue, NameExpr) and lvalue.is_def)
                 and not s.type):
-            lvalue = s.lvalues[0]
-            if isinstance(lvalue, NameExpr):
-                if not lvalue.is_def:
-                    # Only a definition can create a type alias, not regular assignment.
-                    return
-                rvalue = s.rvalue
+            rvalue = s.rvalue
+            res, alias_tvars = self.analyze_alias(rvalue, allow_unnormalized=True)
+            if not res:
+                return
+            node = self.lookup(lvalue.name, lvalue)
+            if not lvalue.is_def:
+                # Only a definition can create a type alias, not regular assignment.
+                if node and node.kind == TYPE_ALIAS or isinstance(node.node, TypeInfo):
+                    self.fail('Cannot assign multiple types to name "{}"'
+                              ' without an explicit "Type[...]" annotation'
+                              .format(lvalue.name), lvalue)
+                return
+            check_for_explicit_any(res, self.options, self.is_typeshed_stub_file, self.msg,
+                                   context=s)
+            # when this type alias gets "inlined", the Any is not explicit anymore,
+            # so we need to replace it with non-explicit Anys
+            res = make_any_non_explicit(res)
+            if isinstance(res, Instance) and not res.args and isinstance(rvalue, RefExpr):
+                # For simple (on-generic) aliases we use aliasing TypeInfo's
+                # to allow using them in runtime context where it makes sense.
+                node.node = res.type
                 if isinstance(rvalue, RefExpr):
-                    node = rvalue.node
-                    if isinstance(node, TypeInfo):
-                        # TODO: We should record the fact that this is a variable
-                        #       that refers to a type, rather than making this
-                        #       just an alias for the type.
-                        sym = self.lookup_type_node(rvalue)
-                        if sym:
-                            self.globals[lvalue.name] = sym
+                    sym = self.lookup_type_node(rvalue)
+                    if sym:
+                        node.normalized = sym.normalized
+                return
+            node.kind = TYPE_ALIAS
+            node.type_override = res
+            node.alias_tvars = alias_tvars
+            if isinstance(rvalue, IndexExpr):
+                # We only need this for subscripted aliases, since simple aliases
+                # are already processed using aliasing TypeInfo's above.
+                rvalue.analyzed = TypeAliasExpr(res, node.alias_tvars,
+                                                fallback=self.alias_fallback(res))
+                rvalue.analyzed.line = rvalue.line
+                rvalue.analyzed.column = rvalue.column
 
     def analyze_lvalue(self, lval: Lvalue, nested: bool = False,
                        add_global: bool = False,
@@ -1562,6 +1747,7 @@ class SemanticAnalyzer(NodeVisitor):
                 v.info = self.type
                 v.is_initialized_in_class = True
                 v.set_line(lval)
+                v._fullname = self.qualified_name(lval.name)
                 lval.node = v
                 lval.is_def = True
                 lval.kind = MDEF
@@ -1696,6 +1882,12 @@ class SemanticAnalyzer(NodeVisitor):
             self.fail(message.format(old_type), s)
             return
 
+        check_for_explicit_any(old_type, self.options, self.is_typeshed_stub_file, self.msg,
+                               context=s)
+
+        if 'unimported' in self.options.disallow_any and has_any_from_unimported_type(old_type):
+            self.msg.unimported_type_becomes_any("Argument 2 to NewType(...)", old_type, s)
+
         # If so, add it to the symbol table.
         node = self.lookup(name, s)
         if node is None:
@@ -1753,10 +1945,6 @@ class SemanticAnalyzer(NodeVisitor):
             return None
         old_type = self.anal_type(unanalyzed_type)
 
-        if isinstance(old_type, Instance) and old_type.type.is_newtype:
-            self.fail("Argument 2 to NewType(...) cannot be another NewType", context)
-            has_failed = True
-
         return None if has_failed else old_type
 
     def build_newtype_typeinfo(self, name: str, old_type: Type, base_type: Instance) -> TypeInfo:
@@ -1811,6 +1999,19 @@ class SemanticAnalyzer(NodeVisitor):
             return
         variance, upper_bound = res
 
+        if 'unimported' in self.options.disallow_any:
+            for idx, constraint in enumerate(values, start=1):
+                if has_any_from_unimported_type(constraint):
+                    prefix = "Constraint {}".format(idx)
+                    self.msg.unimported_type_becomes_any(prefix, constraint, s)
+
+            if has_any_from_unimported_type(upper_bound):
+                prefix = "Upper bound of type variable"
+                self.msg.unimported_type_becomes_any(prefix, upper_bound, s)
+
+        for t in values + [upper_bound]:
+            check_for_explicit_any(t, self.options, self.is_typeshed_stub_file, self.msg,
+                                   context=s)
         # Yes, it's a valid type variable definition! Add it to the symbol table.
         node = self.lookup(name, s)
         node.kind = TVAR
@@ -2090,6 +2291,8 @@ class SemanticAnalyzer(NodeVisitor):
         add_field(Var('_field_types', dictype), is_initialized_in_class=True)
         add_field(Var('_field_defaults', dictype), is_initialized_in_class=True)
         add_field(Var('_source', strtype), is_initialized_in_class=True)
+        add_field(Var('__annotations__', ordereddictype), is_initialized_in_class=True)
+        add_field(Var('__doc__', strtype), is_initialized_in_class=True)
 
         tvd = TypeVarDef('NT', 1, [], info.tuple_type)
         selftype = TypeVarType(tvd)
@@ -2101,7 +2304,7 @@ class SemanticAnalyzer(NodeVisitor):
                        is_classmethod: bool = False,
                        ) -> None:
             if is_classmethod:
-                first = [Argument(Var('cls'), TypeType(selftype), None, ARG_POS)]
+                first = [Argument(Var('cls'), TypeType.make_normalized(selftype), None, ARG_POS)]
             else:
                 first = [Argument(Var('self'), selftype, None, ARG_POS)]
             args = first + args
@@ -2189,46 +2392,77 @@ class SemanticAnalyzer(NodeVisitor):
         fullname = callee.fullname
         if fullname != 'mypy_extensions.TypedDict':
             return None
-        items, types, ok = self.parse_typeddict_args(call, fullname)
+        items, types, total, ok = self.parse_typeddict_args(call, fullname)
         if not ok:
             # Error. Construct dummy return value.
-            return self.build_typeddict_typeinfo('TypedDict', [], [])
-        name = cast(StrExpr, call.args[0]).value
-        if name != var_name or self.is_func_scope():
-            # Give it a unique name derived from the line number.
-            name += '@' + str(call.line)
-        info = self.build_typeddict_typeinfo(name, items, types)
-        # Store it as a global just in case it would remain anonymous.
-        # (Or in the nearest class if there is one.)
-        stnode = SymbolTableNode(GDEF, info, self.cur_mod_id)
-        if self.type:
-            self.type.names[name] = stnode
+            info = self.build_typeddict_typeinfo('TypedDict', [], [], set())
         else:
-            self.globals[name] = stnode
+            name = cast(StrExpr, call.args[0]).value
+            if var_name is not None and name != var_name:
+                self.fail(
+                    "First argument '{}' to TypedDict() does not match variable name '{}'".format(
+                        name, var_name), node)
+            if name != var_name or self.is_func_scope():
+                # Give it a unique name derived from the line number.
+                name += '@' + str(call.line)
+            required_keys = set(items) if total else set()
+            info = self.build_typeddict_typeinfo(name, items, types, required_keys)
+            # Store it as a global just in case it would remain anonymous.
+            # (Or in the nearest class if there is one.)
+            stnode = SymbolTableNode(GDEF, info, self.cur_mod_id)
+            if self.type:
+                self.type.names[name] = stnode
+            else:
+                self.globals[name] = stnode
         call.analyzed = TypedDictExpr(info)
         call.analyzed.set_line(call.line, call.column)
         return info
 
     def parse_typeddict_args(self, call: CallExpr,
-                             fullname: str) -> Tuple[List[str], List[Type], bool]:
+                             fullname: str) -> Tuple[List[str], List[Type], bool, bool]:
         # TODO: Share code with check_argument_count in checkexpr.py?
         args = call.args
         if len(args) < 2:
             return self.fail_typeddict_arg("Too few arguments for TypedDict()", call)
-        if len(args) > 2:
+        if len(args) > 3:
             return self.fail_typeddict_arg("Too many arguments for TypedDict()", call)
         # TODO: Support keyword arguments
-        if call.arg_kinds != [ARG_POS, ARG_POS]:
+        if call.arg_kinds not in ([ARG_POS, ARG_POS], [ARG_POS, ARG_POS, ARG_NAMED]):
             return self.fail_typeddict_arg("Unexpected arguments to TypedDict()", call)
+        if len(args) == 3 and call.arg_names[2] != 'total':
+            return self.fail_typeddict_arg(
+                'Unexpected keyword argument "{}" for "TypedDict"'.format(call.arg_names[2]), call)
         if not isinstance(args[0], (StrExpr, BytesExpr, UnicodeExpr)):
             return self.fail_typeddict_arg(
                 "TypedDict() expects a string literal as the first argument", call)
         if not isinstance(args[1], DictExpr):
             return self.fail_typeddict_arg(
                 "TypedDict() expects a dictionary literal as the second argument", call)
+        total = True
+        if len(args) == 3:
+            total = self.parse_bool(call.args[2])
+            if total is None:
+                return self.fail_typeddict_arg(
+                    'TypedDict() "total" argument must be True or False', call)
         dictexpr = args[1]
         items, types, ok = self.parse_typeddict_fields_with_types(dictexpr.items, call)
-        return items, types, ok
+        for t in types:
+            check_for_explicit_any(t, self.options, self.is_typeshed_stub_file, self.msg,
+                                   context=call)
+
+        if 'unimported' in self.options.disallow_any:
+            for t in types:
+                if has_any_from_unimported_type(t):
+                    self.msg.unimported_type_becomes_any("Type of a TypedDict key", t, dictexpr)
+        return items, types, total, ok
+
+    def parse_bool(self, expr: Expression) -> Optional[bool]:
+        if isinstance(expr, NameExpr):
+            if expr.fullname == 'builtins.True':
+                return True
+            if expr.fullname == 'builtins.False':
+                return False
+        return None
 
     def parse_typeddict_fields_with_types(self, dict_items: List[Tuple[Expression, Expression]],
                                           context: Context) -> Tuple[List[str], List[Type], bool]:
@@ -2238,29 +2472,40 @@ class SemanticAnalyzer(NodeVisitor):
             if isinstance(field_name_expr, (StrExpr, BytesExpr, UnicodeExpr)):
                 items.append(field_name_expr.value)
             else:
-                return self.fail_typeddict_arg("Invalid TypedDict() field name", field_name_expr)
+                self.fail_typeddict_arg("Invalid TypedDict() field name", field_name_expr)
+                return [], [], False
             try:
                 type = expr_to_unanalyzed_type(field_type_expr)
             except TypeTranslationError:
-                return self.fail_typeddict_arg('Invalid field type', field_type_expr)
+                self.fail_typeddict_arg('Invalid field type', field_type_expr)
+                return [], [], False
             types.append(self.anal_type(type))
         return items, types, True
 
     def fail_typeddict_arg(self, message: str,
-                           context: Context) -> Tuple[List[str], List[Type], bool]:
+                           context: Context) -> Tuple[List[str], List[Type], bool, bool]:
         self.fail(message, context)
-        return [], [], False
+        return [], [], True, False
 
     def build_typeddict_typeinfo(self, name: str, items: List[str],
-                                 types: List[Type]) -> TypeInfo:
-        mapping_value_type = join.join_type_list(types)
+                                 types: List[Type],
+                                 required_keys: Set[str]) -> TypeInfo:
         fallback = (self.named_type_or_none('typing.Mapping',
-                                            [self.str_type(), mapping_value_type])
+                                            [self.str_type(), self.object_type()])
                     or self.object_type())
 
-        info = self.basic_new_typeinfo(name, fallback)
-        info.typeddict_type = TypedDictType(OrderedDict(zip(items, types)), fallback)
+        def patch() -> None:
+            # Calculate the correct value type for the fallback Mapping.
+            fallback.args[1] = join.join_type_list(types)
+
+        # We can't calculate the complete fallback type until after semantic
+        # analysis, since otherwise MROs might be incomplete. Postpone a callback
+        # function that patches the fallback.
+        self.patches.append(patch)
 
+        info = self.basic_new_typeinfo(name, fallback)
+        info.typeddict_type = TypedDictType(OrderedDict(zip(items, types)), required_keys,
+                                            fallback)
         return info
 
     def check_classvar(self, s: AssignmentStmt) -> None:
@@ -2289,6 +2534,66 @@ class SemanticAnalyzer(NodeVisitor):
     def fail_invalid_classvar(self, context: Context) -> None:
         self.fail('ClassVar can only be used for assignments in class body', context)
 
+    def process_module_assignment(self, lvals: List[Expression], rval: Expression,
+                                  ctx: AssignmentStmt) -> None:
+        """Propagate module references across assignments.
+
+        Recursively handles the simple form of iterable unpacking; doesn't
+        handle advanced unpacking with *rest, dictionary unpacking, etc.
+
+        In an expression like x = y = z, z is the rval and lvals will be [x,
+        y].
+
+        """
+        if all(isinstance(v, (TupleExpr, ListExpr)) for v in lvals + [rval]):
+            # rval and all lvals are either list or tuple, so we are dealing
+            # with unpacking assignment like `x, y = a, b`. Mypy didn't
+            # understand our all(isinstance(...)), so cast them as
+            # Union[TupleExpr, ListExpr] so mypy knows it is safe to access
+            # their .items attribute.
+            seq_lvals = cast(List[Union[TupleExpr, ListExpr]], lvals)
+            seq_rval = cast(Union[TupleExpr, ListExpr], rval)
+            # given an assignment like:
+            #     (x, y) = (m, n) = (a, b)
+            # we now have:
+            #     seq_lvals = [(x, y), (m, n)]
+            #     seq_rval = (a, b)
+            # We now zip this into:
+            #     elementwise_assignments = [(a, x, m), (b, y, n)]
+            # where each elementwise assignment includes one element of rval and the
+            # corresponding element of each lval. Basically we unpack
+            #     (x, y) = (m, n) = (a, b)
+            # into elementwise assignments
+            #     x = m = a
+            #     y = n = b
+            # and then we recursively call this method for each of those assignments.
+            # If the rval and all lvals are not all of the same length, zip will just ignore
+            # extra elements, so no error will be raised here; mypy will later complain
+            # about the length mismatch in type-checking.
+            elementwise_assignments = zip(seq_rval.items, *[v.items for v in seq_lvals])
+            for rv, *lvs in elementwise_assignments:
+                self.process_module_assignment(lvs, rv, ctx)
+        elif isinstance(rval, NameExpr):
+            rnode = self.lookup(rval.name, ctx)
+            if rnode and rnode.kind == MODULE_REF:
+                for lval in lvals:
+                    if not isinstance(lval, NameExpr):
+                        continue
+                    # respect explicitly annotated type
+                    if (isinstance(lval.node, Var) and lval.node.type is not None):
+                        continue
+                    lnode = self.lookup(lval.name, ctx)
+                    if lnode:
+                        if lnode.kind == MODULE_REF and lnode.node is not rnode.node:
+                            self.fail(
+                                "Cannot assign multiple modules to name '{}' "
+                                "without explicit 'types.ModuleType' annotation".format(lval.name),
+                                ctx)
+                        # never create module alias except on initial var definition
+                        elif lval.is_def:
+                            lnode.kind = MODULE_REF
+                            lnode.node = rnode.node
+
     def process_enum_call(self, s: AssignmentStmt) -> None:
         """Check if s defines an Enum; if yes, store the definition in symbol table."""
         if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):
@@ -2860,24 +3165,50 @@ class SemanticAnalyzer(NodeVisitor):
                 if full_name in obsolete_name_mapping:
                     self.fail("Module%s has no attribute %r (it's now called %r)" % (
                         mod_name, expr.name, obsolete_name_mapping[full_name]), expr)
-        elif isinstance(base, RefExpr) and isinstance(base.node, TypeInfo):
-            n = base.node.names.get(expr.name)
-            if n is not None and (n.kind == MODULE_REF or isinstance(n.node, TypeInfo)):
-                # This branch handles the case C.bar where C is a class and
-                # bar is a type definition or a module resulting from
-                # `import bar` inside class C. Here base.node is a TypeInfo,
-                # and again we look up the name in its namespace.
-                # This is done only when bar is a module or a type; other
-                # things (e.g. methods) are handled by other code in checkmember.
-                n = self.normalize_type_alias(n, expr)
-                if not n:
-                    return
-                expr.kind = n.kind
-                expr.fullname = n.fullname
-                expr.node = n.node
+        elif isinstance(base, RefExpr):
+            # This branch handles the case C.bar (or cls.bar or self.bar inside
+            # a classmethod/method), where C is a class and bar is a type
+            # definition or a module resulting from `import bar` (or a module
+            # assignment) inside class C. We look up bar in the class' TypeInfo
+            # namespace.  This is done only when bar is a module or a type;
+            # other things (e.g. methods) are handled by other code in
+            # checkmember.
+            type_info = None
+            if isinstance(base.node, TypeInfo):
+                # C.bar where C is a class
+                type_info = base.node
+            elif isinstance(base.node, Var) and self.type and self.function_stack:
+                # check for self.bar or cls.bar in method/classmethod
+                func_def = self.function_stack[-1]
+                if not func_def.is_static and isinstance(func_def.type, CallableType):
+                    formal_arg = func_def.type.argument_by_name(base.node.name())
+                    if formal_arg and formal_arg.pos == 0:
+                        type_info = self.type
+            if type_info:
+                n = type_info.names.get(expr.name)
+                if n is not None and (n.kind == MODULE_REF or isinstance(n.node, TypeInfo)):
+                    n = self.normalize_type_alias(n, expr)
+                    if not n:
+                        return
+                    expr.kind = n.kind
+                    expr.fullname = n.fullname
+                    expr.node = n.node
 
     def visit_op_expr(self, expr: OpExpr) -> None:
         expr.left.accept(self)
+
+        if expr.op in ('and', 'or'):
+            inferred = infer_condition_value(expr.left,
+                                             pyversion=self.options.python_version,
+                                             platform=self.options.platform)
+            if ((inferred == ALWAYS_FALSE and expr.op == 'and') or
+                    (inferred == ALWAYS_TRUE and expr.op == 'or')):
+                expr.right_unreachable = True
+                return
+            elif ((inferred == ALWAYS_TRUE and expr.op == 'and') or
+                    (inferred == ALWAYS_FALSE and expr.op == 'or')):
+                expr.right_always = True
+
         expr.right.accept(self)
 
     def visit_comparison_expr(self, expr: ComparisonExpr) -> None:
@@ -2896,13 +3227,11 @@ class SemanticAnalyzer(NodeVisitor):
         elif isinstance(expr.base, RefExpr) and expr.base.kind == TYPE_ALIAS:
             # Special form -- subscripting a generic type alias.
             # Perform the type substitution and create a new alias.
-            res = analyze_type_alias(expr,
-                                     self.lookup_qualified,
-                                     self.lookup_fully_qualified,
-                                     self.tvar_scope,
-                                     self.fail, allow_unnormalized=self.is_stub_file)
-            expr.analyzed = TypeAliasExpr(res, fallback=self.alias_fallback(res),
+            res, alias_tvars = self.analyze_alias(expr, allow_unnormalized=self.is_stub_file)
+            expr.analyzed = TypeAliasExpr(res, alias_tvars, fallback=self.alias_fallback(res),
                                           in_runtime=True)
+            expr.analyzed.line = expr.line
+            expr.analyzed.column = expr.column
         elif refers_to_class_or_function(expr.base):
             # Special form -- type application.
             # Translate index to an unanalyzed type.
@@ -3249,7 +3578,7 @@ class SemanticAnalyzer(NodeVisitor):
             elif prev_is_overloaded:
                 self.fail("Definition of '{}' missing 'overload'".format(n), ctx)
             else:
-                self.name_already_defined(n, ctx)
+                self.name_already_defined(n, ctx, self.globals[n])
 
     def name_not_defined(self, name: str, ctx: Context) -> None:
         message = "Name '{}' is not defined".format(name)
@@ -3257,9 +3586,23 @@ class SemanticAnalyzer(NodeVisitor):
         if extra:
             message += ' {}'.format(extra)
         self.fail(message, ctx)
-
-    def name_already_defined(self, name: str, ctx: Context) -> None:
-        self.fail("Name '{}' already defined".format(name), ctx)
+        if 'builtins.{}'.format(name) in SUGGESTED_TEST_FIXTURES:
+            # The user probably has a missing definition in a test fixture. Let's verify.
+            fullname = 'builtins.{}'.format(name)
+            if self.lookup_fully_qualified_or_none(fullname) is None:
+                # Yes. Generate a helpful note.
+                self.add_fixture_note(fullname, ctx)
+
+    def name_already_defined(self, name: str, ctx: Context,
+                             original_ctx: Optional[SymbolTableNode] = None) -> None:
+        if original_ctx:
+            if original_ctx.node and original_ctx.node.get_line() != -1:
+                extra_msg = ' on line {}'.format(original_ctx.node.get_line())
+            else:
+                extra_msg = ' (possibly by an import)'
+        else:
+            extra_msg = ''
+        self.fail("Name '{}' already defined{}".format(name, extra_msg), ctx)
 
     def fail(self, msg: str, ctx: Context, serious: bool = False, *,
              blocker: bool = False) -> None:
@@ -3332,52 +3675,54 @@ class FirstPass(NodeVisitor):
 
         defs = file.defs
 
-        # Add implicit definitions of module '__name__' etc.
-        for name, t in implicit_module_attrs.items():
-            # unicode docstrings should be accepted in Python 2
-            if name == '__doc__':
-                if self.pyversion >= (3, 0):
-                    typ = UnboundType('__builtins__.str')  # type: Type
+        with experiments.strict_optional_set(options.strict_optional):
+            # Add implicit definitions of module '__name__' etc.
+            for name, t in implicit_module_attrs.items():
+                # unicode docstrings should be accepted in Python 2
+                if name == '__doc__':
+                    if self.pyversion >= (3, 0):
+                        typ = UnboundType('__builtins__.str')  # type: Type
+                    else:
+                        typ = UnionType([UnboundType('__builtins__.str'),
+                                        UnboundType('__builtins__.unicode')])
                 else:
-                    typ = UnionType([UnboundType('__builtins__.str'),
-                                     UnboundType('__builtins__.unicode')])
-            else:
-                assert t is not None, 'type should be specified for {}'.format(name)
-                typ = UnboundType(t)
-            v = Var(name, typ)
-            v._fullname = self.sem.qualified_name(name)
-            self.sem.globals[name] = SymbolTableNode(GDEF, v, self.sem.cur_mod_id)
-
-        for d in defs:
-            d.accept(self)
-
-        # Add implicit definition of literals/keywords to builtins, as we
-        # cannot define a variable with them explicitly.
-        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
-            # fake builtins for its tests which often don't define bool.  If
-            # mypy is fast enough that we no longer need those, this
-            # conditional check should be removed.
-            if 'bool' in self.sem.globals:
-                bool_type = self.sem.named_type('bool')
-                literal_types.extend([
-                    ('True', bool_type),
-                    ('False', bool_type),
-                    ('__debug__', bool_type),
-                ])
-
-            for name, typ in literal_types:
+                    assert t is not None, 'type should be specified for {}'.format(name)
+                    typ = UnboundType(t)
                 v = Var(name, typ)
                 v._fullname = self.sem.qualified_name(name)
                 self.sem.globals[name] = SymbolTableNode(GDEF, v, self.sem.cur_mod_id)
 
-        del self.sem.options
+            for d in defs:
+                d.accept(self)
+
+            # Add implicit definition of literals/keywords to builtins, as we
+            # cannot define a variable with them explicitly.
+            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
+                # fake builtins for its tests which often don't define bool.  If
+                # mypy is fast enough that we no longer need those, this
+                # conditional check should be removed.
+                if 'bool' in self.sem.globals:
+                    bool_type = self.sem.named_type('bool')
+                    literal_types.extend([
+                        ('True', bool_type),
+                        ('False', bool_type),
+                        ('__debug__', bool_type),
+                    ])
+
+                for name, typ in literal_types:
+                    v = Var(name, typ)
+                    v._fullname = self.sem.qualified_name(name)
+                    self.sem.globals[name] = SymbolTableNode(GDEF, v, self.sem.cur_mod_id)
+
+            del self.sem.options
 
     def visit_block(self, b: Block) -> None:
         if b.is_unreachable:
@@ -3462,7 +3807,7 @@ class FirstPass(NodeVisitor):
         self.process_nested_classes(cdef)
 
     def process_nested_classes(self, outer_def: ClassDef) -> None:
-        self.sem.enter_class(outer_def)
+        self.sem.enter_class(outer_def.info)
         for node in outer_def.defs.body:
             if isinstance(node, ClassDef):
                 node.info = TypeInfo(SymbolTable(), node, self.sem.cur_mod_id)
@@ -3571,7 +3916,9 @@ class ThirdPass(TraverserVisitor):
     def visit_file(self, file_node: MypyFile, fnam: str, options: Options) -> None:
         self.errors.set_file(fnam, file_node.fullname())
         self.options = options
-        self.accept(file_node)
+        self.is_typeshed_file = self.errors.is_typeshed_file(fnam)
+        with experiments.strict_optional_set(options.strict_optional):
+            self.accept(file_node)
 
     def refresh_partial(self, node: Union[MypyFile, FuncItem]) -> None:
         """Refresh a stale target in fine-grained incremental mode."""
@@ -3604,14 +3951,22 @@ class ThirdPass(TraverserVisitor):
         self.errors.pop_function()
 
     def visit_class_def(self, tdef: ClassDef) -> None:
-        for type in tdef.info.bases:
-            self.analyze(type)
+        # NamedTuple base classes are validated in check_namedtuple_classdef; we don't have to
+        # check them again here.
+        if not tdef.info.is_named_tuple:
+            for type in tdef.info.bases:
+                self.analyze(type)
         # Recompute MRO now that we have analyzed all modules, to pick
         # up superclasses of bases imported from other modules in an
         # import loop. (Only do so if we succeeded the first time.)
         if tdef.info.mro:
             tdef.info.mro = []  # Force recomputation
             calculate_class_mro(tdef, self.fail_blocker)
+        if tdef.analyzed is not None:
+            if isinstance(tdef.analyzed, TypedDictExpr):
+                self.analyze(tdef.analyzed.info.typeddict_type)
+            elif isinstance(tdef.analyzed, NamedTupleExpr):
+                self.analyze(tdef.analyzed.info.tuple_type)
         super().visit_class_def(tdef)
 
     def visit_decorator(self, dec: Decorator) -> None:
@@ -3668,6 +4023,13 @@ class ThirdPass(TraverserVisitor):
         self.analyze(s.type)
         if isinstance(s.rvalue, IndexExpr) and isinstance(s.rvalue.analyzed, TypeAliasExpr):
             self.analyze(s.rvalue.analyzed.type)
+        if isinstance(s.rvalue, CallExpr):
+            if isinstance(s.rvalue.analyzed, NewTypeExpr):
+                self.analyze(s.rvalue.analyzed.old_type)
+            if isinstance(s.rvalue.analyzed, TypedDictExpr):
+                self.analyze(s.rvalue.analyzed.info.typeddict_type)
+            if isinstance(s.rvalue.analyzed, NamedTupleExpr):
+                self.analyze(s.rvalue.analyzed.info.tuple_type)
         super().visit_assignment_stmt(s)
 
     def visit_cast_expr(self, e: CastExpr) -> None:
@@ -3684,10 +4046,19 @@ class ThirdPass(TraverserVisitor):
 
     # Helpers
 
-    def analyze(self, type: Type) -> None:
+    def analyze(self, type: Optional[Type]) -> None:
         if type:
-            analyzer = TypeAnalyserPass3(self.fail)
+            analyzer = TypeAnalyserPass3(self.fail, self.options, self.is_typeshed_file)
             type.accept(analyzer)
+            self.check_for_omitted_generics(type)
+
+    def check_for_omitted_generics(self, typ: Type) -> None:
+        if 'generics' not in self.options.disallow_any or self.is_typeshed_file:
+            return
+
+        for t in collect_any_types(typ):
+            if t.from_omitted_generics:
+                self.fail(messages.BARE_GENERIC, t)
 
     def fail(self, msg: str, ctx: Context, *, blocker: bool = False) -> None:
         self.errors.report(ctx.get_line(), ctx.get_column(), msg)
@@ -3779,7 +4150,7 @@ def infer_reachability_of_if_statement(s: IfStmt,
                                        pyversion: Tuple[int, int],
                                        platform: str) -> None:
     for i in range(len(s.expr)):
-        result = infer_if_condition_value(s.expr[i], pyversion, platform)
+        result = infer_condition_value(s.expr[i], pyversion, platform)
         if result in (ALWAYS_FALSE, MYPY_FALSE):
             # The condition is considered always false, so we skip the if/elif body.
             mark_block_unreachable(s.body[i])
@@ -3792,13 +4163,19 @@ def infer_reachability_of_if_statement(s: IfStmt,
                 mark_block_mypy_only(s.body[i])
             for body in s.body[i + 1:]:
                 mark_block_unreachable(body)
-            if s.else_body:
-                mark_block_unreachable(s.else_body)
+
+            # Make sure else body always exists and is marked as
+            # unreachable so the type checker always knows that
+            # all control flow paths will flow through the if
+            # statement body.
+            if not s.else_body:
+                s.else_body = Block([])
+            mark_block_unreachable(s.else_body)
             break
 
 
-def infer_if_condition_value(expr: Expression, pyversion: Tuple[int, int], platform: str) -> int:
-    """Infer whether if condition is always true/false.
+def infer_condition_value(expr: Expression, pyversion: Tuple[int, int], platform: str) -> int:
+    """Infer whether the given condition is always true/false.
 
     Return ALWAYS_TRUE if always true, ALWAYS_FALSE if always false,
     MYPY_TRUE if true under mypy and false at runtime, MYPY_FALSE if
@@ -3816,6 +4193,17 @@ def infer_if_condition_value(expr: Expression, pyversion: Tuple[int, int], platf
         name = expr.name
     elif isinstance(expr, MemberExpr):
         name = expr.name
+    elif isinstance(expr, OpExpr) and expr.op in ('and', 'or'):
+        left = infer_condition_value(expr.left, pyversion, platform)
+        if ((left == ALWAYS_TRUE and expr.op == 'and') or
+                (left == ALWAYS_FALSE and expr.op == 'or')):
+            # Either `True and <other>` or `False or <other>`: the result will
+            # always be the right-hand-side.
+            return infer_condition_value(expr.right, pyversion, platform)
+        else:
+            # The result will always be the left-hand-side (e.g. ALWAYS_* or
+            # TRUTH_VALUE_UNKNOWN).
+            return left
     else:
         result = consider_sys_version_info(expr, pyversion)
         if result == TRUTH_VALUE_UNKNOWN:
@@ -4065,3 +4453,13 @@ def find_fixed_callable_return(expr: Expression) -> Optional[CallableType]:
             if isinstance(t.ret_type, CallableType):
                 return t.ret_type
     return None
+
+
+def make_any_non_explicit(t: Type) -> Type:
+    """Replace all Any types within in with Any that has attribute 'explicit' set to False"""
+    return t.accept(MakeAnyNonExplicit())
+
+
+class MakeAnyNonExplicit(TypeTranslator):
+    def visit_any(self, t: AnyType) -> Type:
+        return t.copy_modified(explicit=False)
diff --git a/mypy/stats.py b/mypy/stats.py
index 3739763..de56036 100644
--- a/mypy/stats.py
+++ b/mypy/stats.py
@@ -3,7 +3,7 @@
 import cgi
 import os.path
 
-from typing import Any, Dict, List, cast, Tuple
+from typing import Dict, List, cast, Tuple, Set, Optional
 
 from mypy.traverser import TraverserVisitor
 from mypy.types import (
@@ -12,17 +12,19 @@ from mypy.types import (
 from mypy import nodes
 from mypy.nodes import (
     Expression, FuncDef, TypeApplication, AssignmentStmt, NameExpr, CallExpr, MypyFile,
-    MemberExpr, OpExpr, ComparisonExpr, IndexExpr, UnaryExpr, YieldFromExpr, RefExpr
+    MemberExpr, OpExpr, ComparisonExpr, IndexExpr, UnaryExpr, YieldFromExpr, RefExpr, ClassDef
 )
 
 
 TYPE_EMPTY = 0
-TYPE_PRECISE = 1
-TYPE_IMPRECISE = 2
-TYPE_ANY = 3
+TYPE_UNANALYZED = 1  # type of non-typechecked code
+TYPE_PRECISE = 2
+TYPE_IMPRECISE = 3
+TYPE_ANY = 4
 
 precision_names = [
     'empty',
+    'unanalyzed',
     'precise',
     'imprecise',
     'any',
@@ -30,9 +32,10 @@ precision_names = [
 
 
 class StatisticsVisitor(TraverserVisitor):
-    def __init__(self, inferred: bool, typemap: Dict[Expression, Type] = None,
+    def __init__(self, inferred: bool, filename: str, typemap: Dict[Expression, Type] = None,
                  all_nodes: bool = False) -> None:
         self.inferred = inferred
+        self.filename = filename
         self.typemap = typemap
         self.all_nodes = all_nodes
 
@@ -57,9 +60,10 @@ class StatisticsVisitor(TraverserVisitor):
 
     def visit_func_def(self, o: FuncDef) -> None:
         self.line = o.line
-        if len(o.expanded) > 1:
+        if len(o.expanded) > 1 and o.expanded != [o] * len(o.expanded):
             if o in o.expanded:
-                print('ERROR: cycle in function expansion; skipping')
+                print('{}:{}: ERROR: cycle in function expansion; skipping'.format(self.filename,
+                                                                                   o.get_line()))
                 return
             for defn in o.expanded:
                 self.visit_func_def(cast(FuncDef, defn))
@@ -77,6 +81,15 @@ class StatisticsVisitor(TraverserVisitor):
                 self.record_line(self.line, TYPE_ANY)
             super().visit_func_def(o)
 
+    def visit_class_def(self, o: ClassDef) -> None:
+        # Override this method because we don't want to analyze base_type_exprs (base_type_exprs
+        # are base classes in a class declaration).
+        # While base_type_exprs are technically expressions, type analyzer does not visit them and
+        # they are not in the typemap.
+        for d in o.decorators:
+            d.accept(self)
+        o.defs.accept(self)
+
     def visit_type_application(self, o: TypeApplication) -> None:
         self.line = o.line
         for t in o.types:
@@ -101,7 +114,10 @@ class StatisticsVisitor(TraverserVisitor):
                     items = [lvalue]
                 for item in items:
                     if isinstance(item, RefExpr) and item.is_def:
-                        t = self.typemap.get(item)
+                        if self.typemap is not None:
+                            t = self.typemap.get(item)
+                        else:
+                            t = None
                         if t:
                             self.type(t)
                         else:
@@ -149,12 +165,22 @@ class StatisticsVisitor(TraverserVisitor):
 
     def process_node(self, node: Expression) -> None:
         if self.all_nodes:
-            typ = self.typemap.get(node)
-            if typ:
+            if self.typemap is not None:
                 self.line = node.line
-                self.type(typ)
+                self.type(self.typemap.get(node))
+
+    def type(self, t: Optional[Type]) -> None:
+        if not t:
+            # If an expression does not have a type, it is often due to dead code.
+            # Don't count these because there can be an unanalyzed value on a line with other
+            # analyzed expressions, which overwrite the TYPE_UNANALYZED.
+            self.record_line(self.line, TYPE_UNANALYZED)
+            return
+
+        if isinstance(t, AnyType) and t.special_form:
+            # This is not a real Any type, so don't collect stats for it.
+            return
 
-    def type(self, t: Type) -> None:
         if isinstance(t, AnyType):
             self.log('  !! Any type around line %d' % self.line)
             self.num_any += 1
@@ -191,7 +217,7 @@ class StatisticsVisitor(TraverserVisitor):
 
     def record_line(self, line: int, precision: int) -> None:
         self.line_map[line] = max(precision,
-                                  self.line_map.get(line, TYPE_PRECISE))
+                                  self.line_map.get(line, TYPE_EMPTY))
 
 
 def dump_type_stats(tree: MypyFile, path: str, inferred: bool = False,
@@ -199,7 +225,7 @@ def dump_type_stats(tree: MypyFile, path: str, inferred: bool = False,
     if is_special_module(path):
         return
     print(path)
-    visitor = StatisticsVisitor(inferred, typemap)
+    visitor = StatisticsVisitor(inferred, filename=tree.fullname(), typemap=typemap)
     tree.accept(visitor)
     for line in visitor.output:
         print(line)
@@ -271,7 +297,8 @@ def generate_html_report(tree: MypyFile, path: str, type_map: Dict[Expression, T
     path = os.path.relpath(path)
     if path.startswith('..'):
         return
-    visitor = StatisticsVisitor(inferred=True, typemap=type_map, all_nodes=True)
+    visitor = StatisticsVisitor(inferred=True, filename=tree.fullname(), typemap=type_map,
+                                all_nodes=True)
     tree.accept(visitor)
     assert not os.path.isabs(path) and not path.startswith('..')
     # This line is *wrong* if the preceding assert fails.
diff --git a/mypy/stubgen.py b/mypy/stubgen.py
index 6e25ecd..bd1dbeb 100644
--- a/mypy/stubgen.py
+++ b/mypy/stubgen.py
@@ -73,6 +73,7 @@ Options = NamedTuple('Options', [('pyversion', Tuple[int, int]),
                                  ('modules', List[str]),
                                  ('ignore_errors', bool),
                                  ('recursive', bool),
+                                 ('include_private', bool),
                                  ])
 
 
@@ -86,7 +87,8 @@ def generate_stub_for_module(module: str, output_dir: str, quiet: bool = False,
                              pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
                              no_import: bool = False,
                              search_path: List[str] = [],
-                             interpreter: str = sys.executable) -> None:
+                             interpreter: str = sys.executable,
+                             include_private: bool = False) -> None:
     target = module.replace('.', '/')
     try:
         result = find_module_path_and_all(module=module,
@@ -118,7 +120,7 @@ def generate_stub_for_module(module: str, output_dir: str, quiet: bool = False,
         target = os.path.join(output_dir, target)
         generate_stub(module_path, output_dir, module_all,
                       target=target, add_header=add_header, module=module,
-                      pyversion=pyversion)
+                      pyversion=pyversion, include_private=include_private)
     if not quiet:
         print('Created %s' % target)
 
@@ -185,7 +187,8 @@ def load_python_module_info(module: str, interpreter: str) -> Tuple[str, Optiona
 
 def generate_stub(path: str, output_dir: str, _all_: Optional[List[str]] = None,
                   target: str = None, add_header: bool = False, module: str = None,
-                  pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION
+                  pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
+                  include_private: bool = False
                   ) -> None:
     with open(path, 'rb') as f:
         source = f.read()
@@ -199,7 +202,7 @@ def generate_stub(path: str, output_dir: str, _all_: Optional[List[str]] = None,
             sys.stderr.write('%s\n' % m)
         sys.exit(1)
 
-    gen = StubGenerator(_all_, pyversion=pyversion)
+    gen = StubGenerator(_all_, pyversion=pyversion, include_private=include_private)
     ast.accept(gen)
     if not target:
         target = os.path.join(output_dir, os.path.basename(path))
@@ -223,7 +226,8 @@ NOT_IN_ALL = 'NOT_IN_ALL'
 
 
 class StubGenerator(mypy.traverser.TraverserVisitor):
-    def __init__(self, _all_: Optional[List[str]], pyversion: Tuple[int, int]) -> None:
+    def __init__(self, _all_: Optional[List[str]], pyversion: Tuple[int, int],
+                 include_private: bool = False) -> None:
         self._all_ = _all_
         self._output = []  # type: List[str]
         self._import_lines = []  # type: List[str]
@@ -235,6 +239,7 @@ class StubGenerator(mypy.traverser.TraverserVisitor):
         self._classes = set()  # type: Set[str]
         self._base_classes = []  # type: List[str]
         self._pyversion = pyversion
+        self._include_private = include_private
 
     def visit_mypy_file(self, o: MypyFile) -> None:
         self._classes = find_classes(o)
@@ -515,6 +520,8 @@ class StubGenerator(mypy.traverser.TraverserVisitor):
         return False
 
     def is_private_name(self, name: str) -> bool:
+        if self._include_private:
+            return False
         return name.startswith('_') and (not name.endswith('__')
                                          or name in ('__all__',
                                                      '__author__',
@@ -610,7 +617,7 @@ def walk_packages(packages: List[str]) -> Iterator[str]:
 
 
 def main() -> None:
-    options = parse_options()
+    options = parse_options(sys.argv[1:])
     if not os.path.isdir('out'):
         raise SystemExit('Directory "out" does not exist')
     if options.recursive and options.no_import:
@@ -636,7 +643,8 @@ def main() -> None:
                                      pyversion=options.pyversion,
                                      no_import=options.no_import,
                                      search_path=options.search_path,
-                                     interpreter=options.interpreter)
+                                     interpreter=options.interpreter,
+                                     include_private=options.include_private)
         except Exception as e:
             if not options.ignore_errors:
                 raise e
@@ -644,8 +652,7 @@ def main() -> None:
                 print("Stub generation failed for", module, file=sys.stderr)
 
 
-def parse_options() -> Options:
-    args = sys.argv[1:]
+def parse_options(args: List[str]) -> Options:
     pyversion = defaults.PYTHON3_VERSION
     no_import = False
     recursive = False
@@ -653,6 +660,7 @@ def parse_options() -> Options:
     doc_dir = ''
     search_path = []  # type: List[str]
     interpreter = ''
+    include_private = False
     while args and args[0].startswith('-'):
         if args[0] == '--doc-dir':
             doc_dir = args[1]
@@ -673,6 +681,8 @@ def parse_options() -> Options:
             pyversion = defaults.PYTHON2_VERSION
         elif args[0] == '--no-import':
             no_import = True
+        elif args[0] == '--include-private':
+            include_private = True
         elif args[0] in ('-h', '--help'):
             usage()
         else:
@@ -689,7 +699,8 @@ def parse_options() -> Options:
                    interpreter=interpreter,
                    modules=args,
                    ignore_errors=ignore_errors,
-                   recursive=recursive)
+                   recursive=recursive,
+                   include_private=include_private)
 
 
 def default_python2_interpreter() -> str:
@@ -721,6 +732,9 @@ def usage() -> None:
           --no-import     don't import the modules, just parse and analyze them
                           (doesn't work with C extension modules and doesn't
                           respect __all__)
+          --include-private
+                          generate stubs for objects and members considered private
+                          (single leading undescore and no trailing underscores)
           --doc-dir PATH  use .rst documentation in PATH (this may result in
                           better stubs in some cases; consider setting this to
                           DIR/Python-X.Y.Z/Doc/library)
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
index 8ca6421..589e9b8 100644
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -69,11 +69,6 @@ def is_subtype(left: Type, right: Type,
         elif is_subtype_of_item:
             return True
         # otherwise, fall through
-    # Treat builtins.type the same as Type[Any]
-    elif is_named_instance(left, 'builtins.type'):
-            return is_subtype(TypeType(AnyType()), right)
-    elif is_named_instance(right, 'builtins.type'):
-            return is_subtype(left, TypeType(AnyType()))
     return left.accept(SubtypeVisitor(right, type_parameter_checker,
                                       ignore_pos_arg_names=ignore_pos_arg_names))
 
@@ -158,16 +153,18 @@ class SubtypeVisitor(TypeVisitor[bool]):
             item = right.item
             if isinstance(item, TupleType):
                 item = item.fallback
-            if isinstance(item, Instance):
-                return is_subtype(left, item.type.metaclass_type)
-            elif isinstance(item, AnyType):
-                # Special case: all metaclasses are subtypes of Type[Any]
-                mro = left.type.mro or []
-                return any(base.fullname() == 'builtins.type' for base in mro)
-            else:
-                return False
-        else:
-            return False
+            if is_named_instance(left, 'builtins.type'):
+                return is_subtype(TypeType(AnyType()), right)
+            if left.type.is_metaclass():
+                if isinstance(item, AnyType):
+                    return True
+                if isinstance(item, Instance):
+                    # Special-case enum since we don't have better way of expressing it
+                    if (is_named_instance(left, 'enum.EnumMeta')
+                            and is_named_instance(item, 'enum.Enum')):
+                        return True
+                    return is_named_instance(item, 'builtins.object')
+        return False
 
     def visit_type_var(self, left: TypeVarType) -> bool:
         right = self.right
@@ -231,9 +228,20 @@ class SubtypeVisitor(TypeVisitor[bool]):
         elif isinstance(right, TypedDictType):
             if not left.names_are_wider_than(right):
                 return False
-            for (_, l, r) in left.zip(right):
+            for name, l, r in left.zip(right):
                 if not is_equivalent(l, r, self.check_type_parameter):
                     return False
+                # Non-required key is not compatible with a required key since
+                # indexing may fail unexpectedly if a required key is missing.
+                # Required key is not compatible with a non-required key since
+                # the prior doesn't support 'del' but the latter should support
+                # it.
+                #
+                # NOTE: 'del' support is currently not implemented (#3550). We
+                #       don't want to have to change subtyping after 'del' support
+                #       lands so here we are anticipating that change.
+                if (name in left.required_keys) != (name in right.required_keys):
+                    return False
             # (NOTE: Fallbacks don't matter.)
             return True
         else:
@@ -263,8 +271,8 @@ class SubtypeVisitor(TypeVisitor[bool]):
         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)
+            # This is unsound, we don't check all the __init__ signatures.
+            return left.is_type_obj() and is_subtype(left.items()[0], right)
         else:
             return False
 
@@ -284,11 +292,14 @@ class SubtypeVisitor(TypeVisitor[bool]):
             # This is unsound, we don't check the __init__ signature.
             return is_subtype(left.item, right.ret_type)
         if isinstance(right, Instance):
-            if right.type.fullname() == 'builtins.object':
-                # treat builtins.object the same as Any.
+            if right.type.fullname() in ['builtins.object', 'builtins.type']:
                 return True
             item = left.item
-            return isinstance(item, Instance) and is_subtype(item, right.type.metaclass_type)
+            if isinstance(item, TypeVarType):
+                item = item.upper_bound
+            if isinstance(item, Instance):
+                metaclass = item.type.metaclass_type
+                return metaclass is not None and is_subtype(metaclass, right)
         return False
 
 
@@ -538,7 +549,7 @@ def restrict_subtype_away(t: Type, s: Type) -> Type:
     if isinstance(t, UnionType):
         # Since runtime type checks will ignore type arguments, erase the types.
         erased_s = erase_type(s)
-        new_items = [item for item in t.items
+        new_items = [item for item in t.relevant_items()
                      if (not is_proper_subtype(erase_type(item), erased_s)
                          or isinstance(item, AnyType))]
         return UnionType.make_union(new_items)
diff --git a/mypy/traverser.py b/mypy/traverser.py
index d748b02..495bafd 100644
--- a/mypy/traverser.py
+++ b/mypy/traverser.py
@@ -122,8 +122,9 @@ class TraverserVisitor(NodeVisitor[None]):
     def visit_try_stmt(self, o: TryStmt) -> None:
         o.body.accept(self)
         for i in range(len(o.types)):
-            if o.types[i]:
-                o.types[i].accept(self)
+            tp = o.types[i]
+            if tp is not None:
+                tp.accept(self)
             o.handlers[i].accept(self)
         if o.else_body is not None:
             o.else_body.accept(self)
@@ -133,8 +134,9 @@ class TraverserVisitor(NodeVisitor[None]):
     def visit_with_stmt(self, o: WithStmt) -> None:
         for i in range(len(o.expr)):
             o.expr[i].accept(self)
-            if o.target[i] is not None:
-                o.target[i].accept(self)
+            targ = o.target[i]
+            if targ is not None:
+                targ.accept(self)
         o.body.accept(self)
 
     def visit_member_expr(self, o: MemberExpr) -> None:
diff --git a/mypy/treetransform.py b/mypy/treetransform.py
index 170be48..c7debd8 100644
--- a/mypy/treetransform.py
+++ b/mypy/treetransform.py
@@ -477,7 +477,8 @@ class TransformVisitor(NodeVisitor[Node]):
                            self.type(node.upper_bound), variance=node.variance)
 
     def visit_type_alias_expr(self, node: TypeAliasExpr) -> TypeAliasExpr:
-        return TypeAliasExpr(node.type)
+        return TypeAliasExpr(node.type, node.tvars,
+                             fallback=node.fallback, in_runtime=node.in_runtime)
 
     def visit_newtype_expr(self, node: NewTypeExpr) -> NewTypeExpr:
         res = NewTypeExpr(node.name, node.old_type, line=node.line)
diff --git a/mypy/tvar_scope.py b/mypy/tvar_scope.py
index 3cdb67b..49f8359 100644
--- a/mypy/tvar_scope.py
+++ b/mypy/tvar_scope.py
@@ -30,7 +30,7 @@ class TypeVarScope:
 
     def get_function_scope(self) -> Optional['TypeVarScope']:
         """Get the nearest parent that's a function scope, not a class scope"""
-        it = self
+        it = self  # type: Optional[TypeVarScope]
         while it is not None and it.is_class_scope:
             it = it.parent
         return it
@@ -68,6 +68,7 @@ class TypeVarScope:
 
     def get_binding(self, item: Union[str, SymbolTableNode]) -> Optional[TypeVarDef]:
         fullname = item.fullname if isinstance(item, SymbolTableNode) else item
+        assert fullname is not None
         if fullname in self.scope:
             return self.scope[fullname]
         elif self.parent is not None:
diff --git a/mypy/typeanal.py b/mypy/typeanal.py
index 2a506b7..fe95a5f 100644
--- a/mypy/typeanal.py
+++ b/mypy/typeanal.py
@@ -6,6 +6,8 @@ from itertools import chain
 
 from contextlib import contextmanager
 
+from mypy.messages import MessageBuilder
+from mypy.options import Options
 from mypy.types import (
     Type, UnboundType, TypeVarType, TupleType, TypedDictType, UnionType, Instance,
     AnyType, CallableType, NoneTyp, DeletedType, TypeList, TypeVarDef, TypeVisitor,
@@ -15,17 +17,16 @@ from mypy.types import (
 )
 
 from mypy.nodes import (
-    TVAR, TYPE_ALIAS, UNBOUND_IMPORTED,
-    TypeInfo, Context, SymbolTableNode, Var, Expression,
-    IndexExpr, RefExpr, nongen_builtins, check_arg_names, check_arg_kinds,
-    ARG_POS, ARG_NAMED, ARG_OPT, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2, TypeVarExpr
+    TVAR, TYPE_ALIAS, UNBOUND_IMPORTED, TypeInfo, Context, SymbolTableNode, Var, Expression,
+    IndexExpr, RefExpr, nongen_builtins, check_arg_names, check_arg_kinds, ARG_POS, ARG_NAMED,
+    ARG_OPT, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2, TypeVarExpr
 )
 from mypy.tvar_scope import TypeVarScope
 from mypy.sametypes import is_same_type
 from mypy.exprtotype import expr_to_unanalyzed_type, TypeTranslationError
 from mypy.subtypes import is_subtype
-from mypy import nodes
-from mypy import experiments
+from mypy.plugin import Plugin, AnalyzerPluginInterface, AnalyzeTypeContext
+from mypy import nodes, messages
 
 
 T = TypeVar('T')
@@ -54,6 +55,9 @@ def analyze_type_alias(node: Expression,
                        lookup_fqn_func: Callable[[str], SymbolTableNode],
                        tvar_scope: TypeVarScope,
                        fail_func: Callable[[str, Context], None],
+                       plugin: Plugin,
+                       options: Options,
+                       is_typeshed_stub: bool,
                        allow_unnormalized: bool = False) -> Optional[Type]:
     """Return type if node is valid as a type alias rvalue.
 
@@ -96,8 +100,8 @@ def analyze_type_alias(node: Expression,
     except TypeTranslationError:
         fail_func('Invalid type alias', node)
         return None
-    analyzer = TypeAnalyser(lookup_func, lookup_fqn_func, tvar_scope, fail_func, aliasing=True,
-                            allow_unnormalized=allow_unnormalized)
+    analyzer = TypeAnalyser(lookup_func, lookup_fqn_func, tvar_scope, fail_func, plugin, options,
+                            is_typeshed_stub, aliasing=True, allow_unnormalized=allow_unnormalized)
     return type.accept(analyzer)
 
 
@@ -109,7 +113,7 @@ def no_subscript_builtin_alias(name: str, propose_alt: bool = True) -> str:
     return msg
 
 
-class TypeAnalyser(SyntheticTypeVisitor[Type]):
+class TypeAnalyser(SyntheticTypeVisitor[Type], AnalyzerPluginInterface):
     """Semantic analyzer for types (semantic analysis pass 2).
 
     Converts unbound types into bound types.
@@ -119,19 +123,25 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                  lookup_func: Callable[[str, Context], SymbolTableNode],
                  lookup_fqn_func: Callable[[str], SymbolTableNode],
                  tvar_scope: TypeVarScope,
-                 fail_func: Callable[[str, Context], None], *,
+                 fail_func: Callable[[str, Context], None],
+                 plugin: Plugin,
+                 options: Options,
+                 is_typeshed_stub: bool, *,
                  aliasing: bool = False,
                  allow_tuple_literal: bool = False,
                  allow_unnormalized: bool = False) -> None:
         self.lookup = lookup_func
         self.lookup_fqn_func = lookup_fqn_func
-        self.fail = fail_func
+        self.fail_func = fail_func
         self.tvar_scope = tvar_scope
         self.aliasing = aliasing
         self.allow_tuple_literal = allow_tuple_literal
         # Positive if we are analyzing arguments of another (outer) type
         self.nesting_level = 0
         self.allow_unnormalized = allow_unnormalized
+        self.plugin = plugin
+        self.options = options
+        self.is_typeshed_stub = is_typeshed_stub
 
     def visit_unbound_type(self, t: UnboundType) -> Type:
         if t.optional:
@@ -147,6 +157,9 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                     self.fail('Internal error (node is None, kind={})'.format(sym.kind), t)
                 return AnyType()
             fullname = sym.node.fullname()
+            hook = self.plugin.get_type_analyze_hook(fullname)
+            if hook:
+                return hook(AnalyzeTypeContext(t, t, self))
             if (fullname in nongen_builtins and t.args and
                     not sym.normalized and not self.allow_unnormalized):
                 self.fail(no_subscript_builtin_alias(fullname), t)
@@ -159,21 +172,23 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
             elif fullname == 'builtins.None':
                 return NoneTyp()
             elif fullname == 'typing.Any' or fullname == 'builtins.Any':
-                return AnyType()
+                return AnyType(explicit=True)
             elif fullname == 'typing.Tuple':
                 if len(t.args) == 0 and not t.empty_tuple_index:
                     # Bare 'Tuple' is same as 'tuple'
-                    return self.builtin_type('builtins.tuple')
+                    if 'generics' in self.options.disallow_any and not self.is_typeshed_stub:
+                        self.fail(messages.BARE_GENERIC, t)
+                    typ = self.named_type('builtins.tuple', line=t.line, column=t.column)
+                    typ.from_generic_builtin = True
+                    return typ
                 if len(t.args) == 2 and isinstance(t.args[1], EllipsisType):
                     # Tuple[T, ...] (uniform, variable-length tuple)
-                    instance = self.builtin_type('builtins.tuple', [self.anal_type(t.args[0])])
+                    instance = self.named_type('builtins.tuple', [self.anal_type(t.args[0])])
                     instance.line = t.line
                     return instance
                 return self.tuple_type(self.anal_array(t.args))
             elif fullname == 'typing.Union':
                 items = self.anal_array(t.args)
-                if not experiments.STRICT_OPTIONAL:
-                    items = [item for item in items if not isinstance(item, NoneTyp)]
                 return UnionType.make_union(items)
             elif fullname == 'typing.Optional':
                 if len(t.args) != 1:
@@ -185,11 +200,12 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                 return self.analyze_callable_type(t)
             elif fullname == 'typing.Type':
                 if len(t.args) == 0:
-                    return TypeType(AnyType(), line=t.line)
+                    any_type = AnyType(from_omitted_generics=True, line=t.line, column=t.column)
+                    return TypeType(any_type, line=t.line, column=t.column)
                 if len(t.args) != 1:
                     self.fail('Type[...] must have exactly one type argument', t)
                 item = self.anal_type(t.args[0])
-                return TypeType(item, line=t.line)
+                return TypeType.make_normalized(item, line=t.line)
             elif fullname == 'typing.ClassVar':
                 if self.nesting_level > 0:
                     self.fail('Invalid type: ClassVar nested inside other type', t)
@@ -207,22 +223,27 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                 return UninhabitedType(is_noreturn=True)
             elif sym.kind == TYPE_ALIAS:
                 override = sym.type_override
+                all_vars = sym.alias_tvars
                 assert override is not None
                 an_args = self.anal_array(t.args)
-                all_vars = self.get_type_var_names(override)
-                exp_len = len(all_vars)
+                if all_vars is not None:
+                    exp_len = len(all_vars)
+                else:
+                    exp_len = 0
                 act_len = len(an_args)
                 if exp_len > 0 and act_len == 0:
                     # Interpret bare Alias same as normal generic, i.e., Alias[Any, Any, ...]
-                    return self.replace_alias_tvars(override, all_vars, [AnyType()] * exp_len,
-                                                    t.line, t.column)
+                    assert all_vars is not None
+                    return set_any_tvars(override, all_vars, t.line, t.column)
                 if exp_len == 0 and act_len == 0:
                     return override
                 if act_len != exp_len:
                     self.fail('Bad number of arguments for type alias, expected: %s, given: %s'
                               % (exp_len, act_len), t)
-                    return t
-                return self.replace_alias_tvars(override, all_vars, an_args, t.line, t.column)
+                    return set_any_tvars(override, all_vars or [],
+                                         t.line, t.column, implicit=False)
+                assert all_vars is not None
+                return replace_alias_tvars(override, all_vars, an_args, t.line, t.column)
             elif not isinstance(sym.node, TypeInfo):
                 name = sym.fullname
                 if name is None:
@@ -232,7 +253,7 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                     # context. This is slightly problematic as it allows using the type 'Any'
                     # as a base class -- however, this will fail soon at runtime so the problem
                     # is pretty minor.
-                    return AnyType()
+                    return AnyType(from_unimported_type=True)
                 # Allow unbound type variables when defining an alias
                 if not (self.aliasing and sym.kind == TVAR and
                         self.tvar_scope.get_binding(sym) is None):
@@ -250,6 +271,7 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                 # valid count at this point. Thus we may construct an
                 # Instance with an invalid number of type arguments.
                 instance = Instance(info, self.anal_array(t.args), t.line, t.column)
+                instance.from_generic_builtin = sym.normalized
                 tup = info.tuple_type
                 if tup is not None:
                     # The class has a Tuple[...] base class so it will be
@@ -273,39 +295,6 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
         else:
             return AnyType()
 
-    def get_type_var_names(self, tp: Type) -> List[str]:
-        """Get all type variable names that are present in a generic type alias
-        in order of textual appearance (recursively, if needed).
-        """
-        return [name for name, _
-                in tp.accept(TypeVariableQuery(self.lookup, self.tvar_scope,
-                                               include_callables=True, include_bound_tvars=True))]
-
-    def get_tvar_name(self, t: Type) -> Optional[str]:
-        if not isinstance(t, UnboundType):
-            return None
-        sym = self.lookup(t.name, t)
-        if sym is not None and sym.kind == TVAR:
-            return t.name
-        return None
-
-    def replace_alias_tvars(self, tp: Type, vars: List[str], subs: List[Type],
-                            newline: int, newcolumn: int) -> Type:
-        """Replace type variables in a generic type alias tp with substitutions subs
-        resetting context. Length of subs should be already checked.
-        """
-        typ_args = get_typ_args(tp)
-        new_args = typ_args[:]
-        for i, arg in enumerate(typ_args):
-            tvar = self.get_tvar_name(arg)
-            if tvar and tvar in vars:
-                # Perform actual substitution...
-                new_args[i] = subs[vars.index(tvar)]
-            else:
-                # ...recursively, if needed.
-                new_args[i] = self.replace_alias_tvars(arg, vars, subs, newline, newcolumn)
-        return set_typ_args(tp, new_args, newline, newcolumn)
-
     def visit_any(self, t: AnyType) -> Type:
         return t
 
@@ -341,7 +330,7 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                 variables = self.bind_function_type_variables(t, t)
             ret = t.copy_modified(arg_types=self.anal_array(t.arg_types, nested=nested),
                                   ret_type=self.anal_type(t.ret_type, nested=nested),
-                                  fallback=t.fallback or self.builtin_type('builtins.function'),
+                                  fallback=t.fallback or self.named_type('builtins.function'),
                                   variables=self.anal_var_defs(variables))
         return ret
 
@@ -356,11 +345,11 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
             self.fail('At most one star type allowed in a tuple', t)
             if t.implicit:
                 return TupleType([AnyType() for _ in t.items],
-                                 self.builtin_type('builtins.tuple'),
+                                 self.named_type('builtins.tuple'),
                                  t.line)
             else:
                 return AnyType()
-        fallback = t.fallback if t.fallback else self.builtin_type('builtins.tuple', [AnyType()])
+        fallback = t.fallback if t.fallback else self.named_type('builtins.tuple', [AnyType()])
         return TupleType(self.anal_array(t.items), fallback, t.line)
 
     def visit_typeddict_type(self, t: TypedDictType) -> Type:
@@ -368,7 +357,7 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
             (item_name, self.anal_type(item_type))
             for (item_name, item_type) in t.items.items()
         ])
-        return TypedDictType(items, t.fallback)
+        return TypedDictType(items, set(t.required_keys), t.fallback)
 
     def visit_star_type(self, t: StarType) -> Type:
         return StarType(self.anal_type(t.type), t.line)
@@ -384,53 +373,27 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
         return AnyType()
 
     def visit_type_type(self, t: TypeType) -> Type:
-        return TypeType(self.anal_type(t.item), line=t.line)
+        return TypeType.make_normalized(self.anal_type(t.item), line=t.line)
 
     def analyze_callable_type(self, t: UnboundType) -> Type:
-        fallback = self.builtin_type('builtins.function')
+        fallback = self.named_type('builtins.function')
         if len(t.args) == 0:
             # Callable (bare). Treat as Callable[..., Any].
-            ret = CallableType([AnyType(), AnyType()],
+            any_type = AnyType(from_omitted_generics=True, line=t.line, column=t.column)
+            ret = CallableType([any_type, any_type],
                                [nodes.ARG_STAR, nodes.ARG_STAR2],
                                [None, None],
-                               ret_type=AnyType(),
+                               ret_type=any_type,
                                fallback=fallback,
                                is_ellipsis_args=True)
         elif len(t.args) == 2:
             ret_type = t.args[1]
             if isinstance(t.args[0], TypeList):
                 # Callable[[ARG, ...], RET] (ordinary callable type)
-                args = []   # type: List[Type]
-                names = []  # type: List[str]
-                kinds = []  # type: List[int]
-                for arg in t.args[0].items:
-                    if isinstance(arg, CallableArgument):
-                        args.append(arg.typ)
-                        names.append(arg.name)
-                        if arg.constructor is None:
-                            return AnyType()
-                        found = self.lookup(arg.constructor, arg)
-                        if found is None:
-                            # Looking it up already put an error message in
-                            return AnyType()
-                        elif found.fullname not in ARG_KINDS_BY_CONSTRUCTOR:
-                            self.fail('Invalid argument constructor "{}"'.format(
-                                found.fullname), arg)
-                            return AnyType()
-                        else:
-                            kind = ARG_KINDS_BY_CONSTRUCTOR[found.fullname]
-                            kinds.append(kind)
-                            if arg.name is not None and kind in {ARG_STAR, ARG_STAR2}:
-                                self.fail("{} arguments should not have names".format(
-                                    arg.constructor), arg)
-                                return AnyType()
-                    else:
-                        args.append(arg)
-                        names.append(None)
-                        kinds.append(ARG_POS)
-
-                check_arg_names(names, [t] * len(args), self.fail, "Callable")
-                check_arg_kinds(kinds, [t] * len(args), self.fail)
+                analyzed_args = self.analyze_callable_args(t.args[0])
+                if analyzed_args is None:
+                    return AnyType()
+                args, kinds, names = analyzed_args
                 ret = CallableType(args,
                                    kinds,
                                    names,
@@ -453,6 +416,49 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
         assert isinstance(ret, CallableType)
         return ret.accept(self)
 
+    def analyze_callable_args(self, arglist: TypeList) -> Optional[Tuple[List[Type],
+                                                                         List[int],
+                                                                         List[Optional[str]]]]:
+        args = []   # type: List[Type]
+        kinds = []  # type: List[int]
+        names = []  # type: List[Optional[str]]
+        for arg in arglist.items:
+            if isinstance(arg, CallableArgument):
+                args.append(arg.typ)
+                names.append(arg.name)
+                if arg.constructor is None:
+                    return None
+                found = self.lookup(arg.constructor, arg)
+                if found is None:
+                    # Looking it up already put an error message in
+                    return None
+                elif found.fullname not in ARG_KINDS_BY_CONSTRUCTOR:
+                    self.fail('Invalid argument constructor "{}"'.format(
+                        found.fullname), arg)
+                    return None
+                else:
+                    assert found.fullname is not None
+                    kind = ARG_KINDS_BY_CONSTRUCTOR[found.fullname]
+                    kinds.append(kind)
+                    if arg.name is not None and kind in {ARG_STAR, ARG_STAR2}:
+                        self.fail("{} arguments should not have names".format(
+                            arg.constructor), arg)
+                        return None
+            else:
+                args.append(arg)
+                kinds.append(ARG_POS)
+                names.append(None)
+        # Note that arglist below is only used for error context.
+        check_arg_names(names, [arglist] * len(args), self.fail, "Callable")
+        check_arg_kinds(kinds, [arglist] * len(args), self.fail)
+        return args, kinds, names
+
+    def analyze_type(self, t: Type) -> Type:
+        return t.accept(self)
+
+    def fail(self, msg: str, ctx: Context) -> None:
+        self.fail_func(msg, ctx)
+
     @contextmanager
     def tvar_scope_frame(self) -> Iterator[None]:
         old_scope = self.tvar_scope
@@ -532,13 +538,17 @@ class TypeAnalyser(SyntheticTypeVisitor[Type]):
                                 vd.line))
         return a
 
-    def builtin_type(self, fully_qualified_name: str, args: List[Type] = None) -> Instance:
+    def named_type(self, fully_qualified_name: str,
+                   args: List[Type] = None,
+                   line: int = -1,
+                   column: int = -1) -> Instance:
         node = self.lookup_fqn_func(fully_qualified_name)
         assert isinstance(node.node, TypeInfo)
-        return Instance(node.node, args or [])
+        return Instance(node.node, args or [AnyType()] * len(node.node.defn.type_vars),
+                        line=line, column=column)
 
     def tuple_type(self, items: List[Type]) -> TupleType:
-        return TupleType(items, fallback=self.builtin_type('builtins.tuple', [AnyType()]))
+        return TupleType(items, fallback=self.named_type('builtins.tuple', [AnyType()]))
 
 
 class TypeAnalyserPass3(TypeVisitor[None]):
@@ -561,16 +571,29 @@ class TypeAnalyserPass3(TypeVisitor[None]):
     to types.
     """
 
-    def __init__(self, fail_func: Callable[[str, Context], None]) -> None:
+    def __init__(self,
+                 fail_func: Callable[[str, Context], None],
+                 options: Options,
+                 is_typeshed_stub: bool) -> None:
         self.fail = fail_func
+        self.options = options
+        self.is_typeshed_stub = is_typeshed_stub
 
     def visit_instance(self, t: Instance) -> None:
         info = t.type
         # Check type argument count.
         if len(t.args) != len(info.type_vars):
             if len(t.args) == 0:
+                from_builtins = t.type.fullname() in nongen_builtins and not t.from_generic_builtin
+                if ('generics' in self.options.disallow_any and
+                        not self.is_typeshed_stub and
+                        from_builtins):
+                    alternative = nongen_builtins[t.type.fullname()]
+                    self.fail(messages.IMPLICIT_GENERIC_ANY_BUILTIN.format(alternative), t)
                 # Insert implicit 'Any' type arguments.
-                t.args = [AnyType()] * len(info.type_vars)
+                any_type = AnyType(from_omitted_generics=not from_builtins, line=t.line,
+                                   column=t.line)
+                t.args = [any_type] * len(info.type_vars)
                 return
             # Invalid number of type parameters.
             n = len(info.type_vars)
@@ -610,6 +633,9 @@ class TypeAnalyserPass3(TypeVisitor[None]):
                                   arg, info.name(), tvar.upper_bound), t)
         for arg in t.args:
             arg.accept(self)
+        if info.is_newtype:
+            for base in info.bases:
+                base.accept(self)
 
     def check_type_var_values(self, type: TypeInfo, actuals: List[Type],
                               valids: List[Type], arg_number: int, context: Context) -> None:
@@ -676,6 +702,33 @@ class TypeAnalyserPass3(TypeVisitor[None]):
 TypeVarList = List[Tuple[str, TypeVarExpr]]
 
 
+def replace_alias_tvars(tp: Type, vars: List[str], subs: List[Type],
+                        newline: int, newcolumn: int) -> Type:
+    """Replace type variables in a generic type alias tp with substitutions subs
+    resetting context. Length of subs should be already checked.
+    """
+    typ_args = get_typ_args(tp)
+    new_args = typ_args[:]
+    for i, arg in enumerate(typ_args):
+        if isinstance(arg, (UnboundType, TypeVarType)):
+            tvar = arg.name  # type: Optional[str]
+        else:
+            tvar = None
+        if tvar and tvar in vars:
+            # Perform actual substitution...
+            new_args[i] = subs[vars.index(tvar)]
+        else:
+            # ...recursively, if needed.
+            new_args[i] = replace_alias_tvars(arg, vars, subs, newline, newcolumn)
+    return set_typ_args(tp, new_args, newline, newcolumn)
+
+
+def set_any_tvars(tp: Type, vars: List[str],
+                  newline: int, newcolumn: int, implicit: bool = True) -> Type:
+    any_type = AnyType(from_omitted_generics=implicit, line=newline, column=newcolumn)
+    return replace_alias_tvars(tp, vars, [any_type] * len(vars), newline, newcolumn)
+
+
 def remove_dups(tvars: Iterable[T]) -> List[T]:
     # Get unique elements in order of appearance
     all_tvars = set()  # type: Set[T]
@@ -731,6 +784,78 @@ class TypeVariableQuery(TypeQuery[TypeVarList]):
             return []
 
 
+def check_for_explicit_any(typ: Optional[Type],
+                           options: Options,
+                           is_typeshed_stub: bool,
+                           msg: MessageBuilder,
+                           context: Context) -> None:
+    if ('explicit' in options.disallow_any and
+            not is_typeshed_stub and
+            typ and
+            has_explicit_any(typ)):
+        msg.explicit_any(context)
+
+
+def has_explicit_any(t: Type) -> bool:
+    """
+    Whether this type is or type it contains is an Any coming from explicit type annotation
+    """
+    return t.accept(HasExplicitAny())
+
+
+class HasExplicitAny(TypeQuery[bool]):
+    def __init__(self) -> None:
+        super().__init__(any)
+
+    def visit_any(self, t: AnyType) -> bool:
+        return t.explicit
+
+    def visit_typeddict_type(self, t: TypedDictType) -> bool:
+        # typeddict is checked during TypedDict declaration, so don't typecheck it here.
+        return False
+
+
+def has_any_from_unimported_type(t: Type) -> bool:
+    """Return true if this type is Any because an import was not followed.
+
+    If type t is such Any type or has type arguments that contain such Any type
+    this function will return true.
+    """
+    return t.accept(HasAnyFromUnimportedType())
+
+
+class HasAnyFromUnimportedType(TypeQuery[bool]):
+    def __init__(self) -> None:
+        super().__init__(any)
+
+    def visit_any(self, t: AnyType) -> bool:
+        return t.from_unimported_type
+
+    def visit_typeddict_type(self, t: TypedDictType) -> bool:
+        # typeddict is checked during TypedDict declaration, so don't typecheck it here
+        return False
+
+
+def collect_any_types(t: Type) -> List[AnyType]:
+    """Return all inner `AnyType`s of type t"""
+    return t.accept(CollectAnyTypesQuery())
+
+
+class CollectAnyTypesQuery(TypeQuery[List[AnyType]]):
+    def __init__(self) -> None:
+        super().__init__(self.combine_lists_strategy)
+
+    def visit_any(self, t: AnyType) -> List[AnyType]:
+        return [t]
+
+    @classmethod
+    def combine_lists_strategy(cls, it: Iterable[List[AnyType]]) -> List[AnyType]:
+        result = []  # type: List[AnyType]
+        for l in it:
+            result.extend(l)
+        return result
+
+
 def make_optional_type(t: Type) -> Type:
     """Return the type corresponding to Optional[t].
 
@@ -738,12 +863,11 @@ def make_optional_type(t: Type) -> Type:
     is called during semantic analysis and simplification only works during
     type checking.
     """
-    if not experiments.STRICT_OPTIONAL:
-        return t
     if isinstance(t, NoneTyp):
         return t
-    if isinstance(t, UnionType):
+    elif isinstance(t, UnionType):
         items = [item for item in union_items(t)
                  if not isinstance(item, NoneTyp)]
         return UnionType(items + [NoneTyp()], t.line, t.column)
-    return UnionType([t, NoneTyp()], t.line, t.column)
+    else:
+        return UnionType([t, NoneTyp()], t.line, t.column)
diff --git a/mypy/typefixture.py b/mypy/typefixture.py
index 04714e9..87ddd06 100644
--- a/mypy/typefixture.py
+++ b/mypy/typefixture.py
@@ -145,12 +145,12 @@ 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)
+        self.type_a = TypeType.make_normalized(self.a)
+        self.type_b = TypeType.make_normalized(self.b)
+        self.type_c = TypeType.make_normalized(self.c)
+        self.type_d = TypeType.make_normalized(self.d)
+        self.type_t = TypeType.make_normalized(self.t)
+        self.type_any = TypeType.make_normalized(self.anyt)
 
     # Helper methods
 
diff --git a/mypy/types.py b/mypy/types.py
index 8de44cc..051c320 100644
--- a/mypy/types.py
+++ b/mypy/types.py
@@ -1,22 +1,21 @@
 """Classes for representing mypy types."""
 
-from abc import abstractmethod
 import copy
+from abc import abstractmethod
 from collections import OrderedDict
 from typing import (
-    Any, TypeVar, Dict, List, Tuple, cast, Generic, Set, Sequence, Optional, Union, Iterable,
-    NamedTuple, Callable,
+    Any, TypeVar, Dict, List, Tuple, cast, Generic, Set, Optional, Union, Iterable, NamedTuple,
+    Callable,
 )
 
 import mypy.nodes
+from mypy import experiments
 from mypy.nodes import (
-    INVARIANT, SymbolNode,
-    ARG_POS, ARG_OPT, ARG_STAR, ARG_STAR2, ARG_NAMED, ARG_NAMED_OPT,
+    INVARIANT, SymbolNode, ARG_POS, ARG_OPT, ARG_STAR, ARG_STAR2, ARG_NAMED, ARG_NAMED_OPT,
 )
 from mypy.sharedparse import argument_elide_name
 from mypy.util import IdMapper
 
-
 T = TypeVar('T')
 
 JsonDict = Dict[str, Any]
@@ -35,21 +34,9 @@ def deserialize_type(data: Union[JsonDict, str]) -> 'Type':
 class Type(mypy.nodes.Context):
     """Abstract base class for all types."""
 
-    line = 0
-    column = 0
     can_be_true = True
     can_be_false = True
 
-    def __init__(self, line: int = -1, column: int = -1) -> None:
-        self.line = line
-        self.column = column
-
-    def get_line(self) -> int:
-        return self.line
-
-    def get_column(self) -> int:
-        return self.column
-
     def accept(self, visitor: 'TypeVisitor[T]') -> T:
         raise RuntimeError('Not implemented')
 
@@ -123,12 +110,11 @@ class TypeVarDef(mypy.nodes.Context):
     values = None  # type: List[Type]  # Value restriction, empty list if no restriction
     upper_bound = None  # type: Type
     variance = INVARIANT  # type: int
-    line = 0
-    column = 0
 
     def __init__(self, name: str, id: Union[TypeVarId, int], values: List[Type],
                  upper_bound: Type, variance: int = INVARIANT, line: int = -1,
                  column: int = -1) -> None:
+        super().__init__(line, column)
         assert values is not None, "No restrictions must be represented by empty list"
         self.name = name
         if isinstance(id, int):
@@ -137,8 +123,6 @@ class TypeVarDef(mypy.nodes.Context):
         self.values = values
         self.upper_bound = upper_bound
         self.variance = variance
-        self.line = line
-        self.column = column
 
     @staticmethod
     def new_unification_variable(old: 'TypeVarDef') -> 'TypeVarDef':
@@ -146,12 +130,6 @@ class TypeVarDef(mypy.nodes.Context):
         return TypeVarDef(old.name, new_id, old.values,
                           old.upper_bound, old.variance, old.line, old.column)
 
-    def get_line(self) -> int:
-        return self.line
-
-    def get_column(self) -> int:
-        return self.column
-
     def __repr__(self) -> str:
         if self.values:
             return '{} in {}'.format(self.name, tuple(self.values))
@@ -269,16 +247,61 @@ class TypeList(Type):
         assert False, "Sythetic types don't serialize"
 
 
+_dummy = object()  # type: Any
+
+
 class AnyType(Type):
     """The type 'Any'."""
 
-    def __init__(self, implicit: bool = False, line: int = -1, column: int = -1) -> None:
+    def __init__(self,
+                 implicit: bool = False,
+                 from_unimported_type: bool = False,
+                 explicit: bool = False,
+                 from_omitted_generics: bool = False,
+                 special_form: bool = False,
+                 line: int = -1,
+                 column: int = -1) -> None:
         super().__init__(line, column)
+        # Was this Any type was inferred without a type annotation?
+        # Note that this is not always the opposite of explicit.
+        # For instance, if "Any" comes from an unimported type,
+        # both explicit and implicit will be False
         self.implicit = implicit
+        # Does this come from an unfollowed import? See --disallow-any=unimported option
+        self.from_unimported_type = from_unimported_type
+        # Does this Any come from an explicit type annotation?
+        self.explicit = explicit
+        # Does this type come from omitted generics?
+        self.from_omitted_generics = from_omitted_generics
+        # Is this a type that can't be represented in mypy's type system? For instance, type of
+        # call to NewType(...)). Even though these types aren't real Anys, we treat them as such.
+        self.special_form = special_form
 
     def accept(self, visitor: 'TypeVisitor[T]') -> T:
         return visitor.visit_any(self)
 
+    def copy_modified(self,
+                      implicit: bool = _dummy,
+                      from_unimported_type: bool = _dummy,
+                      explicit: bool = _dummy,
+                      from_omitted_generics: bool = _dummy,
+                      special_form: bool = _dummy,
+                      ) -> 'AnyType':
+        if implicit is _dummy:
+            implicit = self.implicit
+        if from_unimported_type is _dummy:
+            from_unimported_type = self.from_unimported_type
+        if explicit is _dummy:
+            explicit = self.explicit
+        if from_omitted_generics is _dummy:
+            from_omitted_generics = self.from_omitted_generics
+        if special_form is _dummy:
+            special_form = self.special_form
+        return AnyType(implicit=implicit, from_unimported_type=from_unimported_type,
+                       explicit=explicit, from_omitted_generics=from_omitted_generics,
+                       special_form=special_form,
+                       line=self.line, column=self.column)
+
     def serialize(self) -> JsonDict:
         return {'.class': 'AnyType'}
 
@@ -398,10 +421,11 @@ class Instance(Type):
     args = None  # type: List[Type]
     erased = False  # True if result of type variable substitution
     invalid = False  # True if recovered after incorrect number of type arguments error
+    from_generic_builtin = False  # True if created from a generic builtin (e.g. list() or set())
 
     def __init__(self, typ: mypy.nodes.TypeInfo, args: List[Type],
                  line: int = -1, column: int = -1, erased: bool = False) -> None:
-        assert(typ is None or typ.fullname() not in ["builtins.Any", "typing.Any"])
+        assert(typ is NOT_READY or typ.fullname() not in ["builtins.Any", "typing.Any"])
         self.type = typ
         self.args = args
         self.erased = erased
@@ -522,9 +546,6 @@ class FunctionLike(Type):
     fallback = None  # type: Instance
 
 
-_dummy = object()  # type: Any
-
-
 FormalArgument = NamedTuple('FormalArgument', [
     ('name', Optional[str]),
     ('pos', Optional[int]),
@@ -542,7 +563,7 @@ class CallableType(FunctionLike):
     is_var_arg = False              # Is it a varargs function?  derived from arg_kinds
     is_kw_arg = False
     ret_type = None  # type: Type   # Return value type
-    name = ''   # type: Optional[str] # Name (may be None; for error messages)
+    name = ''   # type: Optional[str]  # Name (may be None; for error messages and plugins)
     definition = None  # type: Optional[SymbolNode] # For error messages.  May be None.
     # Type variables for a generic function
     variables = None  # type: List[TypeVarDef]
@@ -914,12 +935,14 @@ class TypedDictType(Type):
     whose TypeInfo has a typeddict_type that is anonymous.
     """
 
-    items = None  # type: OrderedDict[str, Type]  # (item_name, item_type)
+    items = None  # type: OrderedDict[str, Type]  # item_name -> item_type
+    required_keys = None  # type: Set[str]
     fallback = None  # type: Instance
 
-    def __init__(self, items: 'OrderedDict[str, Type]', fallback: Instance,
-                 line: int = -1, column: int = -1) -> None:
+    def __init__(self, items: 'OrderedDict[str, Type]', required_keys: Set[str],
+                 fallback: Instance, line: int = -1, column: int = -1) -> None:
         self.items = items
+        self.required_keys = required_keys
         self.fallback = fallback
         self.can_be_true = len(self.items) > 0
         self.can_be_false = len(self.items) == 0
@@ -931,6 +954,7 @@ class TypedDictType(Type):
     def serialize(self) -> JsonDict:
         return {'.class': 'TypedDictType',
                 'items': [[n, t.serialize()] for (n, t) in self.items.items()],
+                'required_keys': sorted(self.required_keys),
                 'fallback': self.fallback.serialize(),
                 }
 
@@ -939,23 +963,30 @@ class TypedDictType(Type):
         assert data['.class'] == 'TypedDictType'
         return TypedDictType(OrderedDict([(n, deserialize_type(t))
                                           for (n, t) in data['items']]),
+                             set(data['required_keys']),
                              Instance.deserialize(data['fallback']))
 
+    def is_anonymous(self) -> bool:
+        return self.fallback.type.fullname() == 'typing.Mapping'
+
     def as_anonymous(self) -> 'TypedDictType':
-        if self.fallback.type.fullname() == 'typing.Mapping':
+        if self.is_anonymous():
             return self
         assert self.fallback.type.typeddict_type is not None
         return self.fallback.type.typeddict_type.as_anonymous()
 
     def copy_modified(self, *, fallback: Instance = None,
-                      item_types: List[Type] = None) -> 'TypedDictType':
+                      item_types: List[Type] = None,
+                      required_keys: Set[str] = None) -> 'TypedDictType':
         if fallback is None:
             fallback = self.fallback
         if item_types is None:
             items = self.items
         else:
             items = OrderedDict(zip(self.items, item_types))
-        return TypedDictType(items, fallback, self.line, self.column)
+        if required_keys is None:
+            required_keys = self.required_keys
+        return TypedDictType(items, required_keys, fallback, self.line, self.column)
 
     def create_anonymous_fallback(self, *, value_type: Type) -> Instance:
         anonymous = self.as_anonymous()
@@ -1090,7 +1121,14 @@ class UnionType(Type):
         """
         return all((isinstance(x, UnionType) and x.has_readable_member(name)) or
                    (isinstance(x, Instance) and x.type.has_readable_member(name))
-                   for x in self.items)
+                   for x in self.relevant_items())
+
+    def relevant_items(self) -> List[Type]:
+        """Removes NoneTypes from Unions when strict Optional checking is off."""
+        if experiments.STRICT_OPTIONAL:
+            return self.items
+        else:
+            return [i for i in self.items if not isinstance(i, NoneTyp)]
 
     def serialize(self) -> JsonDict:
         return {'.class': 'UnionType',
@@ -1183,13 +1221,26 @@ class TypeType(Type):
     # a generic class instance, a union, Any, a type variable...
     item = None  # type: Type
 
-    def __init__(self, item: Type, *, line: int = -1, column: int = -1) -> None:
+    def __init__(self, item: Union[Instance, AnyType, TypeVarType, TupleType, NoneTyp,
+                                   CallableType], *, line: int = -1, column: int = -1) -> None:
+        """To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of
+        type UnionType must be handled through make_normalized static method.
+        """
         super().__init__(line, column)
         if isinstance(item, CallableType) and item.is_type_obj():
             self.item = item.fallback
         else:
             self.item = item
 
+    @staticmethod
+    def make_normalized(item: Type, *, line: int = -1, column: int = -1) -> Type:
+        if isinstance(item, UnionType):
+            return UnionType.make_union(
+                [TypeType.make_normalized(union_item) for union_item in item.items],
+                line=line, column=column
+            )
+        return TypeType(item, line=line, column=column)  # type: ignore
+
     def accept(self, visitor: 'TypeVisitor[T]') -> T:
         return visitor.visit_type_type(self)
 
@@ -1197,9 +1248,9 @@ class TypeType(Type):
         return {'.class': 'TypeType', 'item': self.item.serialize()}
 
     @classmethod
-    def deserialize(cls, data: JsonDict) -> 'TypeType':
+    def deserialize(cls, data: JsonDict) -> Type:
         assert data['.class'] == 'TypeType'
-        return TypeType(deserialize_type(data['item']))
+        return TypeType.make_normalized(deserialize_type(data['item']))
 
 
 #
@@ -1351,6 +1402,7 @@ class TypeTranslator(TypeVisitor[Type]):
             for (item_name, item_type) in t.items.items()
         ])
         return TypedDictType(items,
+                             t.required_keys,
                              # TODO: This appears to be unsafe.
                              cast(Any, t.fallback.accept(self)),
                              t.line, t.column)
@@ -1376,7 +1428,7 @@ class TypeTranslator(TypeVisitor[Type]):
         return Overloaded(items=items)
 
     def visit_type_type(self, t: TypeType) -> Type:
-        return TypeType(t.item.accept(self), line=t.line, column=t.column)
+        return TypeType.make_normalized(t.item.accept(self), line=t.line, column=t.column)
 
 
 class TypeStrVisitor(SyntheticTypeVisitor[str]):
@@ -1495,13 +1547,22 @@ class TypeStrVisitor(SyntheticTypeVisitor[str]):
         return 'Tuple[{}]'.format(s)
 
     def visit_typeddict_type(self, t: TypedDictType) -> str:
-        s = self.keywords_str(t.items.items())
+        def item_str(name: str, typ: str) -> str:
+            if name in t.required_keys:
+                return '{!r}: {}'.format(name, typ)
+            else:
+                return '{!r}?: {}'.format(name, typ)
+
+        s = '{' + ', '.join(item_str(name, typ.accept(self))
+                            for name, typ in t.items.items()) + '}'
+        prefix = ''
+        suffix = ''
         if t.fallback and t.fallback.type:
-            if s == '':
-                return 'TypedDict(_fallback={})'.format(t.fallback.accept(self))
+            if t.fallback.type.fullname() != 'typing.Mapping':
+                prefix = repr(t.fallback.type.fullname()) + ', '
             else:
-                return 'TypedDict({}, _fallback={})'.format(s, t.fallback.accept(self))
-        return 'TypedDict({})'.format(s)
+                suffix = ', fallback={}'.format(t.fallback.accept(self))
+        return 'TypedDict({}{}{})'.format(prefix, s, suffix)
 
     def visit_star_type(self, t: StarType) -> str:
         s = t.type.accept(self)
@@ -1536,15 +1597,6 @@ class TypeStrVisitor(SyntheticTypeVisitor[str]):
                 res.append(str(t))
         return ', '.join(res)
 
-    def keywords_str(self, a: Iterable[Tuple[str, Type]]) -> str:
-        """Convert keywords to strings (pretty-print types)
-        and join the results with commas.
-        """
-        return ', '.join([
-            '{}={}'.format(name, t.accept(self))
-            for (name, t) in a
-        ])
-
 
 class TypeQuery(SyntheticTypeVisitor[T]):
     """Visitor for performing queries of types.
@@ -1692,6 +1744,10 @@ def true_or_false(t: Type) -> Type:
     """
     Unrestricted version of t with both True-ish and False-ish values
     """
+    if isinstance(t, UnionType):
+        new_items = [true_or_false(item) for item in t.items]
+        return UnionType.make_simplified_union(new_items, line=t.line, column=t.column)
+
     new_t = copy_type(t)
     new_t.can_be_true = type(new_t).can_be_true
     new_t.can_be_false = type(new_t).can_be_false
@@ -1796,8 +1852,10 @@ def union_items(typ: Type) -> List[Type]:
         return [typ]
 
 
+names = globals().copy()
+names.pop('NOT_READY', None)
 deserialize_map = {
     key: obj.deserialize  # type: ignore
-    for key, obj in globals().items()
+    for key, obj in names.items()
     if isinstance(obj, type) and issubclass(obj, Type) and obj is not Type
 }
diff --git a/mypy/version.py b/mypy/version.py
index cbe0b01..2dff1c6 100644
--- a/mypy/version.py
+++ b/mypy/version.py
@@ -1,7 +1,7 @@
 import os
 from mypy import git
 
-__version__ = '0.511'
+__version__ = '0.520'
 base_version = __version__
 
 mypy_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
diff --git a/mypy/waiter.py b/mypy/waiter.py
index 62a0555..e8ba99d 100644
--- a/mypy/waiter.py
+++ b/mypy/waiter.py
@@ -9,7 +9,7 @@ import os
 from multiprocessing import cpu_count
 import pipes
 import re
-from subprocess import Popen, STDOUT
+from subprocess import Popen, STDOUT, DEVNULL
 import sys
 import tempfile
 import time
@@ -25,16 +25,22 @@ class LazySubprocess:
     """Wrapper around a subprocess that runs a test task."""
 
     def __init__(self, name: str, args: List[str], *, cwd: str = None,
-                 env: Dict[str, str] = None) -> None:
+                 env: Dict[str, str] = None, passthrough: Optional[int] = None) -> None:
         self.name = name
         self.args = args
         self.cwd = cwd
         self.env = env
         self.start_time = None  # type: float
         self.end_time = None  # type: float
+        # None means no passthrough
+        # otherwise, it represents verbosity level
+        self.passthrough = passthrough
 
     def start(self) -> None:
-        self.outfile = tempfile.TemporaryFile()
+        if self.passthrough is None or self.passthrough < 0:
+            self.outfile = tempfile.TemporaryFile()
+        else:
+            self.outfile = None
         self.start_time = time.perf_counter()
         self.process = Popen(self.args, cwd=self.cwd, env=self.env,
                              stdout=self.outfile, stderr=STDOUT)
@@ -47,6 +53,8 @@ class LazySubprocess:
         return self.process.returncode
 
     def read_output(self) -> str:
+        if not self.outfile:
+            return ''
         file = self.outfile
         file.seek(0)
         # Assume it's ascii to avoid unicode headaches (and portability issues).
@@ -339,7 +347,7 @@ class Waiter:
 
         if self.new_log:  # don't append empty log, it will corrupt the cache file
             # log only LOGSIZE most recent tests
-            test_log = (self.load_log_file() + [self.new_log])[:self.LOGSIZE]
+            test_log = (self.load_log_file() + [self.new_log])[-self.LOGSIZE:]
             try:
                 with open(self.FULL_LOG_FILENAME, 'w') as fp:
                     json.dump(test_log, fp, sort_keys=True, indent=4)
diff --git a/scripts/stubgen b/scripts/stubgen
old mode 100755
new mode 100644
diff --git a/setup.cfg b/setup.cfg
index 8320c2f..c3b5f76 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -10,7 +10,6 @@ exclude =
 	.mypy_cache,
 	.cache,
 	docs/source/conf.py,
-	lib-typing/*,
 	misc/*,
 	pinfer/*,
 	scripts/*,
@@ -29,7 +28,7 @@ show_missing = true
 
 [metadata]
 requires-dist = 
-	typed-ast >= 1.0.3, < 1.1.0
+	typed-ast >= 1.0.4, < 1.1.0
 	typing >= 3.5.3; python_version < "3.5"
 
 [egg_info]
diff --git a/setup.py b/setup.py
index 78c6a63..77c3a3b 100644
--- a/setup.py
+++ b/setup.py
@@ -94,16 +94,13 @@ classifiers = [
 
 package_dir = {'mypy': 'mypy'}
 
-scripts = ['scripts/mypy', 'scripts/stubgen']
-if os.name == 'nt':
-    scripts.append('scripts/mypy.bat')
 
 # These requirements are used when installing by other means than bdist_wheel.
 # E.g. "pip3 install ." or
 # "pip3 install git+git://github.com/python/mypy.git"
 # (as suggested by README.md).
 install_requires = []
-install_requires.append('typed-ast >= 1.0.3, < 1.1.0')
+install_requires.append('typed-ast >= 1.0.4, < 1.1.0')
 if sys.version_info < (3, 5):
     install_requires.append('typing >= 3.5.3')
 
@@ -119,7 +116,8 @@ setup(name='mypy',
       package_dir=package_dir,
       py_modules=[],
       packages=['mypy'],
-      scripts=scripts,
+      entry_points={'console_scripts': ['mypy=mypy.__main__:console_entry',
+                                        'stubgen=mypy.stubgen:main']},
       data_files=data_files,
       classifiers=classifiers,
       cmdclass={'build_py': CustomPythonBuild},
diff --git a/typeshed/stdlib/2/Cookie.pyi b/typeshed/stdlib/2/Cookie.pyi
index 2df4eb0..a4e6344 100644
--- a/typeshed/stdlib/2/Cookie.pyi
+++ b/typeshed/stdlib/2/Cookie.pyi
@@ -1,7 +1,3 @@
-# Stubs for Cookie (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class CookieError(Exception): ...
diff --git a/typeshed/stdlib/2/SocketServer.pyi b/typeshed/stdlib/2/SocketServer.pyi
index 14a739b..8d03b8f 100644
--- a/typeshed/stdlib/2/SocketServer.pyi
+++ b/typeshed/stdlib/2/SocketServer.pyi
@@ -50,15 +50,16 @@ class UDPServer(BaseServer):
                  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: ...
+if sys.platform != 'win32':
+    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 UnixDatagramServer(BaseServer):
+        def __init__(self, server_address: Tuple[str, int],
+                     RequestHandlerClass: type,
+                     bind_and_activate: bool = ...) -> None: ...
 
 class ForkingMixIn: ...
 class ThreadingMixIn: ...
@@ -67,6 +68,9 @@ class ForkingTCPServer(ForkingMixIn, TCPServer): ...
 class ForkingUDPServer(ForkingMixIn, UDPServer): ...
 class ThreadingTCPServer(ThreadingMixIn, TCPServer): ...
 class ThreadingUDPServer(ThreadingMixIn, UDPServer): ...
+if sys.platform != 'win32':
+    class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ...
+    class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ...
 
 
 class BaseRequestHandler:
diff --git a/typeshed/stdlib/2/__builtin__.pyi b/typeshed/stdlib/2/__builtin__.pyi
index 541122b..a681ab6 100644
--- a/typeshed/stdlib/2/__builtin__.pyi
+++ b/typeshed/stdlib/2/__builtin__.pyi
@@ -88,11 +88,10 @@ class type(object):
 
 class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
     @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, x: SupportsInt) -> None: ...
+    def __init__(self, x: SupportsInt = ...) -> None: ...
     @overload
-    def __init__(self, x: Union[str, unicode, bytearray], base: int = 10) -> None: ...
+    def __init__(self, x: Union[str, unicode, bytearray], base: int = ...) -> None: ...
+
     def bit_length(self) -> int: ...
 
     def __add__(self, x: int) -> int: ...
@@ -140,14 +139,7 @@ class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
     def __nonzero__(self) -> bool: ...
 
 class float(SupportsFloat, SupportsInt, SupportsAbs[float]):
-    @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, x: SupportsFloat) -> None: ...
-    @overload
-    def __init__(self, x: unicode) -> None: ...
-    @overload
-    def __init__(self, x: bytearray) -> None: ...
+    def __init__(self, x: Union[SupportsFloat, str, unicode, bytearray] = ...) -> None: ...
     def as_integer_ratio(self) -> Tuple[int, int]: ...
     def hex(self) -> str: ...
     def is_integer(self) -> bool: ...
@@ -309,7 +301,7 @@ class unicode(basestring, Sequence[unicode]):
     def __hash__(self) -> int: ...
 
 class str(basestring, Sequence[str]):
-    def __init__(self, object: object='') -> None: ...
+    def __init__(self, object: object = ...) -> None: ...
     def capitalize(self) -> str: ...
     def center(self, width: int, fillchar: str = ...) -> str: ...
     def count(self, x: unicode, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ...
@@ -487,7 +479,7 @@ class slice(object):
     @overload
     def __init__(self, stop: Optional[int]) -> None: ...
     @overload
-    def __init__(self, start: Optional[int], stop: Optional[int], step: int = None) -> None: ...
+    def __init__(self, start: Optional[int], stop: Optional[int], step: Optional[int] = None) -> None: ...
     def indices(self, len: int) -> Tuple[int, int, int]: ...
 
 class tuple(Sequence[_T_co], Generic[_T_co]):
@@ -574,9 +566,11 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
     def popitem(self) -> Tuple[_KT, _VT]: ...
     def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ...
     @overload
-    def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    @overload
+    def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
     @overload
-    def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
+    def update(self, **kwargs: _VT) -> None: ...
     def iterkeys(self) -> Iterator[_KT]: ...
     def itervalues(self) -> Iterator[_VT]: ...
     def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ...
@@ -676,13 +670,13 @@ class xrange(Sized, Iterable[int], Reversible[int]):
     def __reversed__(self) -> Iterator[int]: ...
 
 class property(object):
-    def __init__(self, fget: Callable[[Any], Any] = None,
-                 fset: Callable[[Any, Any], None] = None,
-                 fdel: Callable[[Any], None] = None, doc: str = None) -> None: ...
+    def __init__(self, fget: Optional[Callable[[Any], Any]] = None,
+                 fset: Optional[Callable[[Any, Any], None]] = None,
+                 fdel: Optional[Callable[[Any], None]] = None, doc: Optional[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 __get__(self, obj: Any, type: Optional[type] = None) -> Any: ...
     def __set__(self, obj: Any, value: Any) -> None: ...
     def __delete__(self, obj: Any) -> None: ...
     def fget(self) -> Any: ...
@@ -716,7 +710,7 @@ def filter(function: Callable[[_T], Any],
 def filter(function: None,
            iterable: Iterable[Optional[_T]]) -> List[_T]: ...
 def format(o: object, format_spec: str = '') -> str: ...  # TODO unicode
-def getattr(o: Any, name: unicode, default: Any = None) -> Any: ...
+def getattr(o: Any, name: unicode, default: Optional[Any] = None) -> Any: ...
 def hasattr(o: Any, name: unicode) -> bool: ...
 def hash(o: object) -> int: ...
 def hex(i: int) -> str: ...  # TODO __index__
@@ -750,14 +744,14 @@ def next(i: Iterator[_T]) -> _T: ...
 def next(i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ...
 def oct(i: int) -> str: ...  # TODO __index__
 @overload
-def open(file: str, mode: str = 'r', buffering: int = ...) -> BinaryIO: ...
+def open(file: str, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ...
 @overload
-def open(file: unicode, mode: str = 'r', buffering: int = ...) -> BinaryIO: ...
+def open(file: unicode, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ...
 @overload
-def open(file: int, mode: str = 'r', buffering: int = ...) -> BinaryIO: ...
+def open(file: int, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ...
 def ord(c: unicode) -> int: ...
 # This is only available after from __future__ import print_function.
-def print(*values: Any, sep: unicode = u' ', end: unicode = u'\n',
+def print(*values: Any, sep: unicode = ..., end: unicode = ...,
            file: IO[Any] = ...) -> None: ...
 @overload
 def pow(x: int, y: int) -> Any: ...  # The return type can be int or float, depending on y.
@@ -768,7 +762,7 @@ def pow(x: float, y: float) -> float: ...
 @overload
 def pow(x: float, y: float, z: float) -> float: ...
 def quit(code: int = ...) -> None: ...
-def range(x: int, y: int = 0, step: int = 1) -> List[int]: ...
+def range(x: int, y: int = ..., step: int = ...) -> List[int]: ...
 def raw_input(prompt: Any = ...) -> str: ...
 
 @overload
@@ -939,14 +933,14 @@ class UnicodeWarning(Warning): ...
 class BytesWarning(Warning): ...
 class ResourceWarning(Warning): ...
 
-def eval(s: str, globals: Dict[str, Any] = ..., locals: Dict[str, Any] = ...) -> Any: ...
+def eval(s: Union[str, unicode], globals: Dict[str, Any] = ..., locals: Dict[str, Any] = ...) -> Any: ...
 def exec(object: str,
-         globals: Dict[str, Any] = None,
-         locals: Dict[str, Any] = None) -> Any: ...  # TODO code object as source
+         globals: Optional[Dict[str, Any]] = None,
+         locals: Optional[Dict[str, Any]] = None) -> Any: ...  # TODO code object as source
 
 def cmp(x: Any, y: Any) -> int: ...
 
-def execfile(filename: str, globals: Dict[str, Any] = None, locals: Dict[str, Any] = None) -> None: ...
+def execfile(filename: str, globals: Optional[Dict[str, Any]] = None, locals: Optional[Dict[str, Any]] = None) -> None: ...
 
 class file(BinaryIO):
     @overload
@@ -958,7 +952,7 @@ class file(BinaryIO):
     def __iter__(self) -> Iterator[str]: ...
     def read(self, n: int = ...) -> str: ...
     def __enter__(self) -> BinaryIO: ...
-    def __exit__(self, t: type = None, exc: BaseException = None, tb: Any = None) -> bool: ...
+    def __exit__(self, t: Optional[type] = None, exc: Optional[BaseException] = None, tb: Optional[Any] = None) -> bool: ...
     def flush(self) -> None: ...
     def fileno(self) -> int: ...
     def isatty(self) -> bool: ...
@@ -976,6 +970,6 @@ class file(BinaryIO):
     def truncate(self, pos: Optional[int] = ...) -> int: ...
 
 # Very old builtins
-def apply(func: Callable[..., _T], args: Sequence[Any] = None, kwds: Mapping[str, Any] = None) -> _T: ...
+def apply(func: Callable[..., _T], args: Optional[Sequence[Any]] = None, kwds: Optional[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/_ast.pyi b/typeshed/stdlib/2/_ast.pyi
index 02236a8..a0a7a00 100644
--- a/typeshed/stdlib/2/_ast.pyi
+++ b/typeshed/stdlib/2/_ast.pyi
@@ -5,7 +5,7 @@ __version__ = ...  # type: str
 
 PyCF_ONLY_AST = ...  # type: int
 
-identifier = str
+_identifier = str
 
 class AST:
     _attributes = ...  # type: typing.Tuple[str, ...]
@@ -33,13 +33,13 @@ class stmt(AST):
     col_offset = ...  # type: int
 
 class FunctionDef(stmt):
-    name = ...  # type: identifier
+    name = ...  # type: _identifier
     args = ...  # type: arguments
     body = ...  # type: typing.List[stmt]
     decorator_list = ...  # type: typing.List[expr]
 
 class ClassDef(stmt):
-    name = ...  # type: identifier
+    name = ...  # type: _identifier
     bases = ...  # type: typing.List[expr]
     body = ...  # type: typing.List[stmt]
     decorator_list = ...  # type: typing.List[expr]
@@ -107,7 +107,7 @@ class Import(stmt):
     names = ...  # type: typing.List[alias]
 
 class ImportFrom(stmt):
-    module = ...  # type: Optional[identifier]
+    module = ...  # type: Optional[_identifier]
     names = ...  # type: typing.List[alias]
     level = ...  # type: Optional[int]
 
@@ -117,7 +117,7 @@ class Exec(stmt):
     locals = ...  # type: Optional[expr]
 
 class Global(stmt):
-    names = ...  # type: typing.List[identifier]
+    names = ...  # type: typing.List[_identifier]
 
 class Expr(stmt):
     value = ...  # type: expr
@@ -222,7 +222,7 @@ class Str(expr):
 
 class Attribute(expr):
     value = ...  # type: expr
-    attr = ...  # type: identifier
+    attr = ...  # type: _identifier
     ctx = ...  # type: expr_context
 
 class Subscript(expr):
@@ -231,7 +231,7 @@ class Subscript(expr):
     ctx = ...  # type: expr_context
 
 class Name(expr):
-    id = ...  # type: identifier
+    id = ...  # type: _identifier
     ctx = ...  # type: expr_context
 
 class List(expr):
@@ -315,14 +315,14 @@ class ExceptHandler(AST):
 
 class arguments(AST):
     args = ...  # type: typing.List[expr]
-    vararg = ...  # type: Optional[identifier]
-    kwarg = ...  # type: Optional[identifier]
+    vararg = ...  # type: Optional[_identifier]
+    kwarg = ...  # type: Optional[_identifier]
     defaults = ...  # type: typing.List[expr]
 
 class keyword(AST):
-    arg = ...  # type: identifier
+    arg = ...  # type: _identifier
     value = ...  # type: expr
 
 class alias(AST):
-    name = ...  # type: identifier
-    asname = ...  # type: Optional[identifier]
+    name = ...  # type: _identifier
+    asname = ...  # type: Optional[_identifier]
diff --git a/typeshed/stdlib/2/_io.pyi b/typeshed/stdlib/2/_io.pyi
index 959d1d1..0a0b6d0 100644
--- a/typeshed/stdlib/2/_io.pyi
+++ b/typeshed/stdlib/2/_io.pyi
@@ -1,15 +1,18 @@
-from typing import Any, BinaryIO, IO, Iterable, Iterator, List, Optional, Type, Tuple, Union
+from typing import Any, AnyStr, BinaryIO, IO, Text, TextIO, Iterable, Iterator, List, Optional, Type, Tuple, TypeVar, Union
+from types import TracebackType
 
 DEFAULT_BUFFER_SIZE = ...  # type: int
 
-
 class BlockingIOError(IOError):
     characters_written = ...  # type: int
 
 class UnsupportedOperation(ValueError, IOError): ...
 
+_T = TypeVar("_T")
 
 class _IOBase(BinaryIO):
+    @property
+    def closed(self) -> bool: ...
     def _checkClosed(self) -> None: ...
     def _checkReadable(self) -> None: ...
     def _checkSeekable(self) -> None: ...
@@ -19,91 +22,147 @@ class _IOBase(BinaryIO):
     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: Optional[int] = ...) -> int: ...
     def writable(self) -> bool: ...
-    def write(self, s: bytes) -> int: ...
+    def __enter__(self: _T) -> _T: ...
+    def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> bool: ...
+    def __iter__(self: _T) -> _T: ...
+    # The parameter type of writelines[s]() is determined by that of write():
     def writelines(self, lines: Iterable[bytes]) -> None: ...
+    # The return type of readline[s]() and next() is determined by that of read():
+    def readline(self, limit: int = ...) -> bytes: ...
+    def readlines(self, hint: int = ...) -> list[bytes]: ...
     def next(self) -> bytes: ...
-    def __iter__(self) -> Iterator[bytes]: ...
-    def __enter__(self) -> '_IOBase': ...
-    def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException],
-                 # TODO: traceback should be TracebackType but that's defined in types
-                 traceback: Optional[Any]) -> bool: ...
 
 class _BufferedIOBase(_IOBase):
-    def read1(self, n: int) -> str: ...
-    def read(self, n: int = ...) -> str: ...
+    def read1(self, n: int) -> bytes: ...
+    def read(self, size: int = ...) -> bytes: ...
     def readinto(self, buffer: bytearray) -> int: ...
-    def write(self, s: str) -> int: ...
-    def detach(self) -> "_BufferedIOBase": ...
+    def write(self, s: bytes) -> int: ...
+    def detach(self) -> _IOBase: ...
 
 class BufferedRWPair(_BufferedIOBase):
-    def peek(self, n: int = ...) -> str: ...
+    def __init__(self, reader: _RawIOBase, writer: _RawIOBase,
+                 buffer_size: int = ..., max_buffer_size: int = ...) -> None: ...
+    def peek(self, n: int = ...) -> bytes: ...
+    def __enter__(self) -> BufferedRWPair: ...
 
 class BufferedRandom(_BufferedIOBase):
+    mode = ...  # type: str
     name = ...  # type: str
     raw = ...  # type: _IOBase
-    mode = ...  # type: str
-    def peek(self, n: int = ...) -> str: ...
+    def __init__(self, raw: _IOBase,
+                 buffer_size: int = ...,
+                 max_buffer_size: int = ...) -> None: ...
+    def peek(self, n: int = ...) -> bytes: ...
 
 class BufferedReader(_BufferedIOBase):
+    mode = ...  # type: str
     name = ...  # type: str
     raw = ...  # type: _IOBase
-    mode = ...  # type: str
-    def peek(self, n: int = ...) -> str: ...
+    def __init__(self, raw: _IOBase, buffer_size: int = ...) -> None: ...
+    def peek(self, n: int = ...) -> bytes: ...
 
 class BufferedWriter(_BufferedIOBase):
     name = ...  # type: str
     raw = ...  # type: _IOBase
     mode = ...  # type: str
+    def __init__(self, raw: _IOBase,
+                 buffer_size: int = ...,
+                 max_buffer_size: int = ...) -> None: ...
 
 class BytesIO(_BufferedIOBase):
+    def __init__(self, initial_bytes: bytes = ...) -> None: ...
     def __setstate__(self, tuple) -> None: ...
     def __getstate__(self) -> tuple: ...
-    def getvalue(self) -> str: ...
+    def getvalue(self) -> bytes: ...
+    def write(self, s: bytes) -> int: ...
+    def writelines(self, lines: Iterable[bytes]) -> None: ...
+    def read1(self, size: int) -> bytes: ...
+    def next(self) -> bytes: ...
 
 class _RawIOBase(_IOBase):
     def readall(self) -> str: ...
     def read(self, n: int = ...) -> str: ...
 
-class FileIO(_RawIOBase):
+class FileIO(_RawIOBase, BytesIO):  # type: ignore  # for __enter__
     mode = ...  # type: str
     closefd = ...  # type: bool
+    def __init__(self, file: str, mode: str = ...) -> None: ...
     def readinto(self, buffer: bytearray)-> int: ...
     def write(self, pbuf: str) -> int: ...
 
 class IncrementalNewlineDecoder(object):
     newlines = ...  # type: Union[str, unicode]
+    def __init__(self, decoder, translate, z=...) -> None: ...
     def decode(self, input, final) -> Any: ...
     def getstate(self) -> Tuple[Any, int]: ...
     def setstate(self, state: Tuple[Any, int]) -> None: ...
     def reset(self) -> None: ...
 
-class _TextIOBase(_IOBase):
+
+# Note: In the actual _io.py, _TextIOBase inherits from _IOBase.
+class _TextIOBase(TextIO):
     errors = ...  # type: Optional[str]
-    newlines = ...  # type: Union[str, unicode]
-    encoding = ...  # type: Optional[str]
-    def read(self, n: int = ...) -> str: ...
-    def detach(self) -> None:
-        raise UnsupportedOperation
+    # TODO: On _TextIOBase, this is always None. But it's unicode/bytes in subclasses.
+    newlines = ...  # type: Union[None, unicode, bytes]
+    encoding = ...  # type: str
+    @property
+    def closed(self) -> bool: ...
+    def _checkClosed(self) -> None: ...
+    def _checkReadable(self) -> None: ...
+    def _checkSeekable(self) -> None: ...
+    def _checkWritable(self) -> None: ...
+    def close(self) -> None: ...
+    def detach(self) -> IO: ...
+    def fileno(self) -> int: ...
+    def flush(self) -> None: ...
+    def isatty(self) -> bool: ...
+    def next(self) -> unicode: ...
+    def read(self, size: int = ...) -> unicode: ...
+    def readable(self) -> bool: ...
+    def readline(self, limit: int = ...) -> unicode: ...
+    def readlines(self, hint: int = ...) -> list[unicode]: ...
+    def seek(self, offset: int, whence: int = ...) -> int: ...
+    def seekable(self) -> bool: ...
+    def tell(self) -> int: ...
+    def truncate(self, size: Optional[int] = ...) -> int: ...
+    def writable(self) -> bool: ...
+    def write(self, pbuf: unicode) -> int: ...
+    def writelines(self, lines: Iterable[unicode]) -> None: ...
+    def __enter__(self: _T) -> _T: ...
+    def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> bool: ...
+    def __iter__(self: _T) -> _T: ...
 
 class StringIO(_TextIOBase):
     line_buffering = ...  # type: bool
-    def getvalue(self) -> str: ...
+    def __init__(self,
+                 initial_value: Optional[unicode] = ...,
+                 newline: Optional[unicode] = ...) -> None: ...
     def __setstate__(self, state: tuple) -> None: ...
     def __getstate__(self) -> tuple: ...
+    def getvalue(self) -> unicode: ...
 
 class TextIOWrapper(_TextIOBase):
     name = ...  # type: str
     line_buffering = ...  # type: bool
-    buffer = ...  # type: str
+    buffer = ...  # type: BinaryIO
     _CHUNK_SIZE = ...  # type: int
-
-def open(file: Union[int, str], mode: str = ...) -> _IOBase: ...
+    def __init__(self, buffer: IO,
+                 encoding: Optional[Text] = ...,
+                 errors: Optional[Text] = ...,
+                 newline: Optional[Text] = ...,
+                 line_buffering: bool = ...,
+                 write_through: bool = ...) -> None: ...
+
+def open(file: Union[str, unicode, int],
+         mode: unicode = ...,
+         buffering: int = ...,
+         encoding: Optional[Text] = ...,
+         errors: Optional[Text] = ...,
+         newline: Optional[Text] = ...,
+         closefd: bool = ...) -> IO[Any]: ...
diff --git a/typeshed/stdlib/2/_threading_local.pyi b/typeshed/stdlib/2/_threading_local.pyi
new file mode 100644
index 0000000..512bf58
--- /dev/null
+++ b/typeshed/stdlib/2/_threading_local.pyi
@@ -0,0 +1,14 @@
+# Source: https://hg.python.org/cpython/file/2.7/Lib/_threading_local.py
+from typing import Any, List
+
+__all__: List[str]
+
+class _localbase(object): ...
+
+class local(_localbase):
+    def __getattribute__(self, name: str) -> Any: ...
+    def __setattr__(self, name: str, value: Any) -> None: ...
+    def __delattr__(self, name: str) -> None: ...
+    def __del__(self) -> None: ...
+
+def _patch(self: local) -> None: ...
diff --git a/typeshed/stdlib/2/_weakrefset.pyi b/typeshed/stdlib/2/_weakrefset.pyi
deleted file mode 100644
index 27aade6..0000000
--- a/typeshed/stdlib/2/_weakrefset.pyi
+++ /dev/null
@@ -1,14 +0,0 @@
-from typing import Iterator, Any, Iterable, MutableSet, TypeVar, Generic
-
-_T = TypeVar('_T')
-
-class WeakSet(MutableSet[_T], Generic[_T]):
-    def __init__(self, data: Iterable[_T] = ...) -> None: ...
-
-    def add(self, x: _T) -> None: ...
-    def discard(self, x: _T) -> None: ...
-    def __contains__(self, x: Any) -> bool: ...
-    def __len__(self) -> int: ...
-    def __iter__(self) -> Iterator[_T]: ...
-
-    # TODO: difference, difference_update, ...
diff --git a/typeshed/stdlib/2/ast.pyi b/typeshed/stdlib/2/ast.pyi
index 244b230..d22a6f8 100644
--- a/typeshed/stdlib/2/ast.pyi
+++ b/typeshed/stdlib/2/ast.pyi
@@ -21,7 +21,7 @@ __version__ = ...  # type: str
 PyCF_ONLY_AST = ...  # type: int
 
 
-def parse(source: Union[str, bytes], filename: Union[str, bytes] = ..., mode: str = ...) -> Module: ...
+def parse(source: Union[str, unicode], filename: Union[str, unicode] = ..., mode: Union[str, unicode] = ...) -> Module: ...
 def copy_location(new_node: AST, old_node: AST) -> AST: ...
 def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ...
 def fix_missing_locations(node: AST) -> AST: ...
@@ -29,7 +29,7 @@ def get_docstring(node: AST, clean: bool = ...) -> str: ...
 def increment_lineno(node: AST, n: int = ...) -> AST: ...
 def iter_child_nodes(node: AST) -> Iterator[AST]: ...
 def iter_fields(node: AST) -> Iterator[typing.Tuple[str, Any]]: ...
-def literal_eval(node_or_string: Union[str, AST]) -> Any: ...
+def literal_eval(node_or_string: Union[str, unicode, AST]) -> Any: ...
 def walk(node: AST) -> Iterator[AST]: ...
 
 class NodeVisitor():
diff --git a/typeshed/stdlib/2/builtins.pyi b/typeshed/stdlib/2/builtins.pyi
index 541122b..a681ab6 100644
--- a/typeshed/stdlib/2/builtins.pyi
+++ b/typeshed/stdlib/2/builtins.pyi
@@ -88,11 +88,10 @@ class type(object):
 
 class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
     @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, x: SupportsInt) -> None: ...
+    def __init__(self, x: SupportsInt = ...) -> None: ...
     @overload
-    def __init__(self, x: Union[str, unicode, bytearray], base: int = 10) -> None: ...
+    def __init__(self, x: Union[str, unicode, bytearray], base: int = ...) -> None: ...
+
     def bit_length(self) -> int: ...
 
     def __add__(self, x: int) -> int: ...
@@ -140,14 +139,7 @@ class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
     def __nonzero__(self) -> bool: ...
 
 class float(SupportsFloat, SupportsInt, SupportsAbs[float]):
-    @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, x: SupportsFloat) -> None: ...
-    @overload
-    def __init__(self, x: unicode) -> None: ...
-    @overload
-    def __init__(self, x: bytearray) -> None: ...
+    def __init__(self, x: Union[SupportsFloat, str, unicode, bytearray] = ...) -> None: ...
     def as_integer_ratio(self) -> Tuple[int, int]: ...
     def hex(self) -> str: ...
     def is_integer(self) -> bool: ...
@@ -309,7 +301,7 @@ class unicode(basestring, Sequence[unicode]):
     def __hash__(self) -> int: ...
 
 class str(basestring, Sequence[str]):
-    def __init__(self, object: object='') -> None: ...
+    def __init__(self, object: object = ...) -> None: ...
     def capitalize(self) -> str: ...
     def center(self, width: int, fillchar: str = ...) -> str: ...
     def count(self, x: unicode, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ...
@@ -487,7 +479,7 @@ class slice(object):
     @overload
     def __init__(self, stop: Optional[int]) -> None: ...
     @overload
-    def __init__(self, start: Optional[int], stop: Optional[int], step: int = None) -> None: ...
+    def __init__(self, start: Optional[int], stop: Optional[int], step: Optional[int] = None) -> None: ...
     def indices(self, len: int) -> Tuple[int, int, int]: ...
 
 class tuple(Sequence[_T_co], Generic[_T_co]):
@@ -574,9 +566,11 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
     def popitem(self) -> Tuple[_KT, _VT]: ...
     def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ...
     @overload
-    def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    @overload
+    def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
     @overload
-    def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
+    def update(self, **kwargs: _VT) -> None: ...
     def iterkeys(self) -> Iterator[_KT]: ...
     def itervalues(self) -> Iterator[_VT]: ...
     def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ...
@@ -676,13 +670,13 @@ class xrange(Sized, Iterable[int], Reversible[int]):
     def __reversed__(self) -> Iterator[int]: ...
 
 class property(object):
-    def __init__(self, fget: Callable[[Any], Any] = None,
-                 fset: Callable[[Any, Any], None] = None,
-                 fdel: Callable[[Any], None] = None, doc: str = None) -> None: ...
+    def __init__(self, fget: Optional[Callable[[Any], Any]] = None,
+                 fset: Optional[Callable[[Any, Any], None]] = None,
+                 fdel: Optional[Callable[[Any], None]] = None, doc: Optional[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 __get__(self, obj: Any, type: Optional[type] = None) -> Any: ...
     def __set__(self, obj: Any, value: Any) -> None: ...
     def __delete__(self, obj: Any) -> None: ...
     def fget(self) -> Any: ...
@@ -716,7 +710,7 @@ def filter(function: Callable[[_T], Any],
 def filter(function: None,
            iterable: Iterable[Optional[_T]]) -> List[_T]: ...
 def format(o: object, format_spec: str = '') -> str: ...  # TODO unicode
-def getattr(o: Any, name: unicode, default: Any = None) -> Any: ...
+def getattr(o: Any, name: unicode, default: Optional[Any] = None) -> Any: ...
 def hasattr(o: Any, name: unicode) -> bool: ...
 def hash(o: object) -> int: ...
 def hex(i: int) -> str: ...  # TODO __index__
@@ -750,14 +744,14 @@ def next(i: Iterator[_T]) -> _T: ...
 def next(i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ...
 def oct(i: int) -> str: ...  # TODO __index__
 @overload
-def open(file: str, mode: str = 'r', buffering: int = ...) -> BinaryIO: ...
+def open(file: str, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ...
 @overload
-def open(file: unicode, mode: str = 'r', buffering: int = ...) -> BinaryIO: ...
+def open(file: unicode, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ...
 @overload
-def open(file: int, mode: str = 'r', buffering: int = ...) -> BinaryIO: ...
+def open(file: int, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ...
 def ord(c: unicode) -> int: ...
 # This is only available after from __future__ import print_function.
-def print(*values: Any, sep: unicode = u' ', end: unicode = u'\n',
+def print(*values: Any, sep: unicode = ..., end: unicode = ...,
            file: IO[Any] = ...) -> None: ...
 @overload
 def pow(x: int, y: int) -> Any: ...  # The return type can be int or float, depending on y.
@@ -768,7 +762,7 @@ def pow(x: float, y: float) -> float: ...
 @overload
 def pow(x: float, y: float, z: float) -> float: ...
 def quit(code: int = ...) -> None: ...
-def range(x: int, y: int = 0, step: int = 1) -> List[int]: ...
+def range(x: int, y: int = ..., step: int = ...) -> List[int]: ...
 def raw_input(prompt: Any = ...) -> str: ...
 
 @overload
@@ -939,14 +933,14 @@ class UnicodeWarning(Warning): ...
 class BytesWarning(Warning): ...
 class ResourceWarning(Warning): ...
 
-def eval(s: str, globals: Dict[str, Any] = ..., locals: Dict[str, Any] = ...) -> Any: ...
+def eval(s: Union[str, unicode], globals: Dict[str, Any] = ..., locals: Dict[str, Any] = ...) -> Any: ...
 def exec(object: str,
-         globals: Dict[str, Any] = None,
-         locals: Dict[str, Any] = None) -> Any: ...  # TODO code object as source
+         globals: Optional[Dict[str, Any]] = None,
+         locals: Optional[Dict[str, Any]] = None) -> Any: ...  # TODO code object as source
 
 def cmp(x: Any, y: Any) -> int: ...
 
-def execfile(filename: str, globals: Dict[str, Any] = None, locals: Dict[str, Any] = None) -> None: ...
+def execfile(filename: str, globals: Optional[Dict[str, Any]] = None, locals: Optional[Dict[str, Any]] = None) -> None: ...
 
 class file(BinaryIO):
     @overload
@@ -958,7 +952,7 @@ class file(BinaryIO):
     def __iter__(self) -> Iterator[str]: ...
     def read(self, n: int = ...) -> str: ...
     def __enter__(self) -> BinaryIO: ...
-    def __exit__(self, t: type = None, exc: BaseException = None, tb: Any = None) -> bool: ...
+    def __exit__(self, t: Optional[type] = None, exc: Optional[BaseException] = None, tb: Optional[Any] = None) -> bool: ...
     def flush(self) -> None: ...
     def fileno(self) -> int: ...
     def isatty(self) -> bool: ...
@@ -976,6 +970,6 @@ class file(BinaryIO):
     def truncate(self, pos: Optional[int] = ...) -> int: ...
 
 # Very old builtins
-def apply(func: Callable[..., _T], args: Sequence[Any] = None, kwds: Mapping[str, Any] = None) -> _T: ...
+def apply(func: Callable[..., _T], args: Optional[Sequence[Any]] = None, kwds: Optional[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/calendar.pyi b/typeshed/stdlib/2/calendar.pyi
deleted file mode 100644
index 6f1fd45..0000000
--- a/typeshed/stdlib/2/calendar.pyi
+++ /dev/null
@@ -1,92 +0,0 @@
-from typing import Any, Iterable, List, Optional, Tuple, Sequence
-import datetime
-
-LocaleType = Tuple[Optional[str], Optional[str]]
-
-class IllegalMonthError(ValueError):
-    def __init__(self, month: int) -> None: ...
-    def __str__(self) -> str: ...
-
-class IllegalWeekdayError(ValueError):
-    def __init__(self, weekday: int) -> None: ...
-    def __str__(self) -> str: ...
-
-def isleap(year: int) -> bool: ...
-def leapdays(y1: int, y2: int) -> int: ...
-def weekday(year: int, month: int, day: int) -> int: ...
-def monthrange(year: int, month: int) -> Tuple[int, int]: ...
-
-class Calendar(object):
-    def __init__(self, firstweekday: int = 0) -> None: ...
-    def getfirstweekday(self) -> int: ...
-    def setfirstweekday(self, firstweekday: int) -> None: ...
-    def iterweekdays(self) -> Iterable[int]: ...
-    def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ...
-    def itermonthdays2(self, year: int, month: int) -> Iterable[Tuple[int, int]]: ...
-    def itermonthdays(self, year: int, month: int) -> Iterable[int]: ...
-    def monthdatescalendar(self, year: int, month: int) -> List[List[datetime.date]]: ...
-    def monthdays2calendar(self, year: int, month: int) -> List[List[Tuple[int, int]]]: ...
-    def monthdayscalendar(self, year: int, month: int) -> List[List[int]]: ...
-    def yeardatescalendar(self, year: int, width: int = 3) -> List[List[int]]: ...
-    def yeardays2calendar(self, year: int, width: int = 3) -> List[List[Tuple[int, int]]]: ...
-    def yeardayscalendar(self, year: int, width: int = 3) -> List[List[int]]: ...
-
-class TextCalendar(Calendar):
-    def prweek(self, theweek: int, width: int) -> None: ...
-    def formatday(self, day: int, weekday: int, width: int) -> str: ...
-    def formatweek(self, theweek: int, width: int) -> str: ...
-    def formatweekday(self, day: int, width: int) -> str: ...
-    def formatweekheader(self, width: int) -> str: ...
-    def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ...
-    def prmonth(self, theyear: int, themonth: int, w: Any=0, l: Any = 0) -> None: ...
-    def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ...
-    def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ...
-    def pryear(self, theyear: int, w: Any = 0, l: Any = 0, c: Any = 6, m: Any = 3) -> None: ...
-
-class HTMLCalendar(Calendar):
-    def formatday(self, day: int, weekday: int) -> str: ...
-    def formatweek(self, theweek: int) -> str: ...
-    def formatweekday(self, day: int) -> str: ...
-    def formatweekheader(self) -> str: ...
-    def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ...
-    def formatmonth(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ...
-    def formatyear(self, theyear: int, width: int = 3) -> str: ...
-    def formatyearpage(self, theyear: int, width: int = 3, css: Optional[str] = ..., encoding: Optional[str] = ...) -> str: ...
-
-class TimeEncoding:
-    def __init__(self, locale: LocaleType) -> None: ...
-    def __enter__(self) -> LocaleType: ...
-    def __exit__(self, *args) -> None: ...
-
-class LocaleTextCalendar(TextCalendar):
-    def __init__(self, firstweekday: int = 0, locale: Optional[LocaleType] = ...) -> None: ...
-    def formatweekday(self, day: int, width: int) -> str: ...
-    def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ...
-
-class LocaleHTMLCalendar(HTMLCalendar):
-    def __init__(self, firstweekday: int = 0, locale: Optional[LocaleType] = ...) -> None: ...
-    def formatweekday(self, day: int) -> str: ...
-    def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ...
-
-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: ...
-
-# Data attributes
-day_name = ...  # type: Sequence[str]
-day_abbr = ...  # type: Sequence[str]
-month_name = ...  # type: Sequence[str]
-month_abbr = ...  # type: Sequence[str]
-
-# Below constants are not in docs or __all__, but enough people have used them
-# they are now effectively public.
-
-MONDAY = ...  # type: int
-TUESDAY = ...  # type: int
-WEDNESDAY = ...  # type: int
-THURSDAY = ...  # type: int
-FRIDAY = ...  # type: int
-SATURDAY = ...  # type: int
-SUNDAY = ...  # type: int
diff --git a/typeshed/stdlib/2/collections.pyi b/typeshed/stdlib/2/collections.pyi
index 5360fe6..1fab274 100644
--- a/typeshed/stdlib/2/collections.pyi
+++ b/typeshed/stdlib/2/collections.pyi
@@ -3,7 +3,8 @@
 # Based on http://docs.python.org/2.7/library/collections.html
 
 # These are not exported.
-from typing import Any, Dict, Generic, TypeVar, Tuple, overload, Type, Optional, List, Union, Reversible
+import typing
+from typing import Dict, Generic, TypeVar, Tuple, overload, Type, Optional, List, Union, Reversible
 
 # These are exported.
 from typing import (
@@ -30,7 +31,7 @@ _KT = TypeVar('_KT')
 _VT = TypeVar('_VT')
 
 # namedtuple is special-cased in the type checker; the initializer is ignored.
-def namedtuple(typename: Union[str, unicode], field_names: Union[str, unicode, Iterable[Any]], *,
+def namedtuple(typename: Union[str, unicode], field_names: Union[str, unicode, Iterable[Union[str, unicode]]], *,
                verbose: bool = ..., rename: bool = ...) -> Type[tuple]: ...
 
 class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]):
@@ -59,17 +60,16 @@ class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]):
     def __reversed__(self) -> Iterator[_T]: ...
 
 class Counter(Dict[_T, int], Generic[_T]):
-    # TODO: __init__ keyword arguments
     @overload
-    def __init__(self) -> None: ...
+    def __init__(self, **kwargs: int) -> None: ...
     @overload
-    def __init__(self, Mapping: Mapping[_T, int]) -> None: ...
+    def __init__(self, mapping: Mapping[_T, int]) -> None: ...
     @overload
     def __init__(self, iterable: Iterable[_T]) -> None: ...
     def elements(self) -> Iterator[_T]: ...
     def most_common(self, n: int = ...) -> List[_T]: ...
     @overload
-    def subtract(self, mapping: Mapping[_T, int]) -> None: ...
+    def subtract(self, __mapping: Mapping[_T, int]) -> None: ...
     @overload
     def subtract(self, iterable: Iterable[_T]) -> None: ...
     # The Iterable[Tuple[...]] argument type is not actually desirable
@@ -78,30 +78,35 @@ class Counter(Dict[_T, int], Generic[_T]):
     # Dict.update. Not sure if we should use '# type: ignore' instead
     # and omit the type from the union.
     @overload
-    def update(self, m: Mapping[_T, int], **kwargs: _VT) -> None: ...
+    def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ...
     @overload
-    def update(self, m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: _VT) -> None: ...
+    def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ...
+    @overload
+    def update(self, **kwargs: int) -> None: ...
+
+    def __add__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __sub__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __and__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __or__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __isub__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __iand__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __ior__(self, other: Counter[_T]) -> Counter[_T]: ...
 
 class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]):
     def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ...
-    def move_to_end(self, key: _KT, last: bool = ...) -> None: ...
     def __reversed__(self) -> Iterator[_KT]: ...
 
 class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]):
     default_factory = ...  # type: Callable[[], _VT]
-    # TODO: __init__ keyword args
-    @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, map: Mapping[_KT, _VT]) -> None: ...
     @overload
-    def __init__(self, iterable: Iterable[Tuple[_KT, _VT]]) -> None: ...
+    def __init__(self, **kwargs: _VT) -> None: ...
     @overload
-    def __init__(self, default_factory: Callable[[], _VT]) -> None: ...
+    def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ...
     @overload
-    def __init__(self, default_factory: Callable[[], _VT],
+    def __init__(self, default_factory: Optional[Callable[[], _VT]],
                  map: Mapping[_KT, _VT]) -> None: ...
     @overload
-    def __init__(self, default_factory: Callable[[], _VT],
+    def __init__(self, default_factory: Optional[Callable[[], _VT]],
                  iterable: Iterable[Tuple[_KT, _VT]]) -> None: ...
     def __missing__(self, key: _KT) -> _VT: ...
diff --git a/typeshed/stdlib/2/compileall.pyi b/typeshed/stdlib/2/compileall.pyi
index 28f079a..c3e861e 100644
--- a/typeshed/stdlib/2/compileall.pyi
+++ b/typeshed/stdlib/2/compileall.pyi
@@ -4,7 +4,7 @@ from typing import Optional, Pattern, Union
 
 _Path = Union[str, bytes]
 
-# fx can be any object with a 'search' method; once we have Protocols we can change the type
-def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ...) -> None: ...
-def compile_file(fullname: _Path, ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ...) -> None: ...
-def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> None: ...
+# rx can be any object with a 'search' method; once we have Protocols we can change the type
+def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ...) -> int: ...
+def compile_file(fullname: _Path, ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ...) -> int: ...
+def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> int: ...
diff --git a/typeshed/stdlib/2/cookielib.pyi b/typeshed/stdlib/2/cookielib.pyi
index f7389df..e17f17a 100644
--- a/typeshed/stdlib/2/cookielib.pyi
+++ b/typeshed/stdlib/2/cookielib.pyi
@@ -1,7 +1,3 @@
-# Stubs for cookielib (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class Cookie:
diff --git a/typeshed/stdlib/2/csv.pyi b/typeshed/stdlib/2/csv.pyi
deleted file mode 100644
index 51a57e4..0000000
--- a/typeshed/stdlib/2/csv.pyi
+++ /dev/null
@@ -1,88 +0,0 @@
-# Stubs for csv (Python 2.7)
-#
-# NOTE: Based on a dynamically typed stub automatically generated by stubgen.
-
-from typing import Any, Dict, Iterable, List, Sequence, Type, Union
-
-# Public interface of _csv.reader's return type
-class _Reader(Iterable[List[str]]):
-    dialect = ...  # type: Dialect
-    line_num = ...  # type: int
-
-    def next(self) -> List[str]: ...
-
-_Row = Sequence[Any]  # May contain anything: csv calls str() on the elements that are not None
-
-# Public interface of _csv.writer's return type
-class _Writer:
-    dialect = ...  # type: Dialect
-
-    def writerow(self, row: _Row) -> None: ...
-    def writerows(self, rows: Iterable[_Row]) -> None: ...
-
-QUOTE_ALL = ...  # type: int
-QUOTE_MINIMAL = ...  # type: int
-QUOTE_NONE = ...  # type: int
-QUOTE_NONNUMERIC = ...  # type: int
-
-class Error(Exception): ...
-
-_Dialect = Union[str, Dialect, Type[Dialect]]
-
-def writer(csvfile: Any, dialect: _Dialect = ..., **fmtparams) -> _Writer: ...
-def reader(csvfile: Iterable[str], dialect: _Dialect = ..., **fmtparams) -> _Reader: ...
-def register_dialect(name, dialect=..., **fmtparams): ...
-def unregister_dialect(name): ...
-def get_dialect(name: str) -> Dialect: ...
-def list_dialects(): ...
-def field_size_limit(new_limit: int = ...) -> int: ...
-
-class Dialect:
-    delimiter = ...  # type: str
-    quotechar = ...  # type: str
-    escapechar = ...  # type: str
-    doublequote = ...  # type: bool
-    skipinitialspace = ...  # type: bool
-    lineterminator = ...  # type: str
-    quoting = ...  # type: int
-    def __init__(self) -> None: ...
-
-class excel(Dialect):
-    pass
-
-class excel_tab(excel):
-    pass
-
-class unix_dialect(Dialect):
-    pass
-
-class DictReader(Iterable):
-    restkey = ...  # type: Any
-    restval = ...  # type: Any
-    reader = ...  # type: Any
-    dialect = ...  # type: _Dialect
-    line_num = ...  # type: int
-    fieldnames = ...  # type: Sequence[Any]
-    def __init__(self, f: Iterable[str], fieldnames: Sequence[Any] = ..., restkey=...,
-                 restval=..., dialect: _Dialect = ..., *args, **kwds) -> None: ...
-    def __iter__(self): ...
-    def next(self): ...
-
-_DictRow = Dict[Any, Union[str, int]]
-
-class DictWriter:
-    fieldnames = ...  # type: Any
-    restval = ...  # type: Any
-    extrasaction = ...  # type: Any
-    writer = ...  # type: Any
-    def __init__(self, f: Any, fieldnames: Sequence[Any], restval=..., extrasaction: str = ...,
-                 dialect: _Dialect = ..., *args, **kwds) -> None: ...
-    def writeheader(self) -> None: ...
-    def writerow(self, rowdict: _DictRow) -> None: ...
-    def writerows(self, rowdicts: Iterable[_DictRow]) -> None: ...
-
-class Sniffer:
-    preferred = ...  # type: Any
-    def __init__(self) -> None: ...
-    def sniff(self, sample: str, delimiters: str = ...) -> Dialect: ...
-    def has_header(self, sample: str) -> bool: ...
diff --git a/typeshed/stdlib/2/datetime.pyi b/typeshed/stdlib/2/datetime.pyi
index eb91541..2a804b2 100644
--- a/typeshed/stdlib/2/datetime.pyi
+++ b/typeshed/stdlib/2/datetime.pyi
@@ -89,7 +89,7 @@ class time:
     def tzname(self) -> Optional[str]: ...
     def dst(self) -> Optional[int]: ...
     def replace(self, hour: int = ..., minute: int = ..., second: int = ...,
-                microsecond: int = ..., tzinfo: Union[_tzinfo, bool] = ...) -> time: ...
+                microsecond: int = ..., tzinfo: Optional[_tzinfo] = ...) -> time: ...
 
 _date = date
 _time = time
@@ -143,6 +143,9 @@ class datetime(object):
     def __init__(self, year: int, month: int, day: int, hour: int = ...,
                  minute: int = ..., second: int = ..., microseconds: int = ...,
                  tzinfo: tzinfo = ...) -> None: ...
+    def __new__(cls, year: int, month: int, day: int, hour: int = ...,
+                minute: int = ..., second: int = ..., microseconds: int = ...,
+                tzinfo: tzinfo = ...) -> datetime: ...
 
     @property
     def year(self) -> int: ...
@@ -185,7 +188,7 @@ class datetime(object):
     def timetz(self) -> _time: ...
     def replace(self, year: int = ..., month: int = ..., day: int = ..., hour: int = ...,
                 minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo:
-                Union[_tzinfo, bool] = ...) -> datetime: ...
+                Optional[_tzinfo] = ...) -> datetime: ...
     def astimezone(self, tz: _tzinfo) -> datetime: ...
     def ctime(self) -> str: ...
     def isoformat(self, sep: str = ...) -> str: ...
diff --git a/typeshed/stdlib/2/doctest.pyi b/typeshed/stdlib/2/doctest.pyi
deleted file mode 100644
index ab88328..0000000
--- a/typeshed/stdlib/2/doctest.pyi
+++ /dev/null
@@ -1,9 +0,0 @@
-# Stubs for doctest
-
-# NOTE: These are incomplete!
-
-from typing import Any, Tuple
-
-# TODO arguments missing
-def testmod(m: Any = ..., name: str = ..., globs: Any = ...,
-            verbose: bool = ...) -> Tuple[int, int]: ...
diff --git a/typeshed/stdlib/2/dummy_thread.pyi b/typeshed/stdlib/2/dummy_thread.pyi
new file mode 100644
index 0000000..df1b21a
--- /dev/null
+++ b/typeshed/stdlib/2/dummy_thread.pyi
@@ -0,0 +1,22 @@
+from mypy_extensions import NoReturn
+from typing import Any, Callable, Dict, Optional, Tuple
+
+class error(Exception):
+    def __init__(self, *args: Any) -> None: ...
+
+def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ...
+def exit() -> NoReturn: ...
+def get_ident() -> int: ...
+def allocate_lock() -> LockType: ...
+def stack_size(size: Optional[int] = ...) -> int: ...
+
+class LockType(object):
+    locked_status: bool
+    def __init__(self) -> None: ...
+    def acquire(self, waitflag: Optional[bool] = ...) -> bool: ...
+    def __enter__(self, waitflag: Optional[bool] = ...) -> bool: ...
+    def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ...
+    def release(self) -> bool: ...
+    def locked(self) -> bool: ...
+
+def interrupt_main() -> None: ...
diff --git a/typeshed/stdlib/2/email/MIMEText.pyi b/typeshed/stdlib/2/email/MIMEText.pyi
index a15eb1d..3b05977 100644
--- a/typeshed/stdlib/2/email/MIMEText.pyi
+++ b/typeshed/stdlib/2/email/MIMEText.pyi
@@ -1,7 +1,3 @@
-# Stubs for email.MIMEText (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from email.mime.nonmultipart import MIMENonMultipart
 
 class MIMEText(MIMENonMultipart):
diff --git a/typeshed/stdlib/2/email/_parseaddr.pyi b/typeshed/stdlib/2/email/_parseaddr.pyi
index 97e859e..beba33f 100644
--- a/typeshed/stdlib/2/email/_parseaddr.pyi
+++ b/typeshed/stdlib/2/email/_parseaddr.pyi
@@ -1,7 +1,3 @@
-# Stubs for email._parseaddr (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def parsedate_tz(data): ...
diff --git a/typeshed/stdlib/2/email/mime/base.pyi b/typeshed/stdlib/2/email/mime/base.pyi
index 0a3eb4c..4eaabce 100644
--- a/typeshed/stdlib/2/email/mime/base.pyi
+++ b/typeshed/stdlib/2/email/mime/base.pyi
@@ -1,6 +1,4 @@
-# Stubs for email.mime.base (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+# NOTE: This stub is incomplete.
 
 # import message
 
diff --git a/typeshed/stdlib/2/email/mime/multipart.pyi b/typeshed/stdlib/2/email/mime/multipart.pyi
index 2bc5a9e..0a7d3fa 100644
--- a/typeshed/stdlib/2/email/mime/multipart.pyi
+++ b/typeshed/stdlib/2/email/mime/multipart.pyi
@@ -1,7 +1,3 @@
-# Stubs for email.mime.multipart (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from email.mime.base import MIMEBase
 
 class MIMEMultipart(MIMEBase):
diff --git a/typeshed/stdlib/2/email/mime/nonmultipart.pyi b/typeshed/stdlib/2/email/mime/nonmultipart.pyi
index b0894ab..04d130e 100644
--- a/typeshed/stdlib/2/email/mime/nonmultipart.pyi
+++ b/typeshed/stdlib/2/email/mime/nonmultipart.pyi
@@ -1,7 +1,3 @@
-# Stubs for email.mime.nonmultipart (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from email.mime.base import MIMEBase
 
 class MIMENonMultipart(MIMEBase):
diff --git a/typeshed/stdlib/2/email/mime/text.pyi b/typeshed/stdlib/2/email/mime/text.pyi
index b6ec4c8..3b05977 100644
--- a/typeshed/stdlib/2/email/mime/text.pyi
+++ b/typeshed/stdlib/2/email/mime/text.pyi
@@ -1,7 +1,3 @@
-# Stubs for email.mime.text (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from email.mime.nonmultipart import MIMENonMultipart
 
 class MIMEText(MIMENonMultipart):
diff --git a/typeshed/stdlib/2/email/utils.pyi b/typeshed/stdlib/2/email/utils.pyi
index 48d2aa3..293a4c3 100644
--- a/typeshed/stdlib/2/email/utils.pyi
+++ b/typeshed/stdlib/2/email/utils.pyi
@@ -1,7 +1,3 @@
-# Stubs for email.utils (Python 2)
-#
-# Derived from stub automatically generated by stubgen.
-
 from email._parseaddr import AddressList as _AddressList
 from email._parseaddr import mktime_tz as mktime_tz
 from email._parseaddr import parsedate as _parsedate
diff --git a/typeshed/stdlib/2/fileinput.pyi b/typeshed/stdlib/2/fileinput.pyi
deleted file mode 100644
index f3e1f37..0000000
--- a/typeshed/stdlib/2/fileinput.pyi
+++ /dev/null
@@ -1,46 +0,0 @@
-from typing import Iterable, Callable, IO, Optional, Union, Iterator
-
-class FileInput(Iterable[str]):
-    def __init__(
-        self,
-        files: Optional[Union[str, Iterable[str]]] = None,
-        inplace: bool = ...,
-        backup: str = ...,
-        bufsize: int = ...,
-        mode: str = ...,
-        openhook: Callable[[str, str], IO[str]] = ...
-    ) -> None: ...
-
-    def __del__(self) -> None: ...
-    def close(self) -> None: ...
-    def __iter__(self) -> Iterator[str]: ...
-    def __getitem__(self, i: Union[int, slice]) -> str: ...
-    def next(self) -> str: ...
-    def nextfile(self) -> None: ...
-    def readline(self) -> str: ...
-    def filename(self) -> Optional[str]: ...
-    def lineno(self) -> int: ...
-    def filelineno(self) -> int: ...
-    def fileno(self) -> int: ...
-    def isfirstline(self) -> bool: ...
-    def isstdin(self) -> bool: ...
-
-def input(
-    files: Optional[Union[str, Iterable[str]]] = None,
-    inplace: bool = ...,
-    backup: str = ...,
-    bufsize: int = ...,
-    mode: str = ...,
-    openhook: Callable[[str, str], IO[str]] = ...) -> FileInput: ...
-
-
-def filename() -> Optional[str]: ...
-def lineno() -> int: ...
-def filelineno() -> int: ...
-def isfirstline() -> bool: ...
-def isstdin() -> bool: ...
-def nextfile() -> None: ...
-def close() -> None: ...
-
-def hook_compressed(filename: str, mode: str) -> IO[str]: ...
-def hook_encoded(encoding: str) -> Callable[[str, str], IO[str]]: ...
diff --git a/typeshed/stdlib/2/genericpath.pyi b/typeshed/stdlib/2/genericpath.pyi
index 85f1c0f..24bbbba 100644
--- a/typeshed/stdlib/2/genericpath.pyi
+++ b/typeshed/stdlib/2/genericpath.pyi
@@ -1,14 +1,12 @@
-# Stubs for genericpath (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import AnyStr, List
 
 class _unicode: ...
 
-def exists(path): ...
-def isfile(path): ...
-def isdir(s): ...
-def getsize(filename): ...
-def getmtime(filename): ...
-def getatime(filename): ...
-def getctime(filename): ...
-def commonprefix(m): ...
+def commonprefix(list: List[AnyStr]) -> AnyStr: ...
+def exists(path: unicode) -> bool: ...
+def getatime(path: unicode) -> float: ...
+def getmtime(path: unicode) -> float: ...
+def getctime(path: unicode) -> float: ...
+def getsize(path: unicode) -> int: ...
+def isfile(path: unicode) -> bool: ...
+def isdir(path: unicode) -> bool: ...
diff --git a/typeshed/stdlib/2/glob.pyi b/typeshed/stdlib/2/glob.pyi
index 9b70e5c..667a51f 100644
--- a/typeshed/stdlib/2/glob.pyi
+++ b/typeshed/stdlib/2/glob.pyi
@@ -1,4 +1,6 @@
-from typing import List, Iterator, AnyStr
+from typing import List, Iterator, Union, AnyStr
 
 def glob(pathname: AnyStr) -> List[AnyStr]: ...
 def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ...
+def glob1(dirname: Union[str, unicode], pattern: AnyStr) -> List[AnyStr]: ...
+def glob0(dirname: Union[str, unicode], basename: AnyStr) -> List[AnyStr]: ...
diff --git a/typeshed/stdlib/2/grp.pyi b/typeshed/stdlib/2/grp.pyi
deleted file mode 100644
index 6a1f758..0000000
--- a/typeshed/stdlib/2/grp.pyi
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import Optional, List
-
-class struct_group(object):
-    gr_name = ...  # type: Optional[str]
-    gr_passwd = ...  # type: Optional[str]
-    gr_gid = ...  # type: int
-    gr_mem = ...  # type: List[str]
-
-def getgrall() -> List[struct_group]: ...
-def getgrgid(id: int) -> struct_group: ...
-def getgrnam(name: str) -> struct_group: ...
diff --git a/typeshed/stdlib/2/gzip.pyi b/typeshed/stdlib/2/gzip.pyi
index 30d9e83..3177bba 100644
--- a/typeshed/stdlib/2/gzip.pyi
+++ b/typeshed/stdlib/2/gzip.pyi
@@ -1,8 +1,4 @@
-# Stubs for gzip (Python 2)
-#
-# NOTE: Based on a dynamically typed stub automatically generated by stubgen.
-
-from typing import Any, IO
+from typing import Any, IO, Text
 import io
 
 class GzipFile(io.BufferedIOBase):
@@ -18,7 +14,7 @@ class GzipFile(io.BufferedIOBase):
     fileobj = ...  # type: Any
     offset = ...  # type: Any
     mtime = ...  # type: Any
-    def __init__(self, filename: str = ..., mode: str = ..., compresslevel: int = ...,
+    def __init__(self, filename: str = ..., mode: Text = ..., compresslevel: int = ...,
                  fileobj: IO[str] = ..., mtime: float = ...) -> None: ...
     @property
     def filename(self): ...
@@ -38,4 +34,4 @@ class GzipFile(io.BufferedIOBase):
     def seek(self, offset, whence=...): ...
     def readline(self, size=...): ...
 
-def open(filename: str, mode: str = ..., compresslevel: int = ...) -> GzipFile: ...
+def open(filename: str, mode: Text = ..., compresslevel: int = ...) -> GzipFile: ...
diff --git a/typeshed/stdlib/2/htmlentitydefs.pyi b/typeshed/stdlib/2/htmlentitydefs.pyi
index c90f3a9..08445e6 100644
--- a/typeshed/stdlib/2/htmlentitydefs.pyi
+++ b/typeshed/stdlib/2/htmlentitydefs.pyi
@@ -1,7 +1,3 @@
-# Stubs for htmlentitydefs (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Mapping
 
 name2codepoint = ...  # type: Mapping[str, int]
diff --git a/typeshed/stdlib/2/inspect.pyi b/typeshed/stdlib/2/inspect.pyi
index a356934..d5bb4d5 100644
--- a/typeshed/stdlib/2/inspect.pyi
+++ b/typeshed/stdlib/2/inspect.pyi
@@ -18,7 +18,7 @@ def ismodule(object: object) -> bool: ...
 def isclass(object: object) -> bool: ...
 def ismethod(object: object) -> bool: ...
 def isfunction(object: object) -> bool: ...
-def isisgeneratorfunction(object: object) -> bool: ...
+def isgeneratorfunction(object: object) -> bool: ...
 def isgenerator(object: object) -> bool: ...
 def istraceback(object: object) -> bool: ...
 def isframe(object: object) -> bool: ...
diff --git a/typeshed/stdlib/2/io.pyi b/typeshed/stdlib/2/io.pyi
index 03cd38e..0c01b2b 100644
--- a/typeshed/stdlib/2/io.pyi
+++ b/typeshed/stdlib/2/io.pyi
@@ -7,98 +7,37 @@
 from typing import List, BinaryIO, TextIO, IO, overload, Iterator, Iterable, Any, Union, Optional
 import _io
 
-DEFAULT_BUFFER_SIZE = 0
-
-def open(file: Union[str, unicode, int],
+from _io import BlockingIOError as BlockingIOError
+from _io import BufferedRWPair as BufferedRWPair
+from _io import BufferedRandom as BufferedRandom
+from _io import BufferedReader as BufferedReader
+from _io import BufferedWriter as BufferedWriter
+from _io import BytesIO as BytesIO
+from _io import DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE
+from _io import FileIO as FileIO
+from _io import IncrementalNewlineDecoder as IncrementalNewlineDecoder
+from _io import StringIO as StringIO
+from _io import TextIOWrapper as TextIOWrapper
+from _io import UnsupportedOperation as UnsupportedOperation
+from _io import open as open
+
+def _OpenWrapper(file: Union[str, unicode, int],
          mode: unicode = ..., buffering: int = ..., encoding: unicode = ...,
          errors: unicode = ..., newline: unicode = ...,
          closefd: bool = ...) -> IO[Any]: ...
 
-class IOBase(_io._IOBase): ...
-
-class BytesIO(BinaryIO):
-    def __init__(self, initial_bytes: str = ...) -> None: ...
-    # TODO getbuffer
-    # TODO see comments in BinaryIO for missing functionality
-    def close(self) -> None: ...
-    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: Optional[int] = ...) -> int: ...
-    def writable(self) -> bool: ...
-    def write(self, s: str) -> int: ...
-    def writelines(self, lines: Iterable[str]) -> None: ...
-    def getvalue(self) -> str: ...
-    def read1(self) -> str: ...
+SEEK_SET = ...  # type: int
+SEEK_CUR = ...  # type: int
+SEEK_END = ...  # type: int
 
-    def __iter__(self) -> Iterator[str]: ...
-    def next(self) -> str: ...
-    def __enter__(self) -> 'BytesIO': ...
-    def __exit__(self, type, value, traceback) -> bool: ...
 
-class StringIO(TextIO):
-    def __init__(self, initial_value: unicode = ...,
-                 newline: unicode = ...) -> None: ...
-    # TODO see comments in BinaryIO for missing functionality
-    name = ...  # type: str
-    def close(self) -> None: ...
-    def closed(self) -> bool: ...
-    def fileno(self) -> int: ...
-    def flush(self) -> None: ...
-    def isatty(self) -> bool: ...
-    def read(self, n: int = ...) -> unicode: ...
-    def readable(self) -> bool: ...
-    def readline(self, limit: int = ...) -> unicode: ...
-    def readlines(self, hint: int = ...) -> List[unicode]: ...
-    def seek(self, offset: int, whence: int = ...) -> int: ...
-    def seekable(self) -> bool: ...
-    def tell(self) -> int: ...
-    def truncate(self, size: Optional[int] = ...) -> int: ...
-    def writable(self) -> bool: ...
-    def write(self, s: unicode) -> int: ...
-    def writelines(self, lines: Iterable[unicode]) -> None: ...
-    def getvalue(self) -> unicode: ...
-
-    def __iter__(self) -> Iterator[unicode]: ...
-    def next(self) -> unicode: ...
-    def __enter__(self) -> 'StringIO': ...
-    def __exit__(self, type, value, traceback) -> bool: ...
+class IOBase(_io._IOBase): ...
 
-class TextIOWrapper(TextIO):
-    # write_through is undocumented but used by subprocess
-    def __init__(self, buffer: IO[str], encoding: unicode = ...,
-                 errors: unicode = ..., newline: unicode = ...,
-                 line_buffering: bool = ...,
-                 write_through: bool = ...) -> None: ...
-    # TODO see comments in BinaryIO for missing functionality
-    def close(self) -> None: ...
-    def closed(self) -> bool: ...
-    def fileno(self) -> int: ...
-    def flush(self) -> None: ...
-    def isatty(self) -> bool: ...
-    def read(self, n: int = ...) -> unicode: ...
-    def readable(self) -> bool: ...
-    def readline(self, limit: int = ...) -> unicode: ...
-    def readlines(self, hint: int = ...) -> List[unicode]: ...
-    def seek(self, offset: int, whence: int = ...) -> int: ...
-    def seekable(self) -> bool: ...
-    def tell(self) -> int: ...
-    def truncate(self, size: Optional[int] = ...) -> int: ...
-    def writable(self) -> bool: ...
-    def write(self, s: unicode) -> int: ...
-    def writelines(self, lines: Iterable[unicode]) -> None: ...
+class RawIOBase(_io._RawIOBase, IOBase):
+    pass
 
-    def __iter__(self) -> Iterator[unicode]: ...
-    def next(self) -> unicode: ...
-    def __enter__(self) -> StringIO: ...
-    def __exit__(self, type, value, traceback) -> bool: ...
+class BufferedIOBase(_io._BufferedIOBase, IOBase):
+    pass
 
-class BufferedIOBase(_io._BufferedIOBase, IOBase): ...
+class TextIOBase(_io._TextIOBase, IOBase):  # type: ignore
+    pass
diff --git a/typeshed/stdlib/2/itertools.pyi b/typeshed/stdlib/2/itertools.pyi
index 644d9f1..9d60526 100644
--- a/typeshed/stdlib/2/itertools.pyi
+++ b/typeshed/stdlib/2/itertools.pyi
@@ -26,9 +26,9 @@ class chain(Iterator[_T], Generic[_T]):
 def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ...
 def dropwhile(predicate: Callable[[_T], Any],
               iterable: Iterable[_T]) -> Iterator[_T]: ...
-def ifilter(predicate: Callable[[_T], Any],
+def ifilter(predicate: Optional[Callable[[_T], Any]],
             iterable: Iterable[_T]) -> Iterator[_T]: ...
-def ifilterfalse(predicate: Callable[[_T], Any],
+def ifilterfalse(predicate: Optional[Callable[[_T], Any]],
                  iterable: Iterable[_T]) -> Iterator[_T]: ...
 
 @overload
@@ -93,9 +93,43 @@ def izip(iter1: Iterable[Any], iter2: Iterable[Any],
 def izip_longest(*p: Iterable[Any],
                  fillvalue: Any = ...) -> Iterator[Any]: ...
 
-# TODO: Return type should be Iterator[Tuple[..]], but unknown tuple shape.
-#       Iterator[Sequence[_T]] loses this type information.
-def product(*p: Iterable[_T], repeat: int = ...) -> Iterator[Sequence[_T]]: ...
+ at overload
+def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3],
+            iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3],
+            iter4: Iterable[_T4],
+            iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3],
+            iter4: Iterable[_T4],
+            iter5: Iterable[_T5],
+            iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ...
+ at overload
+def product(iter1: Iterable[Any],
+            iter2: Iterable[Any],
+            iter3: Iterable[Any],
+            iter4: Iterable[Any],
+            iter5: Iterable[Any],
+            iter6: Iterable[Any],
+            iter7: Iterable[Any], *iterables: Iterable) -> Iterator[Tuple]: ...
+ at overload
+def product(*iter: Iterable[_T], repeat: int) -> Iterator[Tuple[_T, ...]]: ...
 
 def permutations(iterable: Iterable[_T],
                  r: int = ...) -> Iterator[Sequence[_T]]: ...
diff --git a/typeshed/stdlib/2/linecache.pyi b/typeshed/stdlib/2/linecache.pyi
deleted file mode 100644
index 9859788..0000000
--- a/typeshed/stdlib/2/linecache.pyi
+++ /dev/null
@@ -1,7 +0,0 @@
-# Stubs for linecache (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-def getline(filename, lineno, module_globals=None): ...
-def clearcache(): ...
-def checkcache(filename=None): ...
diff --git a/typeshed/stdlib/2/macpath.pyi b/typeshed/stdlib/2/macpath.pyi
index 5e5439f..06a251c 100644
--- a/typeshed/stdlib/2/macpath.pyi
+++ b/typeshed/stdlib/2/macpath.pyi
@@ -1,8 +1,4 @@
-# Stubs for posixpath (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any, AnyStr, List
+from typing import Any
 from genericpath import *  # noqa: F403
 
 curdir = ...  # type: Any
@@ -38,13 +34,3 @@ def realpath(filename): ...
 supports_unicode_filenames = ...  # type: Any
 
 def relpath(path, start=...): ...
-
-# posixpath imports these from genericpath.py:
-def commonprefix(list: List[AnyStr]) -> AnyStr: ...
-def exists(path: unicode) -> bool: ...
-def getatime(path: unicode) -> float: ...
-def getmtime(path: unicode) -> float: ...
-def getctime(path: unicode) -> float: ...
-def getsize(path: unicode) -> int: ...
-def isfile(path: unicode) -> bool: ...
-def isdir(path: unicode) -> bool: ...
diff --git a/typeshed/stdlib/2/mimetools.pyi b/typeshed/stdlib/2/mimetools.pyi
index abae2b5..a265131 100644
--- a/typeshed/stdlib/2/mimetools.pyi
+++ b/typeshed/stdlib/2/mimetools.pyi
@@ -1,7 +1,3 @@
-# Stubs for mimetools (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import rfc822
 
diff --git a/typeshed/stdlib/2/multiprocessing/__init__.pyi b/typeshed/stdlib/2/multiprocessing/__init__.pyi
index c830c8b..556d8cf 100644
--- a/typeshed/stdlib/2/multiprocessing/__init__.pyi
+++ b/typeshed/stdlib/2/multiprocessing/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for multiprocessing (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from multiprocessing.process import Process as Process, current_process as current_process, active_children as active_children
 from multiprocessing.util import SUBDEBUG as SUBDEBUG, SUBWARNING as SUBWARNING
 
diff --git a/typeshed/stdlib/2/multiprocessing/process.pyi b/typeshed/stdlib/2/multiprocessing/process.pyi
index 8d4af5d..c4a84a4 100644
--- a/typeshed/stdlib/2/multiprocessing/process.pyi
+++ b/typeshed/stdlib/2/multiprocessing/process.pyi
@@ -1,7 +1,3 @@
-# Stubs for multiprocessing.process (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def current_process(): ...
diff --git a/typeshed/stdlib/2/multiprocessing/util.pyi b/typeshed/stdlib/2/multiprocessing/util.pyi
index e660fab..7d11627 100644
--- a/typeshed/stdlib/2/multiprocessing/util.pyi
+++ b/typeshed/stdlib/2/multiprocessing/util.pyi
@@ -1,7 +1,3 @@
-# Stubs for multiprocessing.util (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import threading
 
diff --git a/typeshed/stdlib/2/ntpath.pyi b/typeshed/stdlib/2/ntpath.pyi
index 5e5439f..06a251c 100644
--- a/typeshed/stdlib/2/ntpath.pyi
+++ b/typeshed/stdlib/2/ntpath.pyi
@@ -1,8 +1,4 @@
-# Stubs for posixpath (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any, AnyStr, List
+from typing import Any
 from genericpath import *  # noqa: F403
 
 curdir = ...  # type: Any
@@ -38,13 +34,3 @@ def realpath(filename): ...
 supports_unicode_filenames = ...  # type: Any
 
 def relpath(path, start=...): ...
-
-# posixpath imports these from genericpath.py:
-def commonprefix(list: List[AnyStr]) -> AnyStr: ...
-def exists(path: unicode) -> bool: ...
-def getatime(path: unicode) -> float: ...
-def getmtime(path: unicode) -> float: ...
-def getctime(path: unicode) -> float: ...
-def getsize(path: unicode) -> int: ...
-def isfile(path: unicode) -> bool: ...
-def isdir(path: unicode) -> bool: ...
diff --git a/typeshed/stdlib/2/os/__init__.pyi b/typeshed/stdlib/2/os/__init__.pyi
index 881bcf7..8dad31d 100644
--- a/typeshed/stdlib/2/os/__init__.pyi
+++ b/typeshed/stdlib/2/os/__init__.pyi
@@ -1,6 +1,8 @@
-# created from https://docs.python.org/2/library/os.html
+# Stubs for os
+# Ron Murawski <ron at horizonchess.com>
 
 from builtins import OSError as error
+from io import TextIOWrapper as _TextIOWrapper
 import sys
 from typing import (
     Mapping, MutableMapping, Dict, List, Any, Tuple, Iterator, overload, Union, AnyStr,
@@ -11,94 +13,115 @@ from mypy_extensions import NoReturn
 
 _T = TypeVar('_T')
 
-SEEK_SET = 0
-SEEK_CUR = 0
-SEEK_END = 0
-
-# More constants, copied from stdlib/3/os/__init__.pyi
-O_RDONLY = 0
-O_WRONLY = 0
-O_RDWR = 0
-O_APPEND = 0
-O_CREAT = 0
-O_EXCL = 0
-O_TRUNC = 0
-O_DSYNC = 0    # Unix only
-O_RSYNC = 0    # Unix only
-O_SYNC = 0     # Unix only
-O_NDELAY = 0   # Unix only
-O_NONBLOCK = 0  # Unix only
-O_NOCTTY = 0   # Unix only
-O_SHLOCK = 0   # Unix only
-O_EXLOCK = 0   # Unix only
-O_BINARY = 0     # Windows only
-O_NOINHERIT = 0  # Windows only
-O_SHORT_LIVED = 0  # Windows only
-O_TEMPORARY = 0  # Windows only
-O_RANDOM = 0     # Windows only
-O_SEQUENTIAL = 0  # Windows only
-O_TEXT = 0       # Windows only
-O_ASYNC = 0      # Gnu extension if in C library
-O_DIRECT = 0     # Gnu extension if in C library
-O_DIRECTORY = 0  # Gnu extension if in C library
-O_NOFOLLOW = 0   # Gnu extension if in C library
-O_NOATIME = 0    # Gnu extension if in C library
-O_LARGEFILE = 0  # Gnu extension if in C library
-
-curdir = ...  # type: str
-pardir = ...  # type: str
-sep = ...  # type: str
-altsep = ...  # type: str
-extsep = ...  # type: str
-pathsep = ...  # type: str
-defpath = ...  # type: str
-linesep = ...  # type: str
-devnull = ...  # type: str
-name = ...  # type: str
-
-F_OK = 0
-R_OK = 0
-W_OK = 0
-X_OK = 0
+# ----- os variables -----
+
+if sys.version_info >= (3, 2):
+    supports_bytes_environ: bool
+
+if sys.version_info >= (3, 3):
+    supports_dir_fd: Set[Callable[..., Any]]
+    supports_fd: Set[Callable[..., Any]]
+    supports_effective_ids: Set[Callable[..., Any]]
+    supports_follow_symlinks: Set[Callable[..., Any]]
+
+SEEK_SET: int
+SEEK_CUR: int
+SEEK_END: int
+
+O_RDONLY: int
+O_WRONLY: int
+O_RDWR: int
+O_APPEND: int
+O_CREAT: int
+O_EXCL: int
+O_TRUNC: int
+O_DSYNC: int    # Unix only
+O_RSYNC: int    # Unix only
+O_SYNC: int     # Unix only
+O_NDELAY: int   # Unix only
+O_NONBLOCK: int  # Unix only
+O_NOCTTY: int   # Unix only
+O_SHLOCK: int   # Unix only
+O_EXLOCK: int   # Unix only
+O_BINARY: int     # Windows only
+O_NOINHERIT: int  # Windows only
+O_SHORT_LIVED: int  # Windows only
+O_TEMPORARY: int  # Windows only
+O_RANDOM: int     # Windows only
+O_SEQUENTIAL: int  # Windows only
+O_TEXT: int       # Windows only
+O_ASYNC: int      # Gnu extension if in C library
+O_DIRECT: int     # Gnu extension if in C library
+O_DIRECTORY: int  # Gnu extension if in C library
+O_NOFOLLOW: int   # Gnu extension if in C library
+O_NOATIME: int    # Gnu extension if in C library
+O_LARGEFILE: int  # Gnu extension if in C library
+
+curdir: str
+pardir: str
+sep: str
+altsep: str
+extsep: str
+pathsep: str
+defpath: str
+linesep: str
+devnull: str
+name: str
+
+F_OK: int
+R_OK: int
+W_OK: int
+X_OK: int
 
 class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]):
     def copy(self) -> Dict[AnyStr, AnyStr]: ...
 
-environ = ...  # type: _Environ[str]
-
-confstr_names = ...  # type: Dict[str, int]  # Unix only
-pathconf_names = ...  # type: Dict[str, int]  # Unix only
-sysconf_names = ...  # type: Dict[str, int]  # Unix only
-
-EX_OK = 0        # Unix only
-EX_USAGE = 0     # Unix only
-EX_DATAERR = 0   # Unix only
-EX_NOINPUT = 0   # Unix only
-EX_NOUSER = 0    # Unix only
-EX_NOHOST = 0    # Unix only
-EX_UNAVAILABLE = 0  # Unix only
-EX_SOFTWARE = 0  # Unix only
-EX_OSERR = 0     # Unix only
-EX_OSFILE = 0    # Unix only
-EX_CANTCREAT = 0  # Unix only
-EX_IOERR = 0     # Unix only
-EX_TEMPFAIL = 0  # Unix only
-EX_PROTOCOL = 0  # Unix only
-EX_NOPERM = 0    # Unix only
-EX_CONFIG = 0    # Unix only
-P_NOWAIT = 0
-P_NOWAITO = 0
-P_WAIT = 0
-# P_DETACH = 0  # Windows only
-# P_OVERLAY = 0  # Windows only
+environ: _Environ[str]
+if sys.version_info >= (3, 2):
+    environb: _Environ[bytes]
+
+confstr_names: Dict[str, int]  # Unix only
+pathconf_names: Dict[str, int]  # Unix only
+sysconf_names: Dict[str, int]  # Unix only
+
+EX_OK: int        # Unix only
+EX_USAGE: int     # Unix only
+EX_DATAERR: int   # Unix only
+EX_NOINPUT: int   # Unix only
+EX_NOUSER: int    # Unix only
+EX_NOHOST: int    # Unix only
+EX_UNAVAILABLE: int  # Unix only
+EX_SOFTWARE: int  # Unix only
+EX_OSERR: int     # Unix only
+EX_OSFILE: int    # Unix only
+EX_CANTCREAT: int  # Unix only
+EX_IOERR: int     # Unix only
+EX_TEMPFAIL: int  # Unix only
+EX_PROTOCOL: int  # Unix only
+EX_NOPERM: int    # Unix only
+EX_CONFIG: int    # Unix only
+EX_NOTFOUND: int  # Unix only
+
+P_NOWAIT: int
+P_NOWAITO: int
+P_WAIT: int
+if sys.platform == 'win32':
+    P_DETACH: int  # Windows only
+    P_OVERLAY: int  # Windows only
 
 # wait()/waitpid() options
-WNOHANG = 0  # Unix only
-WCONTINUED = 0  # some Unix systems
-WUNTRACED = 0  # Unix only
+WNOHANG: int  # Unix only
+WCONTINUED: int  # some Unix systems
+WUNTRACED: int  # Unix only
+
+TMP_MAX: int  # Undocumented, but used by tempfile
+
+# ----- os classes (structures) -----
+if sys.version_info >= (3, 6):
+    from builtins import _PathLike as PathLike  # See comment in builtins
+
+_PathType = path._PathType
 
-TMP_MAX = 0  # Undocumented, but used by tempfile
-_PathType = Union[bytes, Text]
 _StatVFS = NamedTuple('_StatVFS', [('f_bsize', int), ('f_frsize', int), ('f_blocks', int),
                                    ('f_bfree', int), ('f_bavail', int), ('f_files', int),
                                    ('f_ffree', int), ('f_favail', int), ('f_flag', int),
@@ -201,12 +224,21 @@ def stat_float_times() -> bool: ...
 def statvfs(path: _PathType) -> _StatVFS: ...  # Unix only
 def symlink(source: _PathType, link_name: _PathType) -> None: ...
 def unlink(path: _PathType) -> None: ...
-def utime(path: _PathType, times: Optional[Tuple[float, float]]) -> None: ...
+# TODO: add ns, dir_fd, follow_symlinks argument
+if sys.version_info >= (3, 0):
+    def utime(path: _PathType, times: Optional[Tuple[float, float]] = ...) -> None: ...
+else:
+    def utime(path: _PathType, times: Optional[Tuple[float, float]]) -> None: ...
 
-# TODO onerror: function from OSError to void
-def walk(top: AnyStr, topdown: bool = ..., onerror: Any = ...,
-         followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr],
-                                                    List[AnyStr]]]: ...
+if sys.version_info >= (3, 6):
+    def walk(top: Union[AnyStr, PathLike[AnyStr]], topdown: bool = ...,
+             onerror: Optional[Callable[[OSError], Any]] = ...,
+             followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr],
+                                                        List[AnyStr]]]: ...
+else:
+    def walk(top: AnyStr, topdown: bool = ..., onerror: Optional[Callable[[OSError], Any]] = ...,
+             followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr],
+                                                        List[AnyStr]]]: ...
 
 def abort() -> NoReturn: ...
 # These are defined as execl(file, *args) but the first *arg is mandatory.
@@ -231,11 +263,19 @@ def forkpty() -> Tuple[int, int]: ...  # some flavors of Unix
 def kill(pid: int, sig: int) -> None: ...
 def killpg(pgid: int, sig: int) -> None: ...  # Unix only
 def nice(increment: int) -> int: ...  # Unix only
-# TODO: plock, popen*, P_*
-def popen(command: str, *args, **kwargs) -> Optional[IO[Any]]: ...
-def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ...
-def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ...
-def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ...
+def plock(op: int) -> None: ...  # Unix only ???op is int?
+
+if sys.version_info >= (3, 0):
+    class popen(_TextIOWrapper):
+        # TODO 'b' modes or bytes command not accepted?
+        def __init__(self, command: str, mode: str = ...,
+                     bufsize: int = ...) -> None: ...
+        def close(self) -> Any: ...  # may return int
+else:
+    def popen(command: str, *args, **kwargs) -> Optional[IO[Any]]: ...
+    def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ...
+    def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ...
+    def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ...
 
 def spawnl(mode: int, path: _PathType, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ...
 def spawnle(mode: int, path: _PathType, arg0: Union[bytes, Text],
@@ -271,10 +311,34 @@ def getloadavg() -> Tuple[float, float, float]: ...  # Unix only
 def sysconf(name: Union[str, int]) -> int: ...  # Unix only
 def urandom(n: int) -> bytes: ...
 
-def tmpfile() -> IO[Any]: ...
-def tmpnam() -> str: ...
-def tempnam(dir: str = ..., prefix: str = ...) -> str: ...
+if sys.version_info >= (3, 0):
+    def sched_getaffinity(id: int) -> Set[int]: ...
+if sys.version_info >= (3, 3):
+    class waitresult:
+        si_pid: int
+    def waitid(idtype: int, id: int, options: int) -> waitresult: ...
+
+if sys.version_info < (3, 0):
+    def tmpfile() -> IO[Any]: ...
+    def tmpnam() -> str: ...
+    def tempnam(dir: str = ..., prefix: str = ...) -> str: ...
+
+P_ALL: int
+WEXITED: int
+WNOWAIT: int
+
+if sys.version_info >= (3, 3):
+    def sync() -> None: ...  # Unix only
+
+    def truncate(path: Union[_PathType, int], length: int) -> None: ...  # Unix only up to version 3.4
+
+    def fwalk(top: AnyStr = ..., topdown: bool = ...,
+              onerror: Callable = ..., *, follow_symlinks: bool = ...,
+              dir_fd: int = ...) -> Iterator[Tuple[AnyStr, List[AnyStr],
+                                             List[AnyStr], int]]: ...  # Unix only
+
+    terminal_size = NamedTuple('terminal_size', [('columns', int), ('lines', int)])
+    def get_terminal_size(fd: int = ...) -> terminal_size: ...
 
-P_ALL = 0
-WEXITED = 0
-WNOWAIT = 0
+if sys.version_info >= (3, 4):
+    def cpu_count() -> Optional[int]: ...
diff --git a/typeshed/stdlib/2/os/path.pyi b/typeshed/stdlib/2/os/path.pyi
index 7488956..961c7a8 100644
--- a/typeshed/stdlib/2/os/path.pyi
+++ b/typeshed/stdlib/2/os/path.pyi
@@ -10,7 +10,12 @@ from typing import (
 )
 
 _T = TypeVar('_T')
-_PathType = Union[bytes, Text]
+
+if sys.version_info >= (3, 6):
+    from builtins import _PathLike
+    _PathType = Union[bytes, Text, _PathLike]
+else:
+    _PathType = Union[bytes, Text]
 
 # ----- os.path variables -----
 supports_unicode_filenames = False
@@ -55,12 +60,31 @@ def isdir(path: _PathType) -> bool: ...
 def islink(path: _PathType) -> bool: ...
 def ismount(path: _PathType) -> bool: ...
 
-def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ...
+if sys.version_info < (3, 0):
+    # Make sure signatures are disjunct, and allow combinations of bytes and unicode.
+    # (Since Python 2 allows that, too)
+    # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in
+    # a type error.
+    @overload
+    def join(__p1: bytes, *p: bytes) -> bytes: ...
+    @overload
+    def join(__p1: Text, *p: _PathType) -> Text: ...
+    @overload
+    def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ...
+    @overload
+    def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ...
+    @overload
+    def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ...
+else:
+    def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ...
 
 def normcase(path: AnyStr) -> AnyStr: ...
 def normpath(path: AnyStr) -> AnyStr: ...
-def realpath(path: AnyStr) -> AnyStr: ...
-def relpath(path: AnyStr, start: AnyStr = ...) -> AnyStr: ...
+if sys.platform == 'win32':
+    def realpath(path: AnyStr) -> AnyStr: ...
+else:
+    def realpath(filename: AnyStr) -> AnyStr: ...
+def relpath(path: AnyStr, start: _PathType = ...) -> AnyStr: ...
 
 def samefile(path1: _PathType, path2: _PathType) -> bool: ...
 def sameopenfile(fp1: int, fp2: int) -> bool: ...
diff --git a/typeshed/stdlib/2/os2emxpath.pyi b/typeshed/stdlib/2/os2emxpath.pyi
index 5e5439f..06a251c 100644
--- a/typeshed/stdlib/2/os2emxpath.pyi
+++ b/typeshed/stdlib/2/os2emxpath.pyi
@@ -1,8 +1,4 @@
-# Stubs for posixpath (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any, AnyStr, List
+from typing import Any
 from genericpath import *  # noqa: F403
 
 curdir = ...  # type: Any
@@ -38,13 +34,3 @@ def realpath(filename): ...
 supports_unicode_filenames = ...  # type: Any
 
 def relpath(path, start=...): ...
-
-# posixpath imports these from genericpath.py:
-def commonprefix(list: List[AnyStr]) -> AnyStr: ...
-def exists(path: unicode) -> bool: ...
-def getatime(path: unicode) -> float: ...
-def getmtime(path: unicode) -> float: ...
-def getctime(path: unicode) -> float: ...
-def getsize(path: unicode) -> int: ...
-def isfile(path: unicode) -> bool: ...
-def isdir(path: unicode) -> bool: ...
diff --git a/typeshed/stdlib/2/pdb.pyi b/typeshed/stdlib/2/pdb.pyi
deleted file mode 100644
index 1c375fe..0000000
--- a/typeshed/stdlib/2/pdb.pyi
+++ /dev/null
@@ -1,30 +0,0 @@
-# Stub for pdb (incomplete, only some global functions)
-
-from typing import Any, Dict
-
-def run(statement: str,
-        globals: Dict[str, Any] = None,
-        locals: Dict[str, Any] = None) -> None:
-    ...
-
-def runeval(expression: str,
-            globals: Dict[str, Any] = None,
-            locals: Dict[str, Any] = None) -> Any:
-    ...
-
-def runctx(statement: str,
-        globals: Dict[str, Any],
-        locals: Dict[str, Any]) -> None:
-    ...
-
-def runcall(*args: Any, **kwds: Any) -> Any:
-    ...
-
-def set_trace() -> None:
-    ...
-
-def post_mortem(t: Any = None) -> None:
-    ...
-
-def pm() -> None:
-    ...
diff --git a/typeshed/stdlib/2/pickle.pyi b/typeshed/stdlib/2/pickle.pyi
deleted file mode 100644
index ed7af58..0000000
--- a/typeshed/stdlib/2/pickle.pyi
+++ /dev/null
@@ -1,38 +0,0 @@
-# Stubs for pickle (Python 2)
-
-from typing import Any, IO
-
-
-HIGHEST_PROTOCOL = ...  # type: int
-
-
-def dump(obj: Any, file: IO[bytes], protocol: int = None) -> None: ...
-def dumps(obj: Any, protocol: int = ...) -> bytes: ...
-def load(file: IO[bytes]) -> Any: ...
-def loads(string: bytes) -> Any: ...
-
-
-class PickleError(Exception):
-    pass
-
-
-class PicklingError(PickleError):
-    pass
-
-
-class UnpicklingError(PickleError):
-    pass
-
-
-class Pickler:
-    def __init__(self, file: IO[bytes], protocol: int = None) -> None: ...
-
-    def dump(self, obj: Any) -> None: ...
-
-    def clear_memo(self) -> None: ...
-
-
-class Unpickler:
-    def __init__(self, file: IO[bytes]) -> None: ...
-
-    def load(self) -> Any: ...
diff --git a/typeshed/stdlib/2/popen2.pyi b/typeshed/stdlib/2/popen2.pyi
new file mode 100644
index 0000000..3d050b4
--- /dev/null
+++ b/typeshed/stdlib/2/popen2.pyi
@@ -0,0 +1,29 @@
+from typing import Any, Iterable, List, Optional, Union, TextIO, Tuple, TypeVar
+
+_T = TypeVar('_T')
+
+__all__ = ...  # type: List[str]
+
+class Popen3:
+    sts = ...  # type: int
+    cmd = ...  # type: Iterable
+    pid = ...  # type: int
+    tochild = ...  # type: TextIO
+    fromchild = ...  # type: TextIO
+    childerr = ...  # type: Optional[TextIO]
+    def __init__(self, cmd: Iterable = ..., capturestderr: bool = ..., bufsize: int = ...) -> None: ...
+    def __del__(self) -> None: ...
+    def poll(self, _deadstate: _T = ...) -> Union[int, _T]: ...
+    def wait(self) -> int: ...
+
+class Popen4(Popen3):
+    childerr = ...  # type: None
+    cmd = ...  # type: Iterable
+    pid = ...  # type: int
+    tochild = ...  # type: TextIO
+    fromchild = ...  # type: TextIO
+    def __init__(self, cmd: Iterable = ..., bufsize: int = ...) -> None: ...
+
+def popen2(cmd: Iterable = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ...
+def popen3(cmd: Iterable = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ...
+def popen4(cmd: Iterable = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ...
diff --git a/typeshed/stdlib/2/posixpath.pyi b/typeshed/stdlib/2/posixpath.pyi
index 5e5439f..06a251c 100644
--- a/typeshed/stdlib/2/posixpath.pyi
+++ b/typeshed/stdlib/2/posixpath.pyi
@@ -1,8 +1,4 @@
-# Stubs for posixpath (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any, AnyStr, List
+from typing import Any
 from genericpath import *  # noqa: F403
 
 curdir = ...  # type: Any
@@ -38,13 +34,3 @@ def realpath(filename): ...
 supports_unicode_filenames = ...  # type: Any
 
 def relpath(path, start=...): ...
-
-# posixpath imports these from genericpath.py:
-def commonprefix(list: List[AnyStr]) -> AnyStr: ...
-def exists(path: unicode) -> bool: ...
-def getatime(path: unicode) -> float: ...
-def getmtime(path: unicode) -> float: ...
-def getctime(path: unicode) -> float: ...
-def getsize(path: unicode) -> int: ...
-def isfile(path: unicode) -> bool: ...
-def isdir(path: unicode) -> bool: ...
diff --git a/typeshed/stdlib/2/pwd.pyi b/typeshed/stdlib/2/pwd.pyi
deleted file mode 100644
index ff6c6a4..0000000
--- a/typeshed/stdlib/2/pwd.pyi
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import List
-
-class struct_passwd(tuple):
-    n_fields = ...  # type: int
-    n_sequence_fields = ...  # type: int
-    n_unnamed_fields = ...  # type: int
-    pw_dir = ...  # type: str
-    pw_name = ...  # type: str
-    pw_passwd = ...  # type: str
-    pw_shell = ...  # type: str
-    pw_gecos = ...  # type: str
-    pw_gid = ...  # type: int
-    pw_uid = ...  # type: int
-
-def getpwall() -> List[struct_passwd]: ...
-def getpwnam(name: str) -> struct_passwd: ...
-def getpwuid(uid: int) -> struct_passwd: ...
diff --git a/typeshed/stdlib/2/pydoc.pyi b/typeshed/stdlib/2/pydoc.pyi
index 453d2d7..bde952a 100644
--- a/typeshed/stdlib/2/pydoc.pyi
+++ b/typeshed/stdlib/2/pydoc.pyi
@@ -1,7 +1,3 @@
-# Stubs for pydoc (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, AnyStr, Callable, Container, Dict, IO, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
 from mypy_extensions import NoReturn
 from repr import Repr
diff --git a/typeshed/stdlib/2/re.pyi b/typeshed/stdlib/2/re.pyi
index 8df3a44..110e194 100644
--- a/typeshed/stdlib/2/re.pyi
+++ b/typeshed/stdlib/2/re.pyi
@@ -97,3 +97,4 @@ def subn(pattern: Union[Pattern[str], Pattern[unicode]], repl: Callable[[Match[A
 def escape(string: AnyStr) -> AnyStr: ...
 
 def purge() -> None: ...
+def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: int = ...) -> Pattern[AnyStr]: ...
diff --git a/typeshed/stdlib/2/runpy.pyi b/typeshed/stdlib/2/runpy.pyi
index 0d24e7e..193a320 100644
--- a/typeshed/stdlib/2/runpy.pyi
+++ b/typeshed/stdlib/2/runpy.pyi
@@ -1,7 +1,3 @@
-# Stubs for runpy (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class _TempModule:
diff --git a/typeshed/stdlib/2/select.pyi b/typeshed/stdlib/2/select.pyi
deleted file mode 100644
index a88311e..0000000
--- a/typeshed/stdlib/2/select.pyi
+++ /dev/null
@@ -1,100 +0,0 @@
-"""Stubs for the 'select' module."""
-
-from typing import Any, Optional, Tuple, Iterable, List
-
-EPOLLERR = ...  # type: int
-EPOLLET = ...  # type: int
-EPOLLHUP = ...  # type: int
-EPOLLIN = ...  # type: int
-EPOLLMSG = ...  # type: int
-EPOLLONESHOT = ...  # type: int
-EPOLLOUT = ...  # type: int
-EPOLLPRI = ...  # type: int
-EPOLLRDBAND = ...  # type: int
-EPOLLRDNORM = ...  # type: int
-EPOLLWRBAND = ...  # type: int
-EPOLLWRNORM = ...  # type: int
-EPOLL_RDHUP = ...  # type: int
-KQ_EV_ADD = ...  # type: int
-KQ_EV_CLEAR = ...  # type: int
-KQ_EV_DELETE = ...  # type: int
-KQ_EV_DISABLE = ...  # type: int
-KQ_EV_ENABLE = ...  # type: int
-KQ_EV_EOF = ...  # type: int
-KQ_EV_ERROR = ...  # type: int
-KQ_EV_FLAG1 = ...  # type: int
-KQ_EV_ONESHOT = ...  # type: int
-KQ_EV_SYSFLAGS = ...  # type: int
-KQ_FILTER_AIO = ...  # type: int
-KQ_FILTER_NETDEV = ...  # type: int
-KQ_FILTER_PROC = ...  # type: int
-KQ_FILTER_READ = ...  # type: int
-KQ_FILTER_SIGNAL = ...  # type: int
-KQ_FILTER_TIMER = ...  # type: int
-KQ_FILTER_VNODE = ...  # type: int
-KQ_FILTER_WRITE = ...  # type: int
-KQ_NOTE_ATTRIB = ...  # type: int
-KQ_NOTE_CHILD = ...  # type: int
-KQ_NOTE_DELETE = ...  # type: int
-KQ_NOTE_EXEC = ...  # type: int
-KQ_NOTE_EXIT = ...  # type: int
-KQ_NOTE_EXTEND = ...  # type: int
-KQ_NOTE_FORK = ...  # type: int
-KQ_NOTE_LINK = ...  # type: int
-KQ_NOTE_LINKDOWN = ...  # type: int
-KQ_NOTE_LINKINV = ...  # type: int
-KQ_NOTE_LINKUP = ...  # type: int
-KQ_NOTE_LOWAT = ...  # type: int
-KQ_NOTE_PCTRLMASK = ...  # type: int
-KQ_NOTE_PDATAMASK = ...  # type: int
-KQ_NOTE_RENAME = ...  # type: int
-KQ_NOTE_REVOKE = ...  # type: int
-KQ_NOTE_TRACK = ...  # type: int
-KQ_NOTE_TRACKERR = ...  # type: int
-KQ_NOTE_WRITE = ...  # type: int
-PIPE_BUF = ...  # type: int
-POLLERR = ...  # type: int
-POLLHUP = ...  # type: int
-POLLIN = ...  # type: int
-POLLMSG = ...  # type: int
-POLLNVAL = ...  # type: int
-POLLOUT = ...  # type: int
-POLLPRI = ...  # type: int
-POLLRDBAND = ...  # type: int
-POLLRDNORM = ...  # type: int
-POLLWRBAND = ...  # type: int
-POLLWRNORM = ...  # type: int
-
-def poll() -> epoll: ...
-def select(rlist, wlist, xlist, timeout: float = None) -> Tuple[List, List, List]: ...
-
-class error(Exception): ...
-
-class kevent(object):
-    data = ...  # type: Any
-    fflags = ...  # type: int
-    filter = ...  # type: int
-    flags = ...  # type: int
-    ident = ...  # type: Any
-    udata = ...  # type: Any
-    def __init__(self, *args, **kwargs) -> None: ...
-
-class kqueue(object):
-    closed = ...  # type: bool
-    def __init__(self) -> None: ...
-    def close(self) -> None: ...
-    def control(self, changelist: Optional[Iterable[kevent]], max_events: int, timeout: int = ...) -> List[kevent]: ...
-    def fileno(self) -> int: ...
-    @classmethod
-    def fromfd(cls, fd: int) -> kqueue: ...
-
-class epoll(object):
-    def __init__(self, sizehint: int = ...) -> None: ...
-    def close(self) -> None: ...
-    def fileno(self) -> int: ...
-    def register(self, fd: int, eventmask: int = ...) -> None: ...
-    def modify(self, fd: int, eventmask: int) -> None: ...
-    def unregister(self, fd: int) -> None: ...
-    def poll(self, timeout: float = ..., maxevents: int = ...) -> Any: ...
-    @classmethod
-    def fromfd(cls, fd: int) -> epoll: ...
diff --git a/typeshed/stdlib/2/shutil.pyi b/typeshed/stdlib/2/shutil.pyi
index c39f257..94d0952 100644
--- a/typeshed/stdlib/2/shutil.pyi
+++ b/typeshed/stdlib/2/shutil.pyi
@@ -1,7 +1,3 @@
-# Stubs for shutil (Python 2)
-#
-# NOTE: Based on a dynamically typed stub automatically generated by stubgen.
-
 from typing import List, Iterable, Callable, IO, AnyStr, Any, Optional, Tuple, Sequence
 
 class Error(EnvironmentError): ...
diff --git a/typeshed/stdlib/2/smtplib.pyi b/typeshed/stdlib/2/smtplib.pyi
index cb5f893..76bdcb4 100644
--- a/typeshed/stdlib/2/smtplib.pyi
+++ b/typeshed/stdlib/2/smtplib.pyi
@@ -1,7 +1,3 @@
-# Stubs for smtplib (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class SMTPException(Exception): ...
diff --git a/typeshed/stdlib/2/spwd.pyi b/typeshed/stdlib/2/spwd.pyi
new file mode 100644
index 0000000..1d58990
--- /dev/null
+++ b/typeshed/stdlib/2/spwd.pyi
@@ -0,0 +1,14 @@
+from typing import List, NamedTuple
+
+struct_spwd = NamedTuple("struct_spwd", [("sp_nam", str),
+                                         ("sp_pwd", str),
+                                         ("sp_lstchg", int),
+                                         ("sp_min", int),
+                                         ("sp_max", int),
+                                         ("sp_warn", int),
+                                         ("sp_inact", int),
+                                         ("sp_expire", int),
+                                         ("sp_flag", int)])
+
+def getspall() -> List[struct_spwd]: ...
+def getspnam(name: str) -> struct_spwd: ...
diff --git a/typeshed/stdlib/2/sqlite3/__init__.pyi b/typeshed/stdlib/2/sqlite3/__init__.pyi
index fc22e5d..d5d20d6 100644
--- a/typeshed/stdlib/2/sqlite3/__init__.pyi
+++ b/typeshed/stdlib/2/sqlite3/__init__.pyi
@@ -1,5 +1 @@
-# Stubs for sqlite3 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from sqlite3.dbapi2 import *  # noqa: F403
diff --git a/typeshed/stdlib/2/sqlite3/dbapi2.pyi b/typeshed/stdlib/2/sqlite3/dbapi2.pyi
index bd44433..8d55e04 100644
--- a/typeshed/stdlib/2/sqlite3/dbapi2.pyi
+++ b/typeshed/stdlib/2/sqlite3/dbapi2.pyi
@@ -1,8 +1,7 @@
 # Filip Hron <filip.hron at gmail.com>
 # based heavily on Andrey Vlasovskikh's python-skeletons https://github.com/JetBrains/python-skeletons/blob/master/sqlite3.py
 
-from typing import Any, Union, List, Iterator
-from numbers import Integral
+from typing import Any, Union, List, Iterator, Optional
 from datetime import time, datetime
 from collections import Iterable
 
@@ -141,7 +140,7 @@ class Cursor(Iterator[Any]):
     def executemany(self, sql: str, seq_of_parameters: Iterable[Iterable]): ...
     def executescript(self, sql_script: Union[bytes, unicode]) -> Cursor: ...
     def fetchall(self) -> List[Any]: ...
-    def fetchmany(self, size: Integral = ...) -> List[Any]: ...
+    def fetchmany(self, size: Optional[int] = ...) -> List[Any]: ...
     def fetchone(self) -> Any: ...
     def setinputsizes(self, *args, **kwargs): ...
     def setoutputsize(self, *args, **kwargs): ...
diff --git a/typeshed/stdlib/2/subprocess.pyi b/typeshed/stdlib/2/subprocess.pyi
index 06934c6..047b6bd 100644
--- a/typeshed/stdlib/2/subprocess.pyi
+++ b/typeshed/stdlib/2/subprocess.pyi
@@ -4,7 +4,7 @@
 
 from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text
 
-_FILE = Union[int, IO[Any]]
+_FILE = Union[None, int, IO[Any]]
 _TXT = Union[bytes, Text]
 _CMD = Union[_TXT, Sequence[_TXT]]
 _ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]
diff --git a/typeshed/stdlib/2/sys.pyi b/typeshed/stdlib/2/sys.pyi
index cb9172a..2eaeea7 100644
--- a/typeshed/stdlib/2/sys.pyi
+++ b/typeshed/stdlib/2/sys.pyi
@@ -61,7 +61,7 @@ long_info = ...  # type: object
 maxint = ...  # type: int
 maxsize = ...  # type: int
 maxunicode = ...  # type: int
-modules = ...  # type: Dict[str, ModuleType]
+modules = ...  # type: Dict[str, Any]
 path = ...  # type: List[str]
 platform = ...  # type: str
 prefix = ...  # type: str
@@ -124,7 +124,7 @@ def exit(arg: Any = ...) -> NoReturn:
 def getcheckinterval() -> int: ...  # deprecated
 def getdefaultencoding() -> str: ...
 def getdlopenflags() -> int: ...
-def getfilesystemencoding() -> Union[str, None]: ...
+def getfilesystemencoding() -> str: ...  # In practice, never returns None
 def getrefcount(arg: Any) -> int: ...
 def getrecursionlimit() -> int: ...
 def getsizeof(obj: object, default: int = ...) -> int: ...
diff --git a/typeshed/stdlib/2/textwrap.pyi b/typeshed/stdlib/2/textwrap.pyi
index 7d1a6d3..df8afa6 100644
--- a/typeshed/stdlib/2/textwrap.pyi
+++ b/typeshed/stdlib/2/textwrap.pyi
@@ -1,8 +1,4 @@
-# Stubs for textwrap (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
+from typing import Any, AnyStr
 
 class _unicode: ...
 
@@ -30,4 +26,4 @@ class TextWrapper:
 
 def wrap(text, width=..., **kwargs): ...
 def fill(text, width=..., **kwargs): ...
-def dedent(text): ...
+def dedent(text: AnyStr) -> AnyStr: ...
diff --git a/typeshed/stdlib/2/time.pyi b/typeshed/stdlib/2/time.pyi
index 6d2499f..e75d8e0 100644
--- a/typeshed/stdlib/2/time.pyi
+++ b/typeshed/stdlib/2/time.pyi
@@ -17,6 +17,9 @@ class struct_time(NamedTuple('_struct_time',
     def __init__(self, o: Tuple[int, int, int,
                                 int, int, int,
                                 int, int, int], _arg: Any = ...) -> None: ...
+    def __new__(cls, o: Tuple[int, int, int,
+                              int, int, int,
+                              int, int, int], _arg: Any = ...) -> struct_time: ...
 
 _TIME_TUPLE = Tuple[int, int, int, int, int, int, int, int, int]
 
@@ -32,7 +35,7 @@ def gmtime(secs: Optional[float] = ...) -> struct_time: ...
 
 def localtime(secs: Optional[float] = ...) -> struct_time: ...
 
-def mktime(t: struct_time) -> float:
+def mktime(t: Union[struct_time, _TIME_TUPLE]) -> float:
     raise OverflowError()
     raise ValueError()
 
diff --git a/typeshed/stdlib/2/toaiff.pyi b/typeshed/stdlib/2/toaiff.pyi
new file mode 100644
index 0000000..77334c7
--- /dev/null
+++ b/typeshed/stdlib/2/toaiff.pyi
@@ -0,0 +1,16 @@
+# Stubs for toaiff (Python 2)
+
+# Source: https://hg.python.org/cpython/file/2.7/Lib/toaiff.py
+from pipes import Template
+from typing import Dict, List
+
+
+__all__: List[str]
+table: Dict[str, Template]
+t: Template
+uncompress: Template
+
+class error(Exception): ...
+
+def toaiff(filename: str) -> str: ...
+def _toaiff(filename: str, temps: List[str]) -> str: ...
diff --git a/typeshed/stdlib/2/types.pyi b/typeshed/stdlib/2/types.pyi
index 2896d1a..e4df50d 100644
--- a/typeshed/stdlib/2/types.pyi
+++ b/typeshed/stdlib/2/types.pyi
@@ -82,6 +82,7 @@ class UnboundMethodType:
     im_class = ...  # type: type
     im_func = ...  # type: FunctionType
     im_self = ...  # type: Optional[object]
+    __name__ = ...  # type: str
     __func__ = im_func
     __self__ = im_self
     def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
diff --git a/typeshed/stdlib/2/typing.pyi b/typeshed/stdlib/2/typing.pyi
index dc807a0..84cd0d4 100644
--- a/typeshed/stdlib/2/typing.pyi
+++ b/typeshed/stdlib/2/typing.pyi
@@ -1,7 +1,8 @@
 # Stubs for typing (Python 2.7)
 
 from abc import abstractmethod, ABCMeta
-from types import CodeType, FrameType
+from types import CodeType, FrameType, TracebackType
+import collections  # Needed by aliases like DefaultDict, see mypy issue 2986
 
 # Definitions of special type checking related constructs.  Their definitions
 # are not used, so their value does not matter.
@@ -9,13 +10,17 @@ from types import CodeType, FrameType
 overload = object()
 Any = object()
 TypeVar = object()
-Generic = object()
-Tuple = object()
-Callable = object()
-Type = object()
 _promote = object()
 no_type_check = object()
-ClassVar = object()
+
+class _SpecialForm(object):
+    def __getitem__(self, typeargs: Any) -> object: ...
+
+Tuple: _SpecialForm = ...
+Generic: _SpecialForm = ...
+Callable: _SpecialForm = ...
+Type: _SpecialForm = ...
+ClassVar: _SpecialForm = ...
 
 class GenericMeta(type): ...
 
@@ -199,6 +204,12 @@ class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]):
     def __contains__(self, o: object) -> bool: ...
     def __iter__(self) -> Iterator[_VT_co]: ...
 
+class ContextManager(Generic[_T_co]):
+    def __enter__(self) -> _T_co: ...
+    def __exit__(self, exc_type: Optional[Type[BaseException]],
+                 exc_value: Optional[BaseException],
+                 traceback: Optional[TracebackType]) -> Optional[bool]: ...
+
 class Mapping(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT_co]):
     # TODO: We wish the key type could also be covariant, but that doesn't work,
     # see discussion in https: //github.com/python/typing/pull/273.
@@ -206,9 +217,9 @@ class Mapping(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT_co]):
     def __getitem__(self, k: _KT) -> _VT_co:
         ...
     # Mixin methods
-    @overload  # type: ignore
+    @overload
     def get(self, k: _KT) -> Optional[_VT_co]: ...
-    @overload  # type: ignore
+    @overload
     def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ...
     def keys(self) -> list[_KT]: ...
     def values(self) -> list[_VT_co]: ...
@@ -232,9 +243,11 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]):
     def popitem(self) -> Tuple[_KT, _VT]: ...
     def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ...
     @overload
-    def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    @overload
+    def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
     @overload
-    def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
+    def update(self, **kwargs: _VT) -> None: ...
 
 Text = unicode
 
@@ -379,7 +392,8 @@ class Pattern(Generic[AnyStr]):
 
 # Functions
 
-def get_type_hints(obj: Callable) -> dict[str, Any]: ...
+def get_type_hints(obj: Callable, globalns: Optional[dict[Text, Any]] = ...,
+                   localns: Optional[dict[Text, Any]] = ...) -> None: ...
 
 def cast(tp: Type[_T], obj: Any) -> _T: ...
 
@@ -389,8 +403,8 @@ def cast(tp: Type[_T], obj: Any) -> _T: ...
 class NamedTuple(tuple):
     _fields = ...  # type: Tuple[str, ...]
 
-    def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]], *,
-                 verbose: bool = ..., rename: bool = ...) -> None: ...
+    def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]] = ..., *,
+                 verbose: bool = ..., rename: bool = ..., **kwargs: Any) -> None: ...
 
     @classmethod
     def _make(cls, iterable: Iterable[Any]) -> NamedTuple: ...
diff --git a/typeshed/stdlib/2/unittest.pyi b/typeshed/stdlib/2/unittest.pyi
index 52decfe..1a7a069 100644
--- a/typeshed/stdlib/2/unittest.pyi
+++ b/typeshed/stdlib/2/unittest.pyi
@@ -4,10 +4,9 @@
 
 # Only a subset of functionality is included.
 
-from typing import (
-    Any, Callable, Dict, Iterable, Tuple, List, TextIO, Sequence,
-    overload, Set, FrozenSet, TypeVar, Union, Pattern, Type
-)
+from typing import (Any, Callable, Dict, FrozenSet, Iterable, List, Optional,
+                    overload, Pattern, Sequence, Set, TextIO, Tuple, Type,
+                    TypeVar, Union)
 from abc import abstractmethod, ABCMeta
 import types
 
@@ -153,11 +152,26 @@ class TestSuite(Testable):
     def debug(self) -> None: ...
     def countTestCases(self) -> int: ...
 
-# TODO TestLoader
-# TODO defaultTestLoader
+class TestLoader:
+    testMethodPrefix = ...  # type: str
+    sortTestMethodsUsing = ...  # type: Optional[Callable[[str, str], int]]
+    suiteClass = ...  # type: Callable[[List[TestCase]], TestSuite]
+    def loadTestsFromTestCase(self,
+                              testCaseClass: Type[TestCase]) -> TestSuite: ...
+    def loadTestsFromModule(self, module: str = ...,
+                            use_load_tests: bool = ...) -> TestSuite: ...
+    def loadTestsFromName(self, name: str = ...,
+                          module: Optional[str] = ...) -> TestSuite: ...
+    def loadTestsFromNames(self, names: List[str] = ...,
+                          module: Optional[str] = ...) -> TestSuite: ...
+    def discover(self, start_dir: str, pattern: str = ...,
+                 top_level_dir: Optional[str] = ...) -> TestSuite: ...
+    def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ...
+
+defaultTestLoader = TestLoader
 
 class TextTestRunner:
-    def __init__(self, stream: TextIO = ..., descriptions: bool = ...,
+    def __init__(self, stream: Optional[TextIO] = ..., descriptions: bool = ...,
                  verbosity: int = ..., failfast: bool = ...) -> None: ...
 
 class SkipTest(Exception):
@@ -169,9 +183,16 @@ def skipIf(condition: Any, reason: Union[str, unicode]) -> Any: ...
 def expectedFailure(func: _FT) -> _FT: ...
 def skip(reason: Union[str, unicode]) -> Any: ...
 
-def main(module: str = ..., defaultTest: str = ...,
-         argv: List[str] = ..., testRunner: Any = ...,
-         testLoader: Any = ...) -> None: ...  # TODO types
+# not really documented
+class TestProgram:
+    result = ...  # type: TestResult
+
+def main(module: str = ..., defaultTest: Optional[str] = ...,
+         argv: Optional[Sequence[str]] = ...,
+         testRunner: Union[Type[TextTestRunner], TextTestRunner, None] = ...,
+         testLoader: TestLoader = ..., exit: bool = ..., verbosity: int = ...,
+         failfast: Optional[bool] = ..., catchbreak: Optional[bool] = ...,
+         buffer: Optional[bool] = ...) -> TestProgram: ...
 
 # private but occasionally used
 util = ...  # type: types.ModuleType
diff --git a/typeshed/stdlib/2/urllib.pyi b/typeshed/stdlib/2/urllib.pyi
index 0882926..5f47c18 100644
--- a/typeshed/stdlib/2/urllib.pyi
+++ b/typeshed/stdlib/2/urllib.pyi
@@ -1,6 +1,3 @@
-# Stubs for urllib (Python 2)
-# NOTE: This dynamically typed stub was originally automatically generated by stubgen.
-
 from typing import Any, Mapping, Union, Tuple, Sequence, IO
 
 def url2pathname(pathname: str) -> str: ...
diff --git a/typeshed/stdlib/2/urllib2.pyi b/typeshed/stdlib/2/urllib2.pyi
index 6c1d30c..cfa399e 100644
--- a/typeshed/stdlib/2/urllib2.pyi
+++ b/typeshed/stdlib/2/urllib2.pyi
@@ -41,7 +41,7 @@ class Request(object):
     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: ...
-    def get_header(self, header_name: str, default: str = None) -> str: ...
+    def get_header(self, header_name: str, default: Optional[str] = None) -> str: ...
     def header_items(self): ...
 
 class OpenerDirector(object):
diff --git a/typeshed/stdlib/2/urlparse.pyi b/typeshed/stdlib/2/urlparse.pyi
index 9d0a702..169de2f 100644
--- a/typeshed/stdlib/2/urlparse.pyi
+++ b/typeshed/stdlib/2/urlparse.pyi
@@ -1,6 +1,8 @@
 # Stubs for urlparse (Python 2)
 
-from typing import Dict, List, NamedTuple, Tuple, Sequence, Union, overload
+from typing import AnyStr, Dict, List, NamedTuple, Tuple, Sequence, Union, overload
+
+_String = Union[str, unicode]
 
 uses_relative = ...  # type: List[str]
 uses_netloc = ...  # type: List[str]
@@ -46,23 +48,23 @@ class ParseResult(
 ):
     def geturl(self) -> str: ...
 
-def urlparse(url: Union[str, unicode], scheme: str = ...,
+def urlparse(url: _String, scheme: _String = ...,
              allow_fragments: bool = ...) -> ParseResult: ...
-def urlsplit(url: Union[str, unicode], scheme: str = ...,
+def urlsplit(url: _String, scheme: _String = ...,
              allow_fragments: bool = ...) -> SplitResult: ...
 @overload
-def urlunparse(data: Tuple[str, str, str, str, str, str]) -> str: ...
+def urlunparse(data: Tuple[_String, _String, _String, _String, _String, _String]) -> str: ...
 @overload
-def urlunparse(data: Sequence[str]) -> str: ...
+def urlunparse(data: Sequence[_String]) -> str: ...
 @overload
-def urlunsplit(data: Tuple[str, str, str, str, str]) -> str: ...
+def urlunsplit(data: Tuple[_String, _String, _String, _String, _String]) -> str: ...
 @overload
-def urlunsplit(data: Sequence[str]) -> str: ...
-def urljoin(base: Union[str, unicode], url: Union[str, unicode],
+def urlunsplit(data: Sequence[_String]) -> str: ...
+def urljoin(base: _String, url: _String,
             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]]: ...
-def parse_qsl(qs: str, keep_blank_values: int = ...,
-              strict_parsing: bool = ...) -> List[Tuple[str, str]]: ...
+def urldefrag(url: AnyStr) -> Tuple[AnyStr, str]: ...
+def unquote(s: AnyStr) -> AnyStr: ...
+def parse_qs(qs: AnyStr, keep_blank_values: bool = ...,
+             strict_parsing: bool = ...) -> Dict[AnyStr, List[AnyStr]]: ...
+def parse_qsl(qs: AnyStr, keep_blank_values: int = ...,
+              strict_parsing: bool = ...) -> List[Tuple[AnyStr, AnyStr]]: ...
diff --git a/typeshed/stdlib/2/user.pyi b/typeshed/stdlib/2/user.pyi
new file mode 100644
index 0000000..e6beaa9
--- /dev/null
+++ b/typeshed/stdlib/2/user.pyi
@@ -0,0 +1,9 @@
+# Stubs for user (Python 2)
+
+# Docs: https://docs.python.org/2/library/user.html
+# Source: https://hg.python.org/cpython/file/2.7/Lib/user.py
+from typing import Any
+
+def __getattr__(name) -> Any: ...  # type: ignore
+home: str
+pythonrc: str
diff --git a/typeshed/stdlib/2/weakref.pyi b/typeshed/stdlib/2/weakref.pyi
deleted file mode 100644
index b040e25..0000000
--- a/typeshed/stdlib/2/weakref.pyi
+++ /dev/null
@@ -1,47 +0,0 @@
-# Stubs for weakref (Python 2)
-#
-# Based on stub automatically generated by stubgen.
-
-from typing import Any, MutableMapping, Generic, Iterator, List, TypeVar
-from _weakref import (getweakrefcount, getweakrefs, ref, proxy,
-                      CallableProxyType, ProxyType, ReferenceType)
-from _weakrefset import WeakSet
-
-ProxyTypes = ...  # type: Any
-
-_KT = TypeVar('_KT')
-_VT = TypeVar('_VT')
-
-# Don't inherit from typing.Dict since
-# isinstance(weakref.WeakValueDictionary(), dict) is False
-class WeakValueDictionary(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
-    def itervaluerefs(self) -> Iterator[ReferenceType[_VT]]: ...
-    def valuerefs(self) -> List[ReferenceType[_VT]]: ...
-
-    def __setitem__(self, k: _KT, v: _VT) -> None: ...
-    def __delitem__(self, v: _KT) -> None: ...
-    def __getitem__(self, k: _KT) -> _VT: ...
-    def __len__(self) -> int: ...
-    def __iter__(self) -> Iterator[_KT]: ...
-
-    def has_key(self, key: _KT) -> bool: ...
-    def copy(self) -> WeakValueDictionary[_KT, _VT]: ...
-
-class WeakKeyDictionary(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
-    def iterkeyrefs(self) -> Iterator[ReferenceType[_KT]]: ...
-    def keyrefs(self) -> List[ReferenceType[_KT]]: ...
-
-    def __setitem__(self, k: _KT, v: _VT) -> None: ...
-    def __delitem__(self, v: _KT) -> None: ...
-    def __getitem__(self, k: _KT) -> _VT: ...
-    def __len__(self) -> int: ...
-    def __iter__(self) -> Iterator[_KT]: ...
-
-    def has_key(self, key: _KT) -> bool: ...
-    def copy(self) -> WeakKeyDictionary[_KT, _VT]: ...
-
-# TODO: make generic
-class KeyedRef(ReferenceType):
-    key = ...  # type: Any
-    def __new__(type, ob, callback, key): ...
-    def __init__(self, ob, callback, key): ...
diff --git a/typeshed/stdlib/2/wsgiref/validate.pyi b/typeshed/stdlib/2/wsgiref/validate.pyi
index 490889c..bd0c7b7 100644
--- a/typeshed/stdlib/2/wsgiref/validate.pyi
+++ b/typeshed/stdlib/2/wsgiref/validate.pyi
@@ -1,7 +1,3 @@
-# Stubs for wsgiref.validate (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class WSGIWarning(Warning): ...
diff --git a/typeshed/stdlib/2and3/__future__.pyi b/typeshed/stdlib/2and3/__future__.pyi
index f59753c..7eed90e 100644
--- a/typeshed/stdlib/2and3/__future__.pyi
+++ b/typeshed/stdlib/2and3/__future__.pyi
@@ -1,16 +1,21 @@
 import sys
+from typing import List
 
 class _Feature:
     def getOptionalRelease(self) -> sys._version_info: ...
     def getMandatoryRelease(self) -> sys._version_info: ...
 
-absolute_import = ...  # type: _Feature
-division = ...  # type: _Feature
-generators = ...  # type: _Feature
-nested_scopes = ...  # type: _Feature
-print_function = ...  # type: _Feature
-unicode_literals = ...  # type: _Feature
-with_statement = ...  # type: _Feature
+absolute_import: _Feature
+division: _Feature
+generators: _Feature
+nested_scopes: _Feature
+print_function: _Feature
+unicode_literals: _Feature
+with_statement: _Feature
+if sys.version_info >= (3, 0):
+    barry_as_FLUFL: _Feature
 
-if sys.version_info[:2] >= (3, 5):
-    generator_stop = ...  # type: _Feature
+if sys.version_info >= (3, 5):
+    generator_stop: _Feature
+
+all_feature_names: List[str]
diff --git a/typeshed/stdlib/2and3/_csv.pyi b/typeshed/stdlib/2and3/_csv.pyi
new file mode 100644
index 0000000..d5119ae
--- /dev/null
+++ b/typeshed/stdlib/2and3/_csv.pyi
@@ -0,0 +1,45 @@
+import sys
+
+from typing import Any, Iterable, Iterator, List, Optional, Sequence
+
+QUOTE_ALL = ...  # type: int
+QUOTE_MINIMAL = ...  # type: int
+QUOTE_NONE = ...  # type: int
+QUOTE_NONNUMERIC = ...  # type: int
+
+class Error(Exception): ...
+
+class Dialect:
+    delimiter = ...  # type: str
+    quotechar = ...  # type: Optional[str]
+    escapechar = ...  # type: Optional[str]
+    doublequote = ...  # type: bool
+    skipinitialspace = ...  # type: bool
+    lineterminator = ...  # type: str
+    quoting = ...  # type: int
+    strict = ...  # type: int
+    def __init__(self) -> None: ...
+
+class _reader(Iterator[List[str]]):
+    dialect = ...  # type: Dialect
+    line_num = ...  # type: int
+
+class _writer:
+    dialect = ...  # type: Dialect
+
+    if sys.version_info >= (3, 5):
+        def writerow(self, row: Iterable[Any]) -> None: ...
+        def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ...
+    else:
+        def writerow(self, row: Sequence[Any]) -> None: ...
+        def writerows(self, rows: Iterable[Sequence[Any]]) -> None: ...
+
+
+# TODO: precise type
+def writer(csvfile: Any, dialect: Any = ..., **fmtparams: Any) -> _writer: ...
+def reader(csvfile: Iterable[str], dialect: Any = ..., **fmtparams: Any) -> _reader: ...
+def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ...
+def unregister_dialect(name: str) -> None: ...
+def get_dialect(name: str) -> Dialect: ...
+def list_dialects() -> List[str]: ...
+def field_size_limit(new_limit: int = ...) -> int: ...
diff --git a/typeshed/stdlib/2/_weakref.pyi b/typeshed/stdlib/2and3/_weakref.pyi
similarity index 62%
rename from typeshed/stdlib/2/_weakref.pyi
rename to typeshed/stdlib/2and3/_weakref.pyi
index a7bb9ea..76c97df 100644
--- a/typeshed/stdlib/2/_weakref.pyi
+++ b/typeshed/stdlib/2and3/_weakref.pyi
@@ -1,21 +1,24 @@
+import sys
 from typing import Any, Callable, Generic, Optional, TypeVar
 
 _T = TypeVar('_T')
 
 class CallableProxyType(object):  # "weakcallableproxy"
-    pass
+    def __getattr__(self, attr: str) -> Any: ...
 
 class ProxyType(object):  # "weakproxy"
-    pass
+    def __getattr__(self, attr: str) -> Any: ...
 
 class ReferenceType(Generic[_T]):
-    # TODO rest of members
+    if sys.version_info >= (3, 4):
+        __callback__: Callable[[ReferenceType[_T]], Any]
     def __init__(self, o: _T, callback: Callable[[ReferenceType[_T]],
                                                  Any] = ...) -> None: ...
     def __call__(self) -> Optional[_T]: ...
+    def __hash__(self) -> int: ...
 
 ref = ReferenceType
 
 def getweakrefcount(object: Any) -> int: ...
 def getweakrefs(object: Any) -> int: ...
-def proxy(object: Any, callback: Callable[[Any], Any] = ...) -> None: ...
+def proxy(object: _T, callback: Callable[[_T], Any] = ...) -> ref[_T]: ...
diff --git a/typeshed/stdlib/2and3/_weakrefset.pyi b/typeshed/stdlib/2and3/_weakrefset.pyi
new file mode 100644
index 0000000..950d3fe
--- /dev/null
+++ b/typeshed/stdlib/2and3/_weakrefset.pyi
@@ -0,0 +1,43 @@
+from typing import Iterator, Any, Iterable, MutableSet, Optional, TypeVar, Generic, Union
+
+_S = TypeVar('_S')
+_T = TypeVar('_T')
+_SelfT = TypeVar('_SelfT', bound=WeakSet)
+
+class WeakSet(MutableSet[_T], Generic[_T]):
+    def __init__(self, data: Optional[Iterable[_T]] = ...) -> None: ...
+
+    def add(self, item: _T) -> None: ...
+    def clear(self) -> None: ...
+    def discard(self, item: _T) -> None: ...
+    def copy(self: _SelfT) -> _SelfT: ...
+    def pop(self) -> _T: ...
+    def remove(self, item: _T) -> None: ...
+    def update(self, other: Iterable[_T]) -> None: ...
+    def __contains__(self, item: object) -> bool: ...
+    def __len__(self) -> int: ...
+    def __iter__(self) -> Iterator[_T]: ...
+
+    def __ior__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ...
+    def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ...
+    def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ...
+    def difference_update(self: _SelfT, other: Iterable[_T]) -> None: ...
+    def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ...
+    def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ...
+    def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ...
+    def intersection_update(self, other: Iterable[_T]) -> None: ...
+    def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ...
+    def issubset(self, other: Iterable[_T]) -> bool: ...
+    def __le__(self, other: Iterable[_T]) -> bool: ...
+    def __lt__(self, other: Iterable[_T]) -> bool: ...
+    def issuperset(self, other: Iterable[_T]) -> bool: ...
+    def __ge__(self, other: Iterable[_T]) -> bool: ...
+    def __gt__(self, other: Iterable[_T]) -> bool: ...
+    def __eq__(self, other: object) -> bool: ...
+    def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ...
+    def __xor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ...
+    def symmetric_difference_update(self, other: Iterable[_S]) -> None: ...
+    def __ixor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ...
+    def union(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ...
+    def __or__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ...
+    def isdisjoint(self, other: Iterable[_T]) -> bool: ...
diff --git a/typeshed/stdlib/2and3/asynchat.pyi b/typeshed/stdlib/2and3/asynchat.pyi
index 44e1f83..7195f80 100644
--- a/typeshed/stdlib/2and3/asynchat.pyi
+++ b/typeshed/stdlib/2and3/asynchat.pyi
@@ -2,28 +2,28 @@ from abc import abstractmethod
 import asyncore
 import socket
 import sys
-from typing import Union, Tuple, Sequence
+from typing import Optional, Sequence, Tuple, Union
 
 
 class simple_producer:
-    def __init__(self, data: str, buffer_size: int = ...) -> None: ...
-    def more(self) -> str: ...
+    def __init__(self, data: bytes, buffer_size: int = ...) -> None: ...
+    def more(self) -> bytes: ...
 
 class async_chat(asyncore.dispatcher):
     ac_in_buffer_size = ...  # type: int
     ac_out_buffer_size = ...  # type: int
-    def __init__(self, sock: socket.socket = None, map: asyncore._maptype = None) -> None: ...
+    def __init__(self, sock: Optional[socket.socket] = None, map: Optional[asyncore._maptype] = None) -> None: ...
 
     @abstractmethod
     def collect_incoming_data(self, data: bytes) -> None: ...
     @abstractmethod
     def found_terminator(self) -> None: ...
-    def set_terminator(self, term: Union[str, int, None]) -> None: ...
-    def get_terminator(self) -> Union[str, int, None]: ...
+    def set_terminator(self, term: Union[bytes, int, None]) -> None: ...
+    def get_terminator(self) -> Union[bytes, int, None]: ...
     def handle_read(self) -> None: ...
     def handle_write(self) -> None: ...
     def handle_close(self) -> None: ...
-    def push(self, data: str) -> None: ...
+    def push(self, data: bytes) -> None: ...
     def push_with_producer(self, producer: simple_producer) -> None: ...
     def readable(self) -> bool: ...
     def writable(self) -> bool: ...
@@ -33,9 +33,9 @@ class async_chat(asyncore.dispatcher):
 
 if sys.version_info < (3, 0):
     class fifo:
-        def __init__(self, list: Sequence[Union[str, simple_producer]] = ...) -> None: ...
+        def __init__(self, list: Sequence[Union[bytes, simple_producer]] = ...) -> None: ...
         def __len__(self) -> int: ...
         def is_empty(self) -> bool: ...
-        def first(self) -> str: ...
-        def push(self, data: Union[str, simple_producer]) -> None: ...
-        def pop(self) -> Tuple[int, str]: ...
+        def first(self) -> bytes: ...
+        def push(self, data: Union[bytes, simple_producer]) -> None: ...
+        def pop(self) -> Tuple[int, bytes]: ...
diff --git a/typeshed/stdlib/2and3/asyncore.pyi b/typeshed/stdlib/2and3/asyncore.pyi
index 4816da0..0753197 100644
--- a/typeshed/stdlib/2and3/asyncore.pyi
+++ b/typeshed/stdlib/2and3/asyncore.pyi
@@ -25,7 +25,7 @@ def poll2(timeout: float = ..., map: _maptype = ...) -> None: ...
 
 poll3 = poll2
 
-def loop(timeout: float = ..., use_poll: bool = ..., map: _maptype = ..., count: int = None) -> None: ...
+def loop(timeout: float = ..., use_poll: bool = ..., map: _maptype = ..., count: Optional[int] = None) -> None: ...
 
 
 # Not really subclass of socket.socket; it's only delegation.
@@ -39,7 +39,7 @@ class dispatcher:
     closing = ...  # type: bool
     ignore_log_types = ...  # type: frozenset[str]
 
-    def __init__(self, sock: socket.socket = None, map: _maptype = ...) -> None: ...
+    def __init__(self, sock: Optional[socket.socket] = None, map: _maptype = ...) -> None: ...
     def add_channel(self, map: _maptype = ...) -> None: ...
     def del_channel(self, map: _maptype = ...) -> None: ...
     def create_socket(self, family: int, type: int) -> None: ...
@@ -47,10 +47,15 @@ class dispatcher:
     def set_reuse_addr(self) -> None: ...
     def readable(self) -> bool: ...
     def writable(self) -> bool: ...
+    def listen(self, backlog: int) -> None: ...
+    def bind(self, address: Union[tuple, str]) -> None: ...
+    def connect(self, address: Union[tuple, str]) -> None: ...
     def accept(self) -> Optional[Tuple[socket.socket, Any]]: ...
-    def recv(self, buffer_size: int) -> str: ...
-    def log(self, message: Any) -> None: ...
+    def send(self, data: bytes) -> int: ...
+    def recv(self, buffer_size: int) -> bytes: ...
+    def close(self) -> None: ...
 
+    def log(self, message: Any) -> None: ...
     def log_info(self, message: Any, type: str = ...) -> None: ...
     def handle_read_event(self) -> None: ...
     def handle_connect_event(self) -> None: ...
@@ -63,46 +68,51 @@ class dispatcher:
     def handle_connect(self) -> None: ...
     def handle_accept(self) -> None: ...
     def handle_close(self) -> None: ...
-    def detach(self) -> int: ...
-    def fileno(self) -> int: ...
-
-    # return value is an address
-    def getpeername(self) -> Any: ...
-    def getsockname(self) -> Any: ...
 
-    @overload
-    def getsockopt(self, level: int, optname: int) -> int: ...
-    @overload
-    def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...
-
-    def gettimeout(self) -> float: ...
-    def ioctl(self, control: object,
-              option: Tuple[int, int, int]) -> None: ...
-    def listen(self, backlog: int) -> None: ...
-    # TODO the return value may be BinaryIO or TextIO, depending on mode
-    def makefile(self, mode: str = ..., buffering: int = ...,
-                 encoding: str = ..., errors: str = ...,
-                 newline: str = ...) -> Any:
-        ...
-
-    # return type is an address
-    def recvfrom(self, bufsize: int, flags: int = ...) -> Any: ...
-    def recvfrom_into(self, buffer: str, nbytes: int, flags: int = ...) -> Any: ...
-    def recv_into(self, buffer: str, nbytes: int, flags: int = ...) -> Any: ...
-    def send(self, data: str, flags: int = ...) -> Optional[int]: ...
-    def sendall(self, data: str, flags: int = ...) -> None: ...
-    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: int, value: Union[int, str]) -> None: ...
-    def shutdown(self, how: int) -> None: ...
+    if sys.version_info < (3, 5):
+        # Historically, some methods were "imported" from `self.socket` by
+        # means of `__getattr__`. This was long deprecated, and as of Python
+        # 3.5 has been removed; simply call the relevant methods directly on
+        # self.socket if necessary.
+
+        def detach(self) -> int: ...
+        def fileno(self) -> int: ...
+
+        # return value is an address
+        def getpeername(self) -> Any: ...
+        def getsockname(self) -> Any: ...
+
+        @overload
+        def getsockopt(self, level: int, optname: int) -> int: ...
+        @overload
+        def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...
+
+        def gettimeout(self) -> float: ...
+        def ioctl(self, control: object,
+                  option: Tuple[int, int, int]) -> None: ...
+        # TODO the return value may be BinaryIO or TextIO, depending on mode
+        def makefile(self, mode: str = ..., buffering: int = ...,
+                     encoding: str = ..., errors: str = ...,
+                     newline: str = ...) -> Any:
+            ...
+
+        # return type is an address
+        def recvfrom(self, bufsize: int, flags: int = ...) -> Any: ...
+        def recvfrom_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ...
+        def recv_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ...
+        def sendall(self, data: bytes, flags: int = ...) -> None: ...
+        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: int, value: Union[int, bytes]) -> None: ...
+        def shutdown(self, how: int) -> None: ...
 
 class dispatcher_with_send(dispatcher):
     def __init__(self, sock: socket.socket = ..., map: _maptype = ...) -> None: ...
     def initiate_send(self) -> None: ...
     def handle_write(self) -> None: ...
     # incompatible signature:
-    # def send(self, data: str) -> Optional[int]: ...
+    # def send(self, data: bytes) -> Optional[int]: ...
 
 def compact_traceback() -> Tuple[Tuple[str, str, str], type, type, str]: ...
 def close_all(map: _maptype = ..., ignore_all: bool = ...) -> None: ...
@@ -113,16 +123,16 @@ class file_wrapper:
     fd = ...  # type: int
 
     def __init__(self, fd: int) -> None: ...
-    def recv(self, bufsize: int, flags: int = ...) -> str: ...
-    def send(self, data: str, flags: int = ...) -> int: ...
+    def recv(self, bufsize: int, flags: int = ...) -> bytes: ...
+    def send(self, data: bytes, flags: int = ...) -> int: ...
 
     @overload
     def getsockopt(self, level: int, optname: int) -> int: ...
     @overload
     def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...
 
-    def read(self, bufsize: int, flags: int = ...) -> str: ...
-    def write(self, data: str, flags: int = ...) -> int: ...
+    def read(self, bufsize: int, flags: int = ...) -> bytes: ...
+    def write(self, data: bytes, flags: int = ...) -> int: ...
 
     def close(self) -> None: ...
     def fileno(self) -> int: ...
diff --git a/typeshed/stdlib/2and3/bz2.pyi b/typeshed/stdlib/2and3/bz2.pyi
index e7cdab5..7c92e43 100644
--- a/typeshed/stdlib/2and3/bz2.pyi
+++ b/typeshed/stdlib/2and3/bz2.pyi
@@ -1,21 +1,21 @@
 # Stubs for bz2
 
-from typing import Any, BinaryIO, TextIO, IO, Union
+from typing import Any, BinaryIO, TextIO, IO, Optional, Union
 
 def compress(data: bytes, compresslevel: int = ...) -> bytes: ...
 def decompress(data: bytes) -> bytes: ...
 
 def open(filename: Union[str, bytes, IO[Any]],
          mode: str = 'rb',
-         encoding: str = None,
-         errors: str = None,
-         newline: str = None) -> IO[Any]: ...
+         encoding: Optional[str] = None,
+         errors: Optional[str] = None,
+         newline: Optional[str] = None) -> IO[Any]: ...
 
 class BZ2File(BinaryIO):
     def __init__(self,
                  filename: Union[str, bytes, IO[Any]],
                  mode: str = "r",
-                 buffering: Any = None,
+                 buffering: Optional[Any] = None,
                  compresslevel: int = 9) -> None: ...
 
 class BZ2Compressor(object):
diff --git a/typeshed/stdlib/3/calendar.pyi b/typeshed/stdlib/2and3/calendar.pyi
similarity index 60%
rename from typeshed/stdlib/3/calendar.pyi
rename to typeshed/stdlib/2and3/calendar.pyi
index 957f8ce..6b59fd0 100644
--- a/typeshed/stdlib/3/calendar.pyi
+++ b/typeshed/stdlib/2and3/calendar.pyi
@@ -1,10 +1,10 @@
 import datetime
-
+import sys
 from time import struct_time
-from typing import Any, Iterable, List, Optional, Tuple, Sequence, Union
+from typing import Any, Iterable, List, Optional, Sequence, Tuple, Union
 
 
-LocaleType = Tuple[Optional[str], Optional[str]]
+_LocaleType = Tuple[Optional[str], Optional[str]]
 
 class IllegalMonthError(ValueError):
     def __init__(self, month: int) -> None: ...
@@ -20,7 +20,7 @@ def weekday(year: int, month: int, day: int) -> int: ...
 def monthrange(year: int, month: int) -> Tuple[int, int]: ...
 
 class Calendar:
-    def __init__(self, firstweekday: int = 0) -> None: ...
+    def __init__(self, firstweekday: int = ...) -> None: ...
     def getfirstweekday(self) -> int: ...
     def setfirstweekday(self, firstweekday: int) -> None: ...
     def iterweekdays(self) -> Iterable[int]: ...
@@ -30,9 +30,9 @@ class Calendar:
     def monthdatescalendar(self, year: int, month: int) -> List[List[datetime.date]]: ...
     def monthdays2calendar(self, year: int, month: int) -> List[List[Tuple[int, int]]]: ...
     def monthdayscalendar(self, year: int, month: int) -> List[List[int]]: ...
-    def yeardatescalendar(self, year: int, width: int = 3) -> List[List[int]]: ...
-    def yeardays2calendar(self, year: int, width: int = 3) -> List[List[Tuple[int, int]]]: ...
-    def yeardayscalendar(self, year: int, width: int = 3) -> List[List[int]]: ...
+    def yeardatescalendar(self, year: int, width: int = ...) -> List[List[int]]: ...
+    def yeardays2calendar(self, year: int, width: int = ...) -> List[List[Tuple[int, int]]]: ...
+    def yeardayscalendar(self, year: int, width: int = ...) -> List[List[int]]: ...
 
 class TextCalendar(Calendar):
     def prweek(self, theweek: int, width: int) -> None: ...
@@ -41,10 +41,20 @@ class TextCalendar(Calendar):
     def formatweekday(self, day: int, width: int) -> str: ...
     def formatweekheader(self, width: int) -> str: ...
     def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ...
-    def prmonth(self, theyear: int, themonth: int, w: Any=0, l: Any = 0) -> None: ...
-    def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ...
-    def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ...
-    def pryear(self, theyear: int, w: Any = 0, l: Any = 0, c: Any = 6, m: Any = 3) -> None: ...
+    def prmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ...
+    def formatmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ...
+    def formatyear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ...
+    def pryear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ...
+
+def firstweekday() -> int: ...
+def monthcalendar(year: int, month: int) -> List[List[int]]: ...
+def prweek(theweek: int, width: int) -> None: ...
+def week(theweek: int, width: int) -> str: ...
+def weekheader(width: int) -> str: ...
+def prmonth(theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ...
+def month(theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ...
+def calendar(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ...
+def prcal(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ...
 
 class HTMLCalendar(Calendar):
     def formatday(self, day: int, weekday: int) -> str: ...
@@ -53,21 +63,27 @@ class HTMLCalendar(Calendar):
     def formatweekheader(self) -> str: ...
     def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ...
     def formatmonth(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ...
-    def formatyear(self, theyear: int, width: int = 3) -> str: ...
-    def formatyearpage(self, theyear: int, width: int = 3, css: Optional[str] = 'calendar.css', encoding: Optional[str] = ...) -> str: ...
-
-class different_locale:
-    def __init__(self, locale: LocaleType) -> None: ...
-    def __enter__(self) -> LocaleType: ...
-    def __exit__(self, *args) -> None: ...
+    def formatyear(self, theyear: int, width: int = ...) -> str: ...
+    def formatyearpage(self, theyear: int, width: int = ..., css: Optional[str] = ..., encoding: Optional[str] = ...) -> str: ...
+
+if sys.version_info < (3, 0):
+    class TimeEncoding:
+        def __init__(self, locale: _LocaleType) -> None: ...
+        def __enter__(self) -> _LocaleType: ...
+        def __exit__(self, *args) -> None: ...
+else:
+    class different_locale:
+        def __init__(self, locale: _LocaleType) -> None: ...
+        def __enter__(self) -> _LocaleType: ...
+        def __exit__(self, *args) -> None: ...
 
 class LocaleTextCalendar(TextCalendar):
-    def __init__(self, firstweekday: int = 0, locale: Optional[LocaleType] = ...) -> None: ...
+    def __init__(self, firstweekday: int = ..., locale: Optional[_LocaleType] = ...) -> None: ...
     def formatweekday(self, day: int, width: int) -> str: ...
     def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ...
 
 class LocaleHTMLCalendar(HTMLCalendar):
-    def __init__(self, firstweekday: int = 0, locale: Optional[LocaleType] = ...) -> None: ...
+    def __init__(self, firstweekday: int = ..., locale: Optional[_LocaleType] = ...) -> None: ...
     def formatweekday(self, day: int) -> str: ...
     def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ...
 
diff --git a/typeshed/stdlib/2and3/contextlib.pyi b/typeshed/stdlib/2and3/contextlib.pyi
index 6ff18d8..480546f 100644
--- a/typeshed/stdlib/2and3/contextlib.pyi
+++ b/typeshed/stdlib/2and3/contextlib.pyi
@@ -2,35 +2,40 @@
 
 from typing import (
     Any, Callable, Generator, IO, Iterable, Iterator, Optional, Type,
-    Generic, TypeVar,
+    Generic, TypeVar
 )
 from types import TracebackType
 import sys
+# Aliased here for backwards compatibility; TODO eventually remove this
+from typing import ContextManager as ContextManager
+
+if sys.version_info >= (3, 5):
+    from typing import AsyncContextManager, AsyncIterator
+
+if sys.version_info >= (3, 6):
+    from typing import ContextManager as AbstractContextManager
 
 _T = TypeVar('_T')
+
 _ExitFunc = Callable[[Optional[Type[BaseException]],
-                      Optional[Exception],
+                      Optional[BaseException],
                       Optional[TracebackType]], bool]
 _CM_EF = TypeVar('_CM_EF', ContextManager, _ExitFunc)
 
-# TODO already in PEP, have to get added to mypy
-class ContextManager(Generic[_T]):
-    def __enter__(self) -> _T: ...
-    def __exit__(self, exc_type: Optional[Type[BaseException]],
-                 exc_val: Optional[Exception],
-                 exc_tb: Optional[TracebackType]) -> bool: ...
-
 if sys.version_info >= (3, 2):
-    class GeneratorContextManager(Generic[_T], ContextManager[_T]):
+    class GeneratorContextManager(ContextManager[_T], Generic[_T]):
         def __call__(self, func: Callable[..., _T]) -> Callable[..., _T]: ...
     def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., GeneratorContextManager[_T]]: ...
 else:
     def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
 
+if sys.version_info >= (3, 7):
+    def asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]]: ...
+
 if sys.version_info < (3,):
     def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ...
 
-class closing(Generic[_T], ContextManager[_T]):
+class closing(ContextManager[_T], Generic[_T]):
     def __init__(self, thing: _T) -> None: ...
 
 if sys.version_info >= (3, 4):
diff --git a/typeshed/stdlib/2and3/csv.pyi b/typeshed/stdlib/2and3/csv.pyi
new file mode 100644
index 0000000..a61edcb
--- /dev/null
+++ b/typeshed/stdlib/2and3/csv.pyi
@@ -0,0 +1,97 @@
+from collections import OrderedDict
+import sys
+from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Union
+
+from _csv import (_reader,
+                  _writer,
+                  reader as reader,
+                  writer as writer,
+                  register_dialect as register_dialect,
+                  unregister_dialect as unregister_dialect,
+                  get_dialect as get_dialect,
+                  list_dialects as list_dialects,
+                  field_size_limit as field_size_limit,
+                  QUOTE_ALL as QUOTE_ALL,
+                  QUOTE_MINIMAL as QUOTE_MINIMAL,
+                  QUOTE_NONE as QUOTE_NONE,
+                  QUOTE_NONNUMERIC as QUOTE_NONNUMERIC,
+                  Error as Error,
+                  )
+
+_Dialect = Union[str, Dialect]
+_DictRow = Dict[str, Any]
+
+class Dialect(object):
+    delimiter = ...  # type: str
+    quotechar = ...  # type: Optional[str]
+    escapechar = ...  # type: Optional[str]
+    doublequote = ...  # type: bool
+    skipinitialspace = ...  # type: bool
+    lineterminator = ...  # type: str
+    quoting = ...  # type: int
+    def __init__(self) -> None: ...
+
+class excel(Dialect):
+    delimiter = ...  # type: str
+    quotechar = ...  # type: str
+    doublequote = ...  # type: bool
+    skipinitialspace = ...  # type: bool
+    lineterminator = ...  # type: str
+    quoting = ...  # type: int
+
+class excel_tab(excel):
+    delimiter = ...  # type: str
+
+if sys.version_info >= (3,):
+    class unix_dialect(Dialect):
+        delimiter = ...  # type: str
+        quotechar = ...  # type: str
+        doublequote = ...  # type: bool
+        skipinitialspace = ...  # type: bool
+        lineterminator = ...  # type: str
+        quoting = ...  # type: int
+
+if sys.version_info >= (3, 6):
+    class DictReader(Iterator[OrderedDict[str, str]]):
+        restkey = ...  # type: Optional[str]
+        restval = ...  # type: Optional[str]
+        reader = ...  # type: _reader
+        dialect = ...  # type: _Dialect
+        line_num = ...  # type: int
+        fieldnames = ...  # type: Sequence[str]
+        def __init__(self, f: Iterator[str], fieldnames: Sequence[str] = ...,
+                     restkey: Optional[str] = ..., restval: Optional[str] = ..., dialect: _Dialect = ...,
+                     *args: Any, **kwds: Any) -> None: ...
+        def __iter__(self) -> Iterator[OrderedDict[str, str]]: ...
+        def next(self) -> OrderedDict[str, str]: ...
+else:
+    class DictReader(Iterator[Dict[Any, str]]):
+        restkey = ...  # type: Optional[str]
+        restval = ...  # type: Optional[str]
+        reader = ...  # type: _reader
+        dialect = ...  # type: _Dialect
+        line_num = ...  # type: int
+        fieldnames = ...  # type: Sequence[str]
+        def __init__(self, f: Iterator[str], fieldnames: Sequence[str] = ...,
+                     restkey: Optional[str] = ..., restval: Optional[str] = ..., dialect: _Dialect = ...,
+                     *args: Any, **kwds: Any) -> None: ...
+        def __iter__(self) -> Iterator[OrderedDict[Any, str]]: ...
+        def next(self) -> OrderedDict[Any, str]: ...
+
+class DictWriter(object):
+    fieldnames = ...  # type: Sequence[str]
+    restval = ...  # type: Optional[Any]
+    extrasaction = ...  # type: str
+    writer = ...  # type: _writer
+    def __init__(self, f: Any, fieldnames: Sequence[str],
+                 restval: Optional[Any] = ..., extrasaction: str = ..., dialect: _Dialect = ...,
+                 *args: Any, **kwds: Any) -> None: ...
+    def writeheader(self) -> None: ...
+    def writerow(self, rowdict: _DictRow) -> None: ...
+    def writerows(self, rowdicts: Iterable[_DictRow]) -> None: ...
+
+class Sniffer(object):
+    preferred = ...  # type: List[str]
+    def __init__(self) -> None: ...
+    def sniff(self, sample: str, delimiters: Optional[str] = ...) -> Dialect: ...
+    def has_header(self, sample: str) -> bool: ...
diff --git a/typeshed/stdlib/2/difflib.pyi b/typeshed/stdlib/2and3/difflib.pyi
similarity index 79%
rename from typeshed/stdlib/2/difflib.pyi
rename to typeshed/stdlib/2and3/difflib.pyi
index e0809f8..4701e32 100644
--- a/typeshed/stdlib/2/difflib.pyi
+++ b/typeshed/stdlib/2and3/difflib.pyi
@@ -1,9 +1,8 @@
-# Stubs for difflib
+# Based on https://docs.python.org/2.7/library/difflib.html and https://docs.python.org/3.2/library/difflib.html
 
-# Based on https://docs.python.org/2.7/library/difflib.html
-
-# TODO: Support unicode?
+# TODO: Support unicode in Python 2?
 
+import sys
 from typing import (
     TypeVar, Callable, Iterable, Iterator, List, NamedTuple, Sequence, Tuple,
     Generic, Optional
@@ -11,6 +10,12 @@ from typing import (
 
 _T = TypeVar('_T')
 
+Match = NamedTuple('Match', [
+    ('a', int),
+    ('b', int),
+    ('size', int),
+])
+
 class SequenceMatcher(Generic[_T]):
     def __init__(self, isjunk: Optional[Callable[[_T], bool]] = ...,
                  a: Sequence[_T] = ..., b: Sequence[_T] = ...,
@@ -20,7 +25,7 @@ class SequenceMatcher(Generic[_T]):
     def set_seq2(self, b: Sequence[_T]) -> None: ...
     def find_longest_match(self, alo: int, ahi: int, blo: int,
                            bhi: int) -> Tuple[int, int, int]: ...
-    def get_matching_blocks(self) -> List[Tuple[int, int, int]]: ...
+    def get_matching_blocks(self) -> List[Match]: ...
     def get_opcodes(self) -> List[Tuple[str, int, int, int, int]]: ...
     def get_grouped_opcodes(self, n: int = ...
                             ) -> Iterable[Tuple[str, int, int, int, int]]: ...
@@ -62,3 +67,16 @@ class HtmlDiff(object):
                    numlines: int = ...) -> str: ...
 
 def restore(delta: Iterable[str], which: int) -> Iterator[int]: ...
+
+if sys.version_info >= (3, 5):
+    def diff_bytes(
+        dfunc: Callable[[Sequence[str], Sequence[str], str, str, str, str, int, str], Iterator[str]],
+        a: Sequence[bytes],
+        b: Sequence[bytes],
+        fromfile: bytes = ...,
+        tofile: bytes = ...,
+        fromfiledate: bytes = ...,
+        tofiledate: bytes = ...,
+        n: int = ...,
+        lineterm: bytes = ...
+    ) -> Iterator[bytes]: ...
diff --git a/typeshed/stdlib/2and3/distutils/core.pyi b/typeshed/stdlib/2and3/distutils/core.pyi
index d513c2b..9d41daf 100644
--- a/typeshed/stdlib/2and3/distutils/core.pyi
+++ b/typeshed/stdlib/2and3/distutils/core.pyi
@@ -36,12 +36,14 @@ def setup(name: str = ...,
           command_packages: List[str] = ...,
           command_options: Mapping[str, Mapping[str, Tuple[Any, Any]]] = ...,
           package_data: Mapping[str, List[str]] = ...,
+          include_package_data: bool = ...,
           libraries: List[str] = ...,
           headers: List[str] = ...,
           ext_package: str = ...,
           include_dirs: List[str] = ...,
           password: str = ...,
-          fullname: str = ...) -> None: ...
+          fullname: str = ...,
+          **attrs: Any) -> None: ...
 
 def run_setup(script_name: str,
               script_args: Optional[List[str]] = ...,
diff --git a/typeshed/stdlib/2and3/distutils/version.pyi b/typeshed/stdlib/2and3/distutils/version.pyi
index 6b6efbf..d44a6f2 100644
--- a/typeshed/stdlib/2and3/distutils/version.pyi
+++ b/typeshed/stdlib/2and3/distutils/version.pyi
@@ -1,7 +1,3 @@
-# Stubs for distutils.version (Python 2 and 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 import sys
 from typing import Any
 
diff --git a/typeshed/stdlib/2and3/doctest.pyi b/typeshed/stdlib/2and3/doctest.pyi
new file mode 100644
index 0000000..8151fb5
--- /dev/null
+++ b/typeshed/stdlib/2and3/doctest.pyi
@@ -0,0 +1,161 @@
+from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union
+
+import sys
+import types
+import unittest
+
+TestResults = NamedTuple('TestResults', [
+    ('failed', int),
+    ('attempted', int),
+])
+
+OPTIONFLAGS_BY_NAME: Dict[str, int]
+def register_optionflag(name: str) -> int: ...
+DONT_ACCEPT_TRUE_FOR_1: int
+DONT_ACCEPT_BLANKLINE: int
+NORMALIZE_WHITESPACE: int
+ELLIPSIS: int
+SKIP: int
+IGNORE_EXCEPTION_DETAIL: int
+
+COMPARISON_FLAGS: int
+
+REPORT_UDIFF: int
+REPORT_CDIFF: int
+REPORT_NDIFF: int
+REPORT_ONLY_FIRST_FAILURE: int
+if sys.version_info >= (3, 4):
+    FAIL_FAST: int
+
+REPORTING_FLAGS: int
+
+BLANKLINE_MARKER: str
+ELLIPSIS_MARKER: str
+
+class Example:
+    source: str
+    want: str
+    exc_msg: Optional[str]
+    lineno: int
+    indent: int
+    options: Dict[int, bool]
+    def __init__(self, source: str, want: str, exc_msg: Optional[str] = ..., lineno: int = ..., indent: int = ...,
+                 options: Optional[Dict[int, bool]] = ...) -> None: ...
+    def __hash__(self) -> int: ...
+
+class DocTest:
+    examples: List[Example]
+    globs: Dict[str, Any]
+    name: str
+    filename: Optional[str]
+    lineno: Optional[int]
+    docstring: Optional[str]
+    def __init__(self, examples: List[Example], globs: Dict[str, Any], name: str, filename: Optional[str], lineno: Optional[int], docstring: Optional[str]) -> None: ...
+    def __hash__(self) -> int: ...
+    def __lt__(self, other: DocTest) -> bool: ...
+
+class DocTestParser:
+    def parse(self, string: str, name: str = ...) -> List[Union[str, Example]]: ...
+    def get_doctest(self, string: str, globs: Dict[str, Any], name: str, filename: Optional[str], lineno: Optional[str]) -> DocTest: ...
+    def get_examples(self, strin: str, name: str = ...) -> List[Example]: ...
+
+class DocTestFinder:
+    def __init__(self, verbose: bool = ..., parser: DocTestParser = ...,
+                 recurse: bool = ..., exclude_empty: bool = ...) -> None: ...
+    def find(self, obj: object, name: Optional[str] = ..., module: Union[None, bool, types.ModuleType] = ...,
+             globs: Optional[Dict[str, Any]] = ..., extraglobs: Optional[Dict[str, Any]] = ...) -> List[DocTest]: ...
+
+_Out = Callable[[str], Any]
+_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType]
+
+class DocTestRunner:
+    DIVIDER: str
+    optionflags: int
+    original_optionflags: int
+    tries: int
+    failures: int
+    test: DocTest
+
+    def __init__(self, checker: Optional[OutputChecker] = ..., verbose: Optional[bool] = ..., optionflags: int = ...) -> None: ...
+    def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ...
+    def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...
+    def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...
+    def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ...
+    def run(self, test: DocTest, compileflags: Optional[int] = ..., out: Optional[_Out] = ..., clear_globs: bool = ...) -> TestResults: ...
+    def summarize(self, verbose: Optional[bool] = ...) -> TestResults: ...
+    def merge(self, other: DocTestRunner) -> None: ...
+
+class OutputChecker:
+    def check_output(self, want: str, got: str, optionflags: int) -> bool: ...
+    def output_difference(self, example: Example, got: str, optionflags: int) -> str: ...
+
+class DocTestFailure(Exception):
+    test: DocTest
+    example: Example
+    got: str
+
+    def __init__(self, test: DocTest, example: Example, got: str) -> None: ...
+
+class UnexpectedException(Exception):
+    test: DocTest
+    example: Example
+    exc_info: _ExcInfo
+
+    def __init__(self, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ...
+
+class DebugRunner(DocTestRunner): ...
+
+master: Optional[DocTestRunner]
+
+def testmod(m: Optional[types.ModuleType] = ..., name: Optional[str] = ..., globs: Dict[str, Any] = ..., verbose: Optional[bool] = ...,
+            report: bool = ..., optionflags: int = ..., extraglobs: Dict[str, Any] = ...,
+            raise_on_error: bool = ..., exclude_empty: bool = ...) -> TestResults: ...
+def testfile(filename: str, module_relative: bool = ..., name: Optional[str] = ..., package: Union[None, str, types.ModuleType] = ...,
+             globs: Optional[Dict[str, Any]] = ..., verbose: Optional[bool] = ..., report: bool = ..., optionflags: int = ...,
+             extraglobs: Optional[Dict[str, Any]] = ..., raise_on_error: bool = ..., parser: DocTestParser = ...,
+             encoding: Optional[str] = ...) -> TestResults: ...
+def run_docstring_examples(f: object, globs: Dict[str, Any], verbose: bool = ..., name: str = ...,
+                           compileflags: Optional[int] = ..., optionflags: int = ...) -> None: ...
+def set_unittest_reportflags(flags: int) -> int: ...
+
+class DocTestCase(unittest.TestCase):
+    def __init__(self, test: DocTest, optionflags: int = ..., setUp: Optional[Callable[[DocTest], Any]] = ...,
+                 tearDown: Optional[Callable[[DocTest], Any]] = ...,
+                 checker: Optional[OutputChecker] = ...) -> None: ...
+    def setUp(self) -> None: ...
+    def tearDown(self) -> None: ...
+    def runTest(self) -> None: ...
+    def format_failure(self, err: str) -> str: ...
+    def debug(self) -> None: ...
+    def id(self) -> str: ...
+    def __hash__(self) -> int: ...
+    def shortDescription(self) -> str: ...
+
+class SkipDocTestCase(DocTestCase):
+    def __init__(self, module: types.ModuleType) -> None: ...
+    def setUp(self) -> None: ...
+    def test_skip(self) -> None: ...
+    def shortDescription(self) -> str: ...
+
+if sys.version_info >= (3, 4):
+    class _DocTestSuite(unittest.TestSuite): ...
+else:
+    _DocTestSuite = unittest.TestSuite
+
+def DocTestSuite(module: Union[None, str, types.ModuleType] = ..., globs: Optional[Dict[str, Any]] = ...,
+                 extraglobs: Optional[Dict[str, Any]] = ..., test_finder: Optional[DocTestFinder] = ...,
+                 **options: Any) -> _DocTestSuite: ...
+
+class DocFileCase(DocTestCase):
+    def id(self) -> str: ...
+    def format_failure(self, err: str) -> str: ...
+
+def DocFileTest(path: str, module_relative: bool = ..., package: Union[None, str, types.ModuleType] = ...,
+                globs: Optional[Dict[str, Any]] = ..., parser: DocTestParser = ...,
+                encoding: Optional[str] = ..., **options: Any) -> DocFileCase: ...
+def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ...
+def script_from_examples(s: str) -> str: ...
+def testsource(module: Union[None, str, types.ModuleType], name: str) -> str: ...
+def debug_src(src: str, pm: bool = ..., globs: Optional[Dict[str, Any]] = ...) -> None: ...
+def debug_script(src: str, pm: bool = ..., globs: Optional[Dict[str, Any]] = ...) -> None: ...
+def debug(module: Union[None, str, types.ModuleType], name: str, pm: bool = ...) -> None: ...
diff --git a/typeshed/stdlib/3/fileinput.pyi b/typeshed/stdlib/2and3/fileinput.pyi
similarity index 57%
rename from typeshed/stdlib/3/fileinput.pyi
rename to typeshed/stdlib/2and3/fileinput.pyi
index 9ae4c0f..8a56eca 100644
--- a/typeshed/stdlib/3/fileinput.pyi
+++ b/typeshed/stdlib/2and3/fileinput.pyi
@@ -1,28 +1,29 @@
-from typing import Iterable, Callable, IO, AnyStr, Generic, Any, Union, Iterator, Optional
+from typing import Iterable, Callable, IO, AnyStr, Generic, Any, Text, Union, Iterator, Optional
 
 import os
 import sys
 
 if sys.version_info >= (3, 6):
-    _Path = Union[str, bytes, os.PathLike[Any]]
+    _Path = Union[Text, bytes, os.PathLike[Any]]
 else:
-    _Path = Union[str, bytes]
-_Opener = Callable[[_Path, str], IO[AnyStr]]
+    _Path = Union[Text, bytes]
 
 
 def input(
-    files: Union[str, Iterable[str]]=None,
-    inplace: bool=...,
-    backup: str=...,
-    bufsize: int=...,
-    mode: str=...,
-    openhook: Callable[[str, str], IO[AnyStr]]=...) -> Iterable[AnyStr]: ...
+    files: Union[_Path, Iterable[_Path], None] = ...,
+    inplace: bool = ...,
+    backup: str = ...,
+    bufsize: int = ...,
+    mode: str = ...,
+    openhook: Callable[[_Path, str], IO[AnyStr]] = ...) -> Iterable[AnyStr]: ...
 
 
 def close() -> None: ...
 def nextfile() -> None: ...
 def filename() -> str: ...
 def lineno() -> int: ...
+def filelineno() -> int: ...
+def fileno() -> int: ...
 def isfirstline() -> bool: ...
 def isstdin() -> bool: ...
 
@@ -34,13 +35,14 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]):
         backup: str = ...,
         bufsize: int = ...,
         mode: str = ...,
-        openhook: _Opener[AnyStr] = ...
+        openhook: Callable[[_Path, str], IO[AnyStr]] = ...
     ) -> None: ...
 
     def __del__(self) -> None: ...
     def close(self) -> None: ...
-    def __enter__(self) -> 'FileInput[AnyStr]': ...
-    def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ...
+    if sys.version_info >= (3, 2):
+        def __enter__(self) -> FileInput[AnyStr]: ...
+        def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ...
     def __iter__(self) -> Iterator[AnyStr]: ...
     def __next__(self) -> AnyStr: ...
     def __getitem__(self, i: int) -> AnyStr: ...
@@ -54,4 +56,7 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]):
     def isstdin(self) -> bool: ...
 
 def hook_compressed(filename: _Path, mode: str) -> IO[Any]: ...
-def hook_encoded(encoding: str, errors: Optional[str] = ...) -> _Opener[Any]: ...
+if sys.version_info >= (3, 6):
+    def hook_encoded(encoding: str, errors: Optional[str] = ...) -> Callable[[_Path, str], IO[Any]]: ...
+else:
+    def hook_encoded(encoding: str) -> Callable[[_Path, str], IO[Any]]: ...
diff --git a/typeshed/stdlib/2and3/grp.pyi b/typeshed/stdlib/2and3/grp.pyi
new file mode 100644
index 0000000..6054727
--- /dev/null
+++ b/typeshed/stdlib/2and3/grp.pyi
@@ -0,0 +1,10 @@
+from typing import List, NamedTuple, Optional
+
+struct_group = NamedTuple("struct_group", [("gr_name", str),
+                                           ("gr_passwd", Optional[str]),
+                                           ("gr_gid", int),
+                                           ("gr_mem", List[str])])
+
+def getgrall() -> List[struct_group]: ...
+def getgrgid(gid: int) -> struct_group: ...
+def getgrnam(name: str) -> struct_group: ...
diff --git a/typeshed/stdlib/2and3/linecache.pyi b/typeshed/stdlib/2and3/linecache.pyi
new file mode 100644
index 0000000..9a152d6
--- /dev/null
+++ b/typeshed/stdlib/2and3/linecache.pyi
@@ -0,0 +1,12 @@
+import sys
+from typing import Any, Dict, List, Optional, Text
+
+_ModuleGlobals = Dict[str, Any]
+
+def getline(filename: Text, lineno: int, module_globals: Optional[_ModuleGlobals] = ...) -> str: ...
+def clearcache() -> None: ...
+def getlines(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> None: ...
+def checkcache(filename: Optional[Text] = ...) -> None: ...
+def updatecache(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ...
+if sys.version_info >= (3, 5):
+    def lazycache(filename: Text, module_globals: _ModuleGlobals) -> bool: ...
diff --git a/typeshed/stdlib/2and3/locale.pyi b/typeshed/stdlib/2and3/locale.pyi
index bb64666..59ac3c4 100644
--- a/typeshed/stdlib/2and3/locale.pyi
+++ b/typeshed/stdlib/2and3/locale.pyi
@@ -1,5 +1,6 @@
 # Stubs for locale
 
+from decimal import Decimal
 from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
 import sys
 
@@ -91,7 +92,7 @@ def normalize(localename: _str) -> _str: ...
 def resetlocale(category: int = ...) -> None: ...
 def strcoll(string1: _str, string2: _str) -> int: ...
 def strxfrm(string: _str) -> _str: ...
-def format(format: _str, val: int, grouping: bool = ...,
+def format(format: _str, val: Union[float, Decimal], grouping: bool = ...,
            monetary: bool = ...) -> _str: ...
 def format_string(format: _str, val: Sequence[Any],
                   grouping: bool = ...) -> _str: ...
diff --git a/typeshed/stdlib/2and3/logging/__init__.pyi b/typeshed/stdlib/2and3/logging/__init__.pyi
index 653ec23..ea3c419 100644
--- a/typeshed/stdlib/2and3/logging/__init__.pyi
+++ b/typeshed/stdlib/2and3/logging/__init__.pyi
@@ -13,20 +13,36 @@ import threading
 _SysExcInfoType = Union[Tuple[type, BaseException, TracebackType],
                         Tuple[None, None, None]]
 if sys.version_info >= (3, 5):
-    _ExcInfoType = Union[None, bool, _SysExcInfoType, Exception]
+    _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException]
 else:
     _ExcInfoType = Union[None, bool, _SysExcInfoType]
 _ArgsType = Union[Tuple[Any, ...], Dict[str, Any]]
 _FilterType = Union['Filter', Callable[['LogRecord'], int]]
+_Level = Union[int, Text]
 
+raiseExceptions: bool
 
-class Logger:
+if sys.version_info >= (3,):
+    _levelToName = ...  # type: Dict[int, str]
+    _nameToLevel = ...  # type: Dict[str, int]
+else:
+    _levelNames = ...  # type: dict
+
+class Filterer(object):
+    filters = ...  # type: List[Filter]
+    def __init__(self) -> None: ...
+    def addFilter(self, filter: Filter) -> None: ...
+    def removeFilter(self, filter: Filter) -> None: ...
+    def filter(self, record: 'LogRecord') -> bool: ...
+
+class Logger(Filterer):
     name = ...  # type: str
     level = ...  # type: int
     parent = ...  # type: Union[Logger, PlaceHolder]
     propagate = ...  # type: bool
     handlers = ...  # type: List[Handler]
     disabled = ...  # type: int
+    def __init__(self, name: str, level: _Level = ...) -> None: ...
     def setLevel(self, lvl: Union[int, str]) -> None: ...
     def isEnabledFor(self, lvl: int) -> bool: ...
     def getEffectiveLevel(self) -> int: ...
@@ -110,6 +126,7 @@ class Logger:
 
 
 CRITICAL = ...  # type: int
+FATAL = ...  # type: int
 ERROR = ...  # type: int
 WARNING = ...  # type: int
 WARN = ...  # type: int
@@ -118,19 +135,11 @@ DEBUG = ...  # type: int
 NOTSET = ...  # type: int
 
 
-class Filterer(object):
-    filters = ...  # type: List[Filter]
-    def __init__(self) -> None: ...
-    def addFilter(self, filter: Filter) -> None: ...
-    def removeFilter(self, filter: Filter) -> None: ...
-    def filter(self, record: 'LogRecord') -> bool: ...
-
-
 class Handler(Filterer):
     level = ...  # type: int
     formatter = ...  # type: Optional[Formatter]
     lock = ...  # type: Optional[threading.Lock]
-    def __init__(self, level: int = ...) -> None: ...
+    def __init__(self, level: _Level = ...) -> None: ...
     def createLock(self) -> None: ...
     def acquire(self) -> None: ...
     def release(self) -> None: ...
@@ -322,6 +331,7 @@ else:
                   extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ...
     def log(lvl: int, msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
             extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ...
+fatal = critical
 
 def disable(lvl: int) -> None: ...
 def addLevelName(lvl: int, levelName: str) -> None: ...
@@ -332,7 +342,7 @@ def makeLogRecord(attrdict: Mapping[str, Any]) -> LogRecord: ...
 if sys.version_info >= (3,):
     def basicConfig(*, filename: str = ..., filemode: str = ...,
                     format: str = ..., datefmt: str = ..., style: str = ...,
-                    level: int = ..., stream: IO[str] = ...,
+                    level: _Level = ..., stream: IO[str] = ...,
                     handlers: Iterable[Handler] = ...) -> None: ...
 else:
     @overload
@@ -340,10 +350,13 @@ else:
     @overload
     def basicConfig(*, filename: str = ..., filemode: str = ...,
                     format: str = ..., datefmt: str = ...,
-                    level: int = ..., stream: IO[str] = ...) -> None: ...
+                    level: _Level = ..., stream: IO[str] = ...) -> None: ...
 def shutdown() -> None: ...
 
 def setLoggerClass(klass: type) -> None: ...
+
+def captureWarnings(capture: bool) -> None: ...
+
 if sys.version_info >= (3,):
     def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ...
 
diff --git a/typeshed/stdlib/2and3/logging/config.pyi b/typeshed/stdlib/2and3/logging/config.pyi
index 99f7406..dc5e19e 100644
--- a/typeshed/stdlib/2and3/logging/config.pyi
+++ b/typeshed/stdlib/2and3/logging/config.pyi
@@ -3,9 +3,7 @@
 from typing import Any, Callable, Dict, Optional, IO, Union
 import sys
 if sys.version_info >= (3,):
-    # from configparser import RawConfigParser
-    # TODO add RawConfigParser to configparser stubs
-    RawConfigParser = Any
+    from configparser import RawConfigParser
 else:
     from ConfigParser import RawConfigParser
 
diff --git a/typeshed/stdlib/2and3/logging/handlers.pyi b/typeshed/stdlib/2and3/logging/handlers.pyi
index 6041397..2705d56 100644
--- a/typeshed/stdlib/2and3/logging/handlers.pyi
+++ b/typeshed/stdlib/2and3/logging/handlers.pyi
@@ -11,7 +11,7 @@ if sys.version_info >= (3,):
 else:
     from Queue import Queue
 # TODO update socket stubs to add SocketKind
-SocketKind = int
+_SocketKind = int
 
 
 class WatchedFileHandler(Handler):
@@ -122,7 +122,7 @@ class SysLogHandler(Handler):
     LOG_LOCAL6 = ...  # type: int
     LOG_LOCAL7 = ...  # type: int
     def __init__(self, address: Union[Tuple[str, int], str] = ...,
-            facility: int = ..., socktype: SocketKind = ...) -> None: ...
+            facility: int = ..., socktype: _SocketKind = ...) -> None: ...
     def encodePriority(self, facility: Union[int, str],
                        priority: Union[int, str]) -> int: ...
     def mapPriority(self, levelName: int) -> str: ...
diff --git a/typeshed/stdlib/2and3/numbers.pyi b/typeshed/stdlib/2and3/numbers.pyi
index e4f7603..2a3f493 100644
--- a/typeshed/stdlib/2and3/numbers.pyi
+++ b/typeshed/stdlib/2and3/numbers.pyi
@@ -5,7 +5,7 @@
 # Note: these stubs are incomplete. The more complex type
 # signatures are currently omitted.
 
-from typing import Any, Optional, TypeVar
+from typing import Any, Optional, TypeVar, SupportsFloat
 from abc import ABCMeta, abstractmethod
 import sys
 
@@ -59,7 +59,7 @@ class Complex(Number):
     if sys.version_info < (3, 0):
         def __ne__(self, other: object) -> bool: ...
 
-class Real(Complex):
+class Real(Complex, SupportsFloat):
     @abstractmethod
     def __float__(self) -> float: ...
     @abstractmethod
diff --git a/typeshed/stdlib/2and3/optparse.pyi b/typeshed/stdlib/2and3/optparse.pyi
index fe7f437..2e52647 100644
--- a/typeshed/stdlib/2and3/optparse.pyi
+++ b/typeshed/stdlib/2and3/optparse.pyi
@@ -14,7 +14,7 @@ SUPPRESS_USAGE = ...  # type: _Text
 
 def check_builtin(option: Option, opt: Any, value: _Text) -> Any: ...
 def check_choice(option: Option, opt: Any, value: _Text) -> Any: ...
-if sys.version_info >= (3,):
+if sys.version_info < (3,):
     def isbasestring(x: Any) -> bool: ...
 
 class OptParseError(Exception):
@@ -152,7 +152,7 @@ class OptionGroup(OptionContainer):
     option_list = ...  # type: List[Option]
     parser = ...  # type: OptionParser
     title = ...  # type: _Text
-    def __init__(self, parser: OptionParser, title: _Text, description: Optional[_Text]) -> None: ...
+    def __init__(self, parser: OptionParser, title: _Text, description: Optional[_Text] = ...) -> None: ...
     def _create_option_list(self) -> None: ...
     def set_title(self, title: _Text) -> None: ...
 
diff --git a/typeshed/stdlib/2and3/pdb.pyi b/typeshed/stdlib/2and3/pdb.pyi
new file mode 100644
index 0000000..226436b
--- /dev/null
+++ b/typeshed/stdlib/2and3/pdb.pyi
@@ -0,0 +1,30 @@
+# NOTE: This stub is incomplete - only contains some global functions
+
+from typing import Any, Dict, Optional
+
+def run(statement: str,
+        globals: Optional[Dict[str, Any]] = None,
+        locals: Optional[Dict[str, Any]] = None) -> None:
+    ...
+
+def runeval(expression: str,
+            globals: Optional[Dict[str, Any]] = None,
+            locals: Optional[Dict[str, Any]] = None) -> Any:
+    ...
+
+def runctx(statement: str,
+        globals: Dict[str, Any],
+        locals: Dict[str, Any]) -> None:
+    ...
+
+def runcall(*args: Any, **kwds: Any) -> Any:
+    ...
+
+def set_trace() -> None:
+    ...
+
+def post_mortem(t: Optional[Any] = None) -> None:
+    ...
+
+def pm() -> None:
+    ...
diff --git a/typeshed/stdlib/2and3/pickle.pyi b/typeshed/stdlib/2and3/pickle.pyi
new file mode 100644
index 0000000..7bfad8f
--- /dev/null
+++ b/typeshed/stdlib/2and3/pickle.pyi
@@ -0,0 +1,140 @@
+import sys
+from typing import Any, IO, Mapping, Union, Tuple, Callable, Optional, Iterator
+
+HIGHEST_PROTOCOL: int
+if sys.version_info >= (3, 0):
+    DEFAULT_PROTOCOL: int
+
+
+if sys.version_info >= (3, 0):
+    def dump(obj: Any, file: IO[bytes], protocol: Optional[int] = ..., *,
+             fix_imports: bool = ...) -> None: ...
+    def dumps(obj: Any, protocol: Optional[int] = ..., *,
+              fix_imports: bool = ...) -> bytes: ...
+    def loads(bytes_object: bytes, *, fix_imports: bool = ...,
+              encoding: str = ..., errors: str = ...) -> Any: ...
+    def load(file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ...,
+             errors: str = ...) -> Any: ...
+else:
+    def dump(obj: Any, file: IO[bytes], protocol: Optional[int] = ...) -> None: ...
+    def dumps(obj: Any, protocol: Optional[int] = ...) -> bytes: ...
+    def load(file: IO[bytes]) -> Any: ...
+    def loads(string: bytes) -> Any: ...
+
+class PickleError(Exception): ...
+class PicklingError(PickleError): ...
+class UnpicklingError(PickleError): ...
+
+_reducedtype = Union[str,
+                     Tuple[Callable[..., Any], Tuple],
+                     Tuple[Callable[..., Any], Tuple, Any],
+                     Tuple[Callable[..., Any], Tuple, Any,
+                           Optional[Iterator]],
+                     Tuple[Callable[..., Any], Tuple, Any,
+                           Optional[Iterator], Optional[Iterator]]]
+
+
+class Pickler:
+    fast: bool
+    if sys.version_info >= (3, 3):
+        dispatch_table: Mapping[type, Callable[[Any], _reducedtype]]
+
+    if sys.version_info >= (3, 0):
+        def __init__(self, file: IO[bytes], protocol: Optional[int] = ..., *,
+                     fix_imports: bool = ...) -> None: ...
+    else:
+        def __init__(self, file: IO[bytes], protocol: Optional[int] = ...) -> None: ...
+
+    def dump(self, obj: Any) -> None: ...
+    def clear_memo(self) -> None: ...
+    def persistent_id(self, obj: Any) -> Any: ...
+
+
+class Unpickler:
+    if sys.version_info >= (3, 0):
+        def __init__(self, file: IO[bytes], *, fix_imports: bool = ...,
+                     encoding: str = ..., errors: str = ...) -> None: ...
+    else:
+        def __init__(self, file: IO[bytes]) -> None: ...
+
+    def load(self) -> Any: ...
+    def find_class(self, module: str, name: str) -> Any: ...
+    if sys.version_info >= (3, 0):
+        def persistent_load(self, pid: Any) -> Any: ...
+
+MARK: bytes
+STOP: bytes
+POP: bytes
+POP_MARK: bytes
+DUP: bytes
+FLOAT: bytes
+INT: bytes
+BININT: bytes
+BININT1: bytes
+LONG: bytes
+BININT2: bytes
+NONE: bytes
+PERSID: bytes
+BINPERSID: bytes
+REDUCE: bytes
+STRING: bytes
+BINSTRING: bytes
+SHORT_BINSTRING: bytes
+UNICODE: bytes
+BINUNICODE: bytes
+APPEND: bytes
+BUILD: bytes
+GLOBAL: bytes
+DICT: bytes
+EMPTY_DICT: bytes
+APPENDS: bytes
+GET: bytes
+BINGET: bytes
+INST: bytes
+LONG_BINGET: bytes
+LIST: bytes
+EMPTY_LIST: bytes
+OBJ: bytes
+PUT: bytes
+BINPUT: bytes
+LONG_BINPUT: bytes
+SETITEM: bytes
+TUPLE: bytes
+EMPTY_TUPLE: bytes
+SETITEMS: bytes
+BINFLOAT: bytes
+
+TRUE: bytes
+FALSE: bytes
+
+# protocol 2
+PROTO: bytes
+NEWOBJ: bytes
+EXT1: bytes
+EXT2: bytes
+EXT4: bytes
+TUPLE1: bytes
+TUPLE2: bytes
+TUPLE3: bytes
+NEWTRUE: bytes
+NEWFALSE: bytes
+LONG1: bytes
+LONG4: bytes
+
+if sys.version_info >= (3, 0):
+    # protocol 3
+    BINBYTES: bytes
+    SHORT_BINBYTES: bytes
+
+if sys.version_info >= (3, 4):
+    # protocol 4
+    SHORT_BINUNICODE: bytes
+    BINUNICODE8: bytes
+    BINBYTES8: bytes
+    EMPTY_SET: bytes
+    ADDITEMS: bytes
+    FROZENSET: bytes
+    NEWOBJ_EX: bytes
+    STACK_GLOBAL: bytes
+    MEMOIZE: bytes
+    FRAME: bytes
diff --git a/typeshed/stdlib/2and3/pstats.pyi b/typeshed/stdlib/2and3/pstats.pyi
index 2321391..8bf1b0d 100644
--- a/typeshed/stdlib/2and3/pstats.pyi
+++ b/typeshed/stdlib/2and3/pstats.pyi
@@ -1,5 +1,5 @@
 from profile import Profile
-from cProfile import Profile as cProfile
+from cProfile import Profile as _cProfile
 import os
 import sys
 from typing import Any, Dict, IO, Iterable, List, Text, Tuple, TypeVar, Union, overload
@@ -12,13 +12,13 @@ else:
     _Path = Union[bytes, Text]
 
 class Stats:
-    def __init__(self: _T, __arg: Union[None, str, Text, Profile, cProfile] = ...,
-                 *args: Union[None, str, Text, Profile, cProfile, _T],
+    def __init__(self: _T, __arg: Union[None, str, Text, Profile, _cProfile] = ...,
+                 *args: Union[None, str, Text, Profile, _cProfile, _T],
                  stream: IO[Any] = ...) -> None: ...
-    def init(self, arg: Union[None, str, Text, Profile, cProfile]) -> None: ...
-    def load_stats(self, arg: Union[None, str, Text, Profile, cProfile]) -> None: ...
+    def init(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ...
+    def load_stats(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ...
     def get_top_level_stats(self) -> None: ...
-    def add(self: _T, *arg_list: Union[None, str, Text, Profile, cProfile, _T]) -> _T: ...
+    def add(self: _T, *arg_list: Union[None, str, Text, Profile, _cProfile, _T]) -> _T: ...
     def dump_stats(self, filename: _Path) -> None: ...
     def get_sort_arg_defs(self) -> Dict[str, Tuple[Tuple[Tuple[int, int], ...], str]]: ...
     @overload
diff --git a/typeshed/stdlib/2and3/pwd.pyi b/typeshed/stdlib/2and3/pwd.pyi
new file mode 100644
index 0000000..5bd0bbb
--- /dev/null
+++ b/typeshed/stdlib/2and3/pwd.pyi
@@ -0,0 +1,13 @@
+from typing import List, NamedTuple
+
+struct_passwd = NamedTuple("struct_passwd", [("pw_name", str),
+                                             ("pw_passwd", str),
+                                             ("pw_uid", int),
+                                             ("pw_gid", int),
+                                             ("pw_gecos", str),
+                                             ("pw_dir", str),
+                                             ("pw_shell", str)])
+
+def getpwall() -> List[struct_passwd]: ...
+def getpwuid(uid: int) -> struct_passwd: ...
+def getpwnam(name: str) -> struct_passwd: ...
diff --git a/typeshed/stdlib/2and3/sched.pyi b/typeshed/stdlib/2and3/sched.pyi
index 7222d13..b8e7b2b 100644
--- a/typeshed/stdlib/2and3/sched.pyi
+++ b/typeshed/stdlib/2and3/sched.pyi
@@ -1,5 +1,3 @@
-# Stub for sched (Python 2 and 3)
-
 import sys
 from typing import Any, Callable, Dict, List, NamedTuple, Text, Tuple
 
diff --git a/typeshed/stdlib/2and3/select.pyi b/typeshed/stdlib/2and3/select.pyi
new file mode 100644
index 0000000..ab9ffc6
--- /dev/null
+++ b/typeshed/stdlib/2and3/select.pyi
@@ -0,0 +1,137 @@
+import sys
+from typing import Any, Optional, Sequence, Tuple, Iterable, List, Union
+
+# When we have protocols, this should change to a protocol with a fileno method
+# See https://docs.python.org/3/c-api/file.html#c.PyObject_AsFileDescriptor
+_FileDescriptor = Union[int, Any]
+
+EPOLLERR: int
+EPOLLET: int
+EPOLLHUP: int
+EPOLLIN: int
+EPOLLMSG: int
+EPOLLONESHOT: int
+EPOLLOUT: int
+EPOLLPRI: int
+EPOLLRDBAND: int
+EPOLLRDNORM: int
+EPOLLWRBAND: int
+EPOLLWRNORM: int
+EPOLL_RDHUP: int
+KQ_EV_ADD: int
+KQ_EV_CLEAR: int
+KQ_EV_DELETE: int
+KQ_EV_DISABLE: int
+KQ_EV_ENABLE: int
+KQ_EV_EOF: int
+KQ_EV_ERROR: int
+KQ_EV_FLAG1: int
+KQ_EV_ONESHOT: int
+KQ_EV_SYSFLAGS: int
+KQ_FILTER_AIO: int
+KQ_FILTER_NETDEV: int
+KQ_FILTER_PROC: int
+KQ_FILTER_READ: int
+KQ_FILTER_SIGNAL: int
+KQ_FILTER_TIMER: int
+KQ_FILTER_VNODE: int
+KQ_FILTER_WRITE: int
+KQ_NOTE_ATTRIB: int
+KQ_NOTE_CHILD: int
+KQ_NOTE_DELETE: int
+KQ_NOTE_EXEC: int
+KQ_NOTE_EXIT: int
+KQ_NOTE_EXTEND: int
+KQ_NOTE_FORK: int
+KQ_NOTE_LINK: int
+KQ_NOTE_LINKDOWN: int
+KQ_NOTE_LINKINV: int
+KQ_NOTE_LINKUP: int
+KQ_NOTE_LOWAT: int
+KQ_NOTE_PCTRLMASK: int
+KQ_NOTE_PDATAMASK: int
+KQ_NOTE_RENAME: int
+KQ_NOTE_REVOKE: int
+KQ_NOTE_TRACK: int
+KQ_NOTE_TRACKERR: int
+KQ_NOTE_WRITE: int
+PIPE_BUF: int
+POLLERR: int
+POLLHUP: int
+POLLIN: int
+POLLMSG: int
+POLLNVAL: int
+POLLOUT: int
+POLLPRI: int
+POLLRDBAND: int
+POLLRDNORM: int
+POLLWRBAND: int
+POLLWRNORM: int
+
+class poll:
+    def __init__(self) -> None: ...
+    def register(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ...
+    def modify(self, fd: _FileDescriptor, eventmask: int) -> None: ...
+    def unregister(self, fd: _FileDescriptor) -> None: ...
+    def poll(self, timeout: Optional[float] = ...) -> List[Tuple[int, int]]: ...
+
+def select(rlist: Sequence[Any], wlist: Sequence[Any], xlist: Sequence[Any],
+           timeout: Optional[float] = ...) -> Tuple[List[Any],
+                                                    List[Any],
+                                                    List[Any]]: ...
+
+if sys.version_info >= (3, 3):
+    error = OSError
+else:
+    class error(Exception): ...
+
+# BSD only
+class kevent(object):
+    data: Any
+    fflags: int
+    filter: int
+    flags: int
+    ident: int
+    udata: Any
+    def __init__(self, ident: _FileDescriptor, filter: int = ..., flags: int = ..., fflags: int = ..., data: Any = ..., udata: Any = ...) -> None: ...
+
+# BSD only
+class kqueue(object):
+    closed: bool
+    def __init__(self) -> None: ...
+    def close(self) -> None: ...
+    def control(self, changelist: Optional[Iterable[kevent]], max_events: int, timeout: float = ...) -> List[kevent]: ...
+    def fileno(self) -> int: ...
+    @classmethod
+    def fromfd(cls, fd: _FileDescriptor) -> kqueue: ...
+
+# Linux only
+class epoll(object):
+    if sys.version_info >= (3, 3):
+        def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ...
+    else:
+        def __init__(self, sizehint: int = ...) -> None: ...
+    if sys.version_info >= (3, 4):
+        def __enter__(self) -> epoll: ...
+        def __exit__(self, *args: Any) -> None: ...
+    def close(self) -> None: ...
+    closed: bool
+    def fileno(self) -> int: ...
+    def register(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ...
+    def modify(self, fd: _FileDescriptor, eventmask: int) -> None: ...
+    def unregister(self, fd: _FileDescriptor) -> None: ...
+    def poll(self, timeout: float = ..., maxevents: int = ...) -> List[Tuple[int, int]]: ...
+    @classmethod
+    def fromfd(cls, fd: _FileDescriptor) -> epoll: ...
+
+if sys.version_info >= (3, 3):
+    # Solaris only
+    class devpoll:
+        if sys.version_info >= (3, 4):
+            def close(self) -> None: ...
+            closed: bool
+            def fileno(self) -> int: ...
+        def register(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ...
+        def modify(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ...
+        def unregister(self, fd: _FileDescriptor) -> None: ...
+        def poll(self, timeout: Optional[float] = ...) -> List[Tuple[int, int]]: ...
diff --git a/typeshed/stdlib/2and3/smtpd.pyi b/typeshed/stdlib/2and3/smtpd.pyi
index f4339c0..923b8bc 100644
--- a/typeshed/stdlib/2and3/smtpd.pyi
+++ b/typeshed/stdlib/2and3/smtpd.pyi
@@ -47,7 +47,7 @@ class SMTPChannel(asynchat.async_chat):
                      map: Optional[asyncore._maptype] = ...) -> None: ...
     else:
         def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ...) -> None: ...
-    def push(self, msg: Text) -> None: ...
+    def push(self, msg: bytes) -> None: ...
     def collect_incoming_data(self, data: bytes) -> None: ...
     def found_terminator(self) -> None: ...
     def smtp_HELO(self, arg: str) -> None: ...
diff --git a/typeshed/stdlib/2and3/socket.pyi b/typeshed/stdlib/2and3/socket.pyi
index 93052b8..37488fd 100644
--- a/typeshed/stdlib/2and3/socket.pyi
+++ b/typeshed/stdlib/2and3/socket.pyi
@@ -6,250 +6,404 @@
 # see: http://nullege.com/codes/search/socket
 # adapted for Python 2.7 by Michal Pokorny
 import sys
-from typing import Any, Tuple, List, Optional, Union, overload
+from typing import Any, Tuple, List, Optional, Union, overload, TypeVar
+
 
 # ----- variables and constants -----
 
-AF_UNIX = 0
-AF_INET = 0
-AF_INET6 = 0
-SOCK_STREAM = 0
-SOCK_DGRAM = 0
-SOCK_RAW = 0
-SOCK_RDM = 0
-SOCK_SEQPACKET = 0
-SOCK_CLOEXEC = 0
-SOCK_NONBLOCK = 0
-SOMAXCONN = 0
-has_ipv6 = False
-_GLOBAL_DEFAULT_TIMEOUT = ...  # type: Any
-SocketType = ...  # type: Any
-SocketIO = ...  # type: Any
-
-
-# the following constants are included with Python 3.2.3 (Ubuntu)
-# some of the constants may be Linux-only
-# all Windows/Mac-specific constants are absent
-AF_APPLETALK = 0
-AF_ASH = 0
-AF_ATMPVC = 0
-AF_ATMSVC = 0
-AF_AX25 = 0
-AF_BLUETOOTH = 0
-AF_BRIDGE = 0
-AF_DECnet = 0
-AF_ECONET = 0
-AF_IPX = 0
-AF_IRDA = 0
-AF_KEY = 0
-AF_LLC = 0
-AF_NETBEUI = 0
-AF_NETLINK = 0
-AF_NETROM = 0
-AF_PACKET = 0
-AF_PPPOX = 0
-AF_ROSE = 0
-AF_ROUTE = 0
-AF_SECURITY = 0
-AF_SNA = 0
-AF_TIPC = 0
-AF_UNSPEC = 0
-AF_WANPIPE = 0
-AF_X25 = 0
-AI_ADDRCONFIG = 0
-AI_ALL = 0
-AI_CANONNAME = 0
-AI_NUMERICHOST = 0
-AI_NUMERICSERV = 0
-AI_PASSIVE = 0
-AI_V4MAPPED = 0
-BDADDR_ANY = 0
-BDADDR_LOCAL = 0
-BTPROTO_HCI = 0
-BTPROTO_L2CAP = 0
-BTPROTO_RFCOMM = 0
-BTPROTO_SCO = 0
-CAPI = 0
-EAGAIN = 0
-EAI_ADDRFAMILY = 0
-EAI_AGAIN = 0
-EAI_BADFLAGS = 0
-EAI_FAIL = 0
-EAI_FAMILY = 0
-EAI_MEMORY = 0
-EAI_NODATA = 0
-EAI_NONAME = 0
-EAI_OVERFLOW = 0
-EAI_SERVICE = 0
-EAI_SOCKTYPE = 0
-EAI_SYSTEM = 0
-EBADF = 0
-EINTR = 0
-EWOULDBLOCK = 0
-HCI_DATA_DIR = 0
-HCI_FILTER = 0
-HCI_TIME_STAMP = 0
-INADDR_ALLHOSTS_GROUP = 0
-INADDR_ANY = 0
-INADDR_BROADCAST = 0
-INADDR_LOOPBACK = 0
-INADDR_MAX_LOCAL_GROUP = 0
-INADDR_NONE = 0
-INADDR_UNSPEC_GROUP = 0
-IPPORT_RESERVED = 0
-IPPORT_USERRESERVED = 0
-IPPROTO_AH = 0
-IPPROTO_DSTOPTS = 0
-IPPROTO_EGP = 0
-IPPROTO_ESP = 0
-IPPROTO_FRAGMENT = 0
-IPPROTO_GRE = 0
-IPPROTO_HOPOPTS = 0
-IPPROTO_ICMP = 0
-IPPROTO_ICMPV6 = 0
-IPPROTO_IDP = 0
-IPPROTO_IGMP = 0
-IPPROTO_IP = 0
-IPPROTO_IPIP = 0
-IPPROTO_IPV6 = 0
-IPPROTO_NONE = 0
-IPPROTO_PIM = 0
-IPPROTO_PUP = 0
-IPPROTO_RAW = 0
-IPPROTO_ROUTING = 0
-IPPROTO_RSVP = 0
-IPPROTO_TCP = 0
-IPPROTO_TP = 0
-IPPROTO_UDP = 0
-IPV6_CHECKSUM = 0
-IPV6_DSTOPTS = 0
-IPV6_HOPLIMIT = 0
-IPV6_HOPOPTS = 0
-IPV6_JOIN_GROUP = 0
-IPV6_LEAVE_GROUP = 0
-IPV6_MULTICAST_HOPS = 0
-IPV6_MULTICAST_IF = 0
-IPV6_MULTICAST_LOOP = 0
-IPV6_NEXTHOP = 0
-IPV6_PKTINFO = 0
-IPV6_RECVDSTOPTS = 0
-IPV6_RECVHOPLIMIT = 0
-IPV6_RECVHOPOPTS = 0
-IPV6_RECVPKTINFO = 0
-IPV6_RECVRTHDR = 0
-IPV6_RECVTCLASS = 0
-IPV6_RTHDR = 0
-IPV6_RTHDRDSTOPTS = 0
-IPV6_RTHDR_TYPE_0 = 0
-IPV6_TCLASS = 0
-IPV6_UNICAST_HOPS = 0
-IPV6_V6ONLY = 0
-IP_ADD_MEMBERSHIP = 0
-IP_DEFAULT_MULTICAST_LOOP = 0
-IP_DEFAULT_MULTICAST_TTL = 0
-IP_DROP_MEMBERSHIP = 0
-IP_HDRINCL = 0
-IP_MAX_MEMBERSHIPS = 0
-IP_MULTICAST_IF = 0
-IP_MULTICAST_LOOP = 0
-IP_MULTICAST_TTL = 0
-IP_OPTIONS = 0
-IP_RECVOPTS = 0
-IP_RECVRETOPTS = 0
-IP_RETOPTS = 0
-IP_TOS = 0
-IP_TTL = 0
-MSG_CTRUNC = 0
-MSG_DONTROUTE = 0
-MSG_DONTWAIT = 0
-MSG_EOR = 0
-MSG_OOB = 0
-MSG_PEEK = 0
-MSG_TRUNC = 0
-MSG_WAITALL = 0
-NETLINK_DNRTMSG = 0
-NETLINK_FIREWALL = 0
-NETLINK_IP6_FW = 0
-NETLINK_NFLOG = 0
-NETLINK_ROUTE = 0
-NETLINK_USERSOCK = 0
-NETLINK_XFRM = 0
-NI_DGRAM = 0
-NI_MAXHOST = 0
-NI_MAXSERV = 0
-NI_NAMEREQD = 0
-NI_NOFQDN = 0
-NI_NUMERICHOST = 0
-NI_NUMERICSERV = 0
-PACKET_BROADCAST = 0
-PACKET_FASTROUTE = 0
-PACKET_HOST = 0
-PACKET_LOOPBACK = 0
-PACKET_MULTICAST = 0
-PACKET_OTHERHOST = 0
-PACKET_OUTGOING = 0
-PF_PACKET = 0
-SHUT_RD = 0
-SHUT_RDWR = 0
-SHUT_WR = 0
-SOL_HCI = 0
-SOL_IP = 0
-SOL_SOCKET = 0
-SOL_TCP = 0
-SOL_TIPC = 0
-SOL_UDP = 0
-SO_ACCEPTCONN = 0
-SO_BROADCAST = 0
-SO_DEBUG = 0
-SO_DONTROUTE = 0
-SO_ERROR = 0
-SO_KEEPALIVE = 0
-SO_LINGER = 0
-SO_OOBINLINE = 0
-SO_RCVBUF = 0
-SO_RCVLOWAT = 0
-SO_RCVTIMEO = 0
-SO_REUSEADDR = 0
-SO_SNDBUF = 0
-SO_SNDLOWAT = 0
-SO_SNDTIMEO = 0
-SO_TYPE = 0
-TCP_CORK = 0
-TCP_DEFER_ACCEPT = 0
-TCP_INFO = 0
-TCP_KEEPCNT = 0
-TCP_KEEPIDLE = 0
-TCP_KEEPINTVL = 0
-TCP_LINGER2 = 0
-TCP_MAXSEG = 0
-TCP_NODELAY = 0
-TCP_QUICKACK = 0
-TCP_SYNCNT = 0
-TCP_WINDOW_CLAMP = 0
-TIPC_ADDR_ID = 0
-TIPC_ADDR_NAME = 0
-TIPC_ADDR_NAMESEQ = 0
-TIPC_CFG_SRV = 0
-TIPC_CLUSTER_SCOPE = 0
-TIPC_CONN_TIMEOUT = 0
-TIPC_CRITICAL_IMPORTANCE = 0
-TIPC_DEST_DROPPABLE = 0
-TIPC_HIGH_IMPORTANCE = 0
-TIPC_IMPORTANCE = 0
-TIPC_LOW_IMPORTANCE = 0
-TIPC_MEDIUM_IMPORTANCE = 0
-TIPC_NODE_SCOPE = 0
-TIPC_PUBLISHED = 0
-TIPC_SRC_DROPPABLE = 0
-TIPC_SUBSCR_TIMEOUT = 0
-TIPC_SUB_CANCEL = 0
-TIPC_SUB_PORTS = 0
-TIPC_SUB_SERVICE = 0
-TIPC_TOP_SRV = 0
-TIPC_WAIT_FOREVER = 0
-TIPC_WITHDRAWN = 0
-TIPC_ZONE_SCOPE = 0
+AF_UNIX: int
+AF_INET: int
+AF_INET6: int
+SOCK_STREAM: int
+SOCK_DGRAM: int
+SOCK_RAW: int
+SOCK_RDM: int
+SOCK_SEQPACKET: int
+SOCK_CLOEXEC: int
+SOCK_NONBLOCK: int
+SOMAXCONN: int
+has_ipv6: bool
+_GLOBAL_DEFAULT_TIMEOUT: Any
+SocketType: Any
+SocketIO: Any
+
+# These are flags that may exist on Python 3.6. Many don't exist on all platforms.
+AF_AAL5: int
+AF_APPLETALK: int
+AF_ASH: int
+AF_ATMPVC: int
+AF_ATMSVC: int
+AF_AX25: int
+AF_BLUETOOTH: int
+AF_BRIDGE: int
+AF_CAN: int
+AF_DECnet: int
+AF_ECONET: int
+AF_IPX: int
+AF_IRDA: int
+AF_KEY: int
+AF_LLC: int
+AF_NETBEUI: int
+AF_NETLINK: int
+AF_NETROM: int
+AF_PACKET: int
+AF_PPPOX: int
+AF_RDS: int
+AF_ROSE: int
+AF_ROUTE: int
+AF_SECURITY: int
+AF_SNA: int
+AF_SYSTEM: int
+AF_TIPC: int
+AF_UNSPEC: int
+AF_WANPIPE: int
+AF_X25: int
+AI_ADDRCONFIG: int
+AI_ALL: int
+AI_CANONNAME: int
+AI_DEFAULT: int
+AI_MASK: int
+AI_NUMERICHOST: int
+AI_NUMERICSERV: int
+AI_PASSIVE: int
+AI_V4MAPPED: int
+AI_V4MAPPED_CFG: int
+BDADDR_ANY: str
+BDADDR_LOCAL: str
+BTPROTO_HCI: int
+BTPROTO_L2CAP: int
+BTPROTO_RFCOMM: int
+BTPROTO_SCO: int
+CAN_EFF_FLAG: int
+CAN_EFF_MASK: int
+CAN_ERR_FLAG: int
+CAN_ERR_MASK: int
+CAN_RAW: int
+CAN_RAW_ERR_FILTER: int
+CAN_RAW_FILTER: int
+CAN_RAW_LOOPBACK: int
+CAN_RAW_RECV_OWN_MSGS: int
+CAN_RTR_FLAG: int
+CAN_SFF_MASK: int
+CAPI: int
+EAGAIN: int
+EAI_ADDRFAMILY: int
+EAI_AGAIN: int
+EAI_BADFLAGS: int
+EAI_BADHINTS: int
+EAI_FAIL: int
+EAI_FAMILY: int
+EAI_MAX: int
+EAI_MEMORY: int
+EAI_NODATA: int
+EAI_NONAME: int
+EAI_OVERFLOW: int
+EAI_PROTOCOL: int
+EAI_SERVICE: int
+EAI_SOCKTYPE: int
+EAI_SYSTEM: int
+EBADF: int
+EINTR: int
+EWOULDBLOCK: int
+HCI_DATA_DIR: int
+HCI_FILTER: int
+HCI_TIME_STAMP: int
+INADDR_ALLHOSTS_GROUP: int
+INADDR_ANY: int
+INADDR_BROADCAST: int
+INADDR_LOOPBACK: int
+INADDR_MAX_LOCAL_GROUP: int
+INADDR_NONE: int
+INADDR_UNSPEC_GROUP: int
+IPPORT_RESERVED: int
+IPPORT_USERRESERVED: int
+IPPROTO_AH: int
+IPPROTO_BIP: int
+IPPROTO_DSTOPTS: int
+IPPROTO_EGP: int
+IPPROTO_EON: int
+IPPROTO_ESP: int
+IPPROTO_FRAGMENT: int
+IPPROTO_GGP: int
+IPPROTO_GRE: int
+IPPROTO_HELLO: int
+IPPROTO_HOPOPTS: int
+IPPROTO_ICMP: int
+IPPROTO_ICMPV6: int
+IPPROTO_IDP: int
+IPPROTO_IGMP: int
+IPPROTO_IP: int
+IPPROTO_IPCOMP: int
+IPPROTO_IPIP: int
+IPPROTO_IPV4: int
+IPPROTO_IPV6: int
+IPPROTO_MAX: int
+IPPROTO_MOBILE: int
+IPPROTO_ND: int
+IPPROTO_NONE: int
+IPPROTO_PIM: int
+IPPROTO_PUP: int
+IPPROTO_RAW: int
+IPPROTO_ROUTING: int
+IPPROTO_RSVP: int
+IPPROTO_SCTP: int
+IPPROTO_TCP: int
+IPPROTO_TP: int
+IPPROTO_UDP: int
+IPPROTO_VRRP: int
+IPPROTO_XTP: int
+IPV6_CHECKSUM: int
+IPV6_DONTFRAG: int
+IPV6_DSTOPTS: int
+IPV6_HOPLIMIT: int
+IPV6_HOPOPTS: int
+IPV6_JOIN_GROUP: int
+IPV6_LEAVE_GROUP: int
+IPV6_MULTICAST_HOPS: int
+IPV6_MULTICAST_IF: int
+IPV6_MULTICAST_LOOP: int
+IPV6_NEXTHOP: int
+IPV6_PATHMTU: int
+IPV6_PKTINFO: int
+IPV6_RECVDSTOPTS: int
+IPV6_RECVHOPLIMIT: int
+IPV6_RECVHOPOPTS: int
+IPV6_RECVPATHMTU: int
+IPV6_RECVPKTINFO: int
+IPV6_RECVRTHDR: int
+IPV6_RECVTCLASS: int
+IPV6_RTHDR: int
+IPV6_RTHDR_TYPE_0: int
+IPV6_RTHDRDSTOPTS: int
+IPV6_TCLASS: int
+IPV6_UNICAST_HOPS: int
+IPV6_USE_MIN_MTU: int
+IPV6_V6ONLY: int
+IP_ADD_MEMBERSHIP: int
+IP_DEFAULT_MULTICAST_LOOP: int
+IP_DEFAULT_MULTICAST_TTL: int
+IP_DROP_MEMBERSHIP: int
+IP_HDRINCL: int
+IP_MAX_MEMBERSHIPS: int
+IP_MULTICAST_IF: int
+IP_MULTICAST_LOOP: int
+IP_MULTICAST_TTL: int
+IP_OPTIONS: int
+IP_RECVDSTADDR: int
+IP_RECVOPTS: int
+IP_RECVRETOPTS: int
+IP_RETOPTS: int
+IP_TOS: int
+IP_TRANSPARENT: int
+IP_TTL: int
+IPX_TYPE: int
+LOCAL_PEERCRED: int
+MSG_BCAST: int
+MSG_BTAG: int
+MSG_CMSG_CLOEXEC: int
+MSG_CONFIRM: int
+MSG_CTRUNC: int
+MSG_DONTROUTE: int
+MSG_DONTWAIT: int
+MSG_EOF: int
+MSG_EOR: int
+MSG_ERRQUEUE: int
+MSG_ETAG: int
+MSG_FASTOPEN: int
+MSG_MCAST: int
+MSG_MORE: int
+MSG_NOSIGNAL: int
+MSG_NOTIFICATION: int
+MSG_OOB: int
+MSG_PEEK: int
+MSG_TRUNC: int
+MSG_WAITALL: int
+NETLINK_ARPD: int
+NETLINK_CRYPTO: int
+NETLINK_DNRTMSG: int
+NETLINK_FIREWALL: int
+NETLINK_IP6_FW: int
+NETLINK_NFLOG: int
+NETLINK_ROUTE6: int
+NETLINK_ROUTE: int
+NETLINK_SKIP: int
+NETLINK_TAPBASE: int
+NETLINK_TCPDIAG: int
+NETLINK_USERSOCK: int
+NETLINK_W1: int
+NETLINK_XFRM: int
+NI_DGRAM: int
+NI_MAXHOST: int
+NI_MAXSERV: int
+NI_NAMEREQD: int
+NI_NOFQDN: int
+NI_NUMERICHOST: int
+NI_NUMERICSERV: int
+PACKET_BROADCAST: int
+PACKET_FASTROUTE: int
+PACKET_HOST: int
+PACKET_LOOPBACK: int
+PACKET_MULTICAST: int
+PACKET_OTHERHOST: int
+PACKET_OUTGOING: int
+PF_CAN: int
+PF_PACKET: int
+PF_RDS: int
+PF_SYSTEM: int
+SCM_CREDENTIALS: int
+SCM_CREDS: int
+SCM_RIGHTS: int
+SHUT_RD: int
+SHUT_RDWR: int
+SHUT_WR: int
+SOL_ATALK: int
+SOL_AX25: int
+SOL_CAN_BASE: int
+SOL_CAN_RAW: int
+SOL_HCI: int
+SOL_IP: int
+SOL_IPX: int
+SOL_NETROM: int
+SOL_RDS: int
+SOL_ROSE: int
+SOL_SOCKET: int
+SOL_TCP: int
+SOL_TIPC: int
+SOL_UDP: int
+SO_ACCEPTCONN: int
+SO_BINDTODEVICE: int
+SO_BROADCAST: int
+SO_DEBUG: int
+SO_DONTROUTE: int
+SO_ERROR: int
+SO_EXCLUSIVEADDRUSE: int
+SO_KEEPALIVE: int
+SO_LINGER: int
+SO_MARK: int
+SO_OOBINLINE: int
+SO_PASSCRED: int
+SO_PEERCRED: int
+SO_PRIORITY: int
+SO_RCVBUF: int
+SO_RCVLOWAT: int
+SO_RCVTIMEO: int
+SO_REUSEADDR: int
+SO_REUSEPORT: int
+SO_SETFIB: int
+SO_SNDBUF: int
+SO_SNDLOWAT: int
+SO_SNDTIMEO: int
+SO_TYPE: int
+SO_USELOOPBACK: int
+SYSPROTO_CONTROL: int
+TCP_CORK: int
+TCP_DEFER_ACCEPT: int
+TCP_FASTOPEN: int
+TCP_INFO: int
+TCP_KEEPCNT: int
+TCP_KEEPIDLE: int
+TCP_KEEPINTVL: int
+TCP_LINGER2: int
+TCP_MAXSEG: int
+TCP_NODELAY: int
+TCP_NOTSENT_LOWAT: int
+TCP_QUICKACK: int
+TCP_SYNCNT: int
+TCP_WINDOW_CLAMP: int
+TIPC_ADDR_ID: int
+TIPC_ADDR_NAME: int
+TIPC_ADDR_NAMESEQ: int
+TIPC_CFG_SRV: int
+TIPC_CLUSTER_SCOPE: int
+TIPC_CONN_TIMEOUT: int
+TIPC_CRITICAL_IMPORTANCE: int
+TIPC_DEST_DROPPABLE: int
+TIPC_HIGH_IMPORTANCE: int
+TIPC_IMPORTANCE: int
+TIPC_LOW_IMPORTANCE: int
+TIPC_MEDIUM_IMPORTANCE: int
+TIPC_NODE_SCOPE: int
+TIPC_PUBLISHED: int
+TIPC_SRC_DROPPABLE: int
+TIPC_SUB_CANCEL: int
+TIPC_SUB_PORTS: int
+TIPC_SUB_SERVICE: int
+TIPC_SUBSCR_TIMEOUT: int
+TIPC_TOP_SRV: int
+TIPC_WAIT_FOREVER: int
+TIPC_WITHDRAWN: int
+TIPC_ZONE_SCOPE: int
+
+if sys.version_info >= (3, 3):
+    RDS_CANCEL_SENT_TO: int
+    RDS_CMSG_RDMA_ARGS: int
+    RDS_CMSG_RDMA_DEST: int
+    RDS_CMSG_RDMA_MAP: int
+    RDS_CMSG_RDMA_STATUS: int
+    RDS_CMSG_RDMA_UPDATE: int
+    RDS_CONG_MONITOR: int
+    RDS_FREE_MR: int
+    RDS_GET_MR: int
+    RDS_GET_MR_FOR_DEST: int
+    RDS_RDMA_DONTWAIT: int
+    RDS_RDMA_FENCE: int
+    RDS_RDMA_INVALIDATE: int
+    RDS_RDMA_NOTIFY_ME: int
+    RDS_RDMA_READWRITE: int
+    RDS_RDMA_SILENT: int
+    RDS_RDMA_USE_ONCE: int
+    RDS_RECVERR: int
 
+if sys.version_info >= (3, 4):
+    CAN_BCM: int
+    CAN_BCM_TX_SETUP: int
+    CAN_BCM_TX_DELETE: int
+    CAN_BCM_TX_READ: int
+    CAN_BCM_TX_SEND: int
+    CAN_BCM_RX_SETUP: int
+    CAN_BCM_RX_DELETE: int
+    CAN_BCM_RX_READ: int
+    CAN_BCM_TX_STATUS: int
+    CAN_BCM_TX_EXPIRED: int
+    CAN_BCM_RX_STATUS: int
+    CAN_BCM_RX_TIMEOUT: int
+    CAN_BCM_RX_CHANGED: int
+    AF_LINK: int
+
+if sys.version_info >= (3, 5):
+    CAN_RAW_FD_FRAMES: int
+
+if sys.version_info >= (3, 6):
+    SO_DOMAIN: int
+    SO_PROTOCOL: int
+    SO_PEERSEC: int
+    SO_PASSSEC: int
+    TCP_USER_TIMEOUT: int
+    TCP_CONGESTION: int
+    AF_ALG: int
+    SOL_ALG: int
+    ALG_SET_KEY: int
+    ALG_SET_IV: int
+    ALG_SET_OP: int
+    ALG_SET_AEAD_ASSOCLEN: int
+    ALG_SET_AEAD_AUTHSIZE: int
+    ALG_SET_PUBKEY: int
+    ALG_OP_DECRYPT: int
+    ALG_OP_ENCRYPT: int
+    ALG_OP_SIGN: int
+    ALG_OP_VERIFY: int
+
+if sys.platform == 'win32':
+    SIO_RCVALL: int
+    SIO_KEEPALIVE_VALS: int
+    RCVALL_IPLEVEL: int
+    RCVALL_MAX: int
+    RCVALL_OFF: int
+    RCVALL_ON: int
+    RCVALL_SOCKETLEVELONLY: int
+
+    if sys.version_info >= (3, 6):
+        SIO_LOOPBACK_FAST_PATH: int
 
 # enum versions of above flags py 3.4+
 if sys.version_info >= (3, 4):
@@ -285,6 +439,7 @@ if sys.version_info >= (3, 4):
         AF_UNSPEC = ...
         AF_WANPIPE = ...
         AF_X25 = ...
+        AF_LINK = ...
 
     class SocketKind(IntEnum):
         SOCK_STREAM = ...
@@ -337,12 +492,13 @@ class timeout(error):
 
 # TODO AF_PACKET and AF_BLUETOOTH address objects
 
+_SelfT = TypeVar('_SelfT', bound=socket)
 
 # ----- classes -----
 class socket:
-    family = 0
-    type = 0
-    proto = 0
+    family: int
+    type: int
+    proto: int
 
     if sys.version_info < (3,):
         def __init__(self, family: int = ..., type: int = ...,
@@ -351,6 +507,10 @@ class socket:
         def __init__(self, family: int = ..., type: int = ...,
                      proto: int = ..., fileno: Optional[int] = ...) -> None: ...
 
+    if sys.version_info >= (3, 2):
+        def __enter__(self: _SelfT) -> _SelfT: ...
+        def __exit__(self, *args: Any) -> None: ...
+
     # --- methods ---
     # second tuple item is an address
     def accept(self) -> Tuple['socket', Any]: ...
diff --git a/typeshed/stdlib/2and3/spwd.pyi b/typeshed/stdlib/2and3/spwd.pyi
deleted file mode 100644
index ca77abd..0000000
--- a/typeshed/stdlib/2and3/spwd.pyi
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import List
-
-class struct_spwd(object):
-    sp_nam = ...  # type: str
-    sp_pwd = ...  # type: str
-    sp_lstchg = ...  # type: int
-    sp_min = ...  # type: int
-    sp_max = ...  # type: int
-    sp_warn = ...  # type: int
-    sp_inact = ...  # type: int
-    sp_expire = ...  # type: int
-    sp_flag = ...  # type: int
-
-def getspall() -> List[struct_spwd]: ...
-def getspnam(name: str) -> struct_spwd: ...
diff --git a/typeshed/stdlib/2and3/symtable.pyi b/typeshed/stdlib/2and3/symtable.pyi
index 9087263..fd8b9ad 100644
--- a/typeshed/stdlib/2and3/symtable.pyi
+++ b/typeshed/stdlib/2and3/symtable.pyi
@@ -1,7 +1,7 @@
-# Stubs for symtable (Python 2 and 3)
-
 import sys
-from typing import List, Sequence, Tuple
+from typing import List, Sequence, Tuple, Text
+
+def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ...
 
 class SymbolTable(object):
     def get_type(self) -> str: ...
diff --git a/typeshed/stdlib/2and3/tarfile.pyi b/typeshed/stdlib/2and3/tarfile.pyi
index c164029..22fa951 100644
--- a/typeshed/stdlib/2and3/tarfile.pyi
+++ b/typeshed/stdlib/2and3/tarfile.pyi
@@ -4,10 +4,18 @@ from typing import (
     Callable, IO, Iterable, Iterator, List, Mapping, Optional, Type,
     Union,
 )
+import os
 import sys
 from types import TracebackType
 
 
+if sys.version_info >= (3, 6):
+    _Path = Union[bytes, str, os.PathLike]
+elif sys.version_info >= (3,):
+    _Path = Union[bytes, str]
+else:
+    _Path = Union[str, unicode]
+
 ENCODING = ...  # type: str
 
 USTAR_FORMAT = ...  # type: int
@@ -30,7 +38,7 @@ if sys.version_info < (3,):
     TAR_PLAIN = ...  # type: int
     TAR_GZIPPED = ...  # type: int
 
-def open(name: Optional[str] = ..., mode: str = ...,
+def open(name: Optional[_Path] = ..., mode: str = ...,
         fileobj: Optional[IO[bytes]] = ..., bufsize: int = ...,
         *, format: Optional[int] = ..., tarinfo: Optional[TarInfo] = ...,
         dereference: Optional[bool] = ...,
@@ -43,7 +51,7 @@ def open(name: Optional[str] = ..., mode: str = ...,
 
 
 class TarFile(Iterable[TarInfo]):
-    name = ...  # type: Optional[str]
+    name = ...  # type: Optional[_Path]
     mode = ...  # type: str
     fileobj = ...  # type: Optional[IO[bytes]]
     format = ...  # type: Optional[int]
@@ -57,7 +65,7 @@ class TarFile(Iterable[TarInfo]):
     errorlevel = ...  # type: Optional[int]
     if sys.version_info < (3,):
         posix = ...  # type: bool
-    def __init__(self, name: Optional[str] = ..., mode: str = ...,
+    def __init__(self, name: Optional[_Path] = ..., mode: str = ...,
                  fileobj: Optional[IO[bytes]] = ...,
                  format: Optional[int] = ..., tarinfo: Optional[TarInfo] = ...,
                  dereference: Optional[bool] = ...,
@@ -74,7 +82,7 @@ class TarFile(Iterable[TarInfo]):
                  exc_tb: Optional[TracebackType]) -> bool: ...
     def __iter__(self) -> Iterator[TarInfo]: ...
     @classmethod
-    def open(cls, name: Optional[str] = ..., mode: str = ...,
+    def open(cls, name: Optional[_Path] = ..., mode: str = ...,
              fileobj: Optional[IO[bytes]] = ..., bufsize: int = ...,
              *, format: Optional[int] = ..., tarinfo: Optional[TarInfo] = ...,
              dereference: Optional[bool] = ...,
@@ -93,22 +101,22 @@ class TarFile(Iterable[TarInfo]):
         def list(self, verbose: bool = ...) -> None: ...
     def next(self) -> Optional[TarInfo]: ...
     if sys.version_info >= (3, 5):
-        def extractall(self, path: str = ...,
+        def extractall(self, path: _Path = ...,
                        members: Optional[List[TarInfo]] = ...,
                        *, numeric_owner: bool = ...) -> None: ...
     else:
-        def extractall(self, path: str = ...,
+        def extractall(self, path: _Path = ...,
                        members: Optional[List[TarInfo]] = ...) -> None: ...
     if sys.version_info >= (3, 5):
-        def extract(self, member: Union[str, TarInfo], path: str = ...,
+        def extract(self, member: Union[str, TarInfo], path: _Path = ...,
                     set_attrs: bool = ...,
                     *, numeric_owner: bool = ...) -> None: ...
     elif sys.version_info >= (3,):
-        def extract(self, member: Union[str, TarInfo], path: str = ...,
+        def extract(self, member: Union[str, TarInfo], path: _Path = ...,
                     set_attrs: bool = ...) -> None: ...
     else:
         def extract(self, member: Union[str, TarInfo],
-                    path: str = ...) -> None: ...
+                    path: _Path = ...) -> None: ...
     def extractfile(self,
                     member: Union[str, TarInfo]) -> Optional[IO[bytes]]: ...
     if sys.version_info >= (3,):
diff --git a/typeshed/stdlib/2and3/threading.pyi b/typeshed/stdlib/2and3/threading.pyi
index 6d0e4a6..eb89a27 100644
--- a/typeshed/stdlib/2and3/threading.pyi
+++ b/typeshed/stdlib/2and3/threading.pyi
@@ -37,8 +37,7 @@ def stack_size(size: int = ...) -> int: ...
 if sys.version_info >= (3,):
     TIMEOUT_MAX = ...  # type: int
 
-if sys.version_info < (3,):
-    class ThreadError(Exception): ...
+class ThreadError(Exception): ...
 
 
 # TODO: Change to a class with __getattr__ and __setattr__
diff --git a/typeshed/stdlib/2and3/weakref.pyi b/typeshed/stdlib/2and3/weakref.pyi
new file mode 100644
index 0000000..e3ddbf2
--- /dev/null
+++ b/typeshed/stdlib/2and3/weakref.pyi
@@ -0,0 +1,110 @@
+import sys
+import types
+from typing import (
+    TypeVar, Generic, Any, Callable, overload, Mapping, Iterator, Tuple,
+    Iterable, Optional, Type, MutableMapping, Union, List, Dict
+)
+
+from _weakref import (
+    getweakrefcount as getweakrefcount,
+    getweakrefs as getweakrefs,
+    ref as ref,
+    proxy as proxy,
+    CallableProxyType as CallableProxyType,
+    ProxyType as ProxyType,
+    ReferenceType as ReferenceType)
+from _weakrefset import WeakSet as WeakSet
+
+if sys.version_info < (3, 0):
+    from exceptions import ReferenceError as ReferenceError
+
+_S = TypeVar('_S')
+_T = TypeVar('_T')
+_KT = TypeVar('_KT')
+_VT = TypeVar('_VT')
+
+ProxyTypes: Tuple[Type[Any], ...]
+
+if sys.version_info >= (3, 4):
+    class WeakMethod(ref[types.MethodType]):
+        def __new__(cls, meth: types.MethodType, callback: Optional[Callable[[types.MethodType], Any]] = ...) -> WeakMethod: ...
+        def __call__(self) -> Optional[types.MethodType]: ...
+
+class WeakValueDictionary(MutableMapping[_KT, _VT]):
+    @overload
+    def __init__(self) -> None: ...
+    @overload
+    def __init__(self, __map: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]], **kwargs: _VT) -> None: ...
+
+    def __len__(self) -> int: ...
+    def __getitem__(self, k: _KT) -> _VT: ...
+    def __setitem__(self, k: _KT, v: _VT) -> None: ...
+    def __delitem__(self, v: _KT) -> None: ...
+    if sys.version_info < (3, 0):
+        def has_key(self, key: object) -> bool: ...
+    def __contains__(self, o: object) -> bool: ...
+    def __iter__(self) -> Iterator[_KT]: ...
+    def __str__(self) -> str: ...
+
+    def copy(self) -> WeakValueDictionary[_KT, _VT]: ...
+
+    if sys.version_info < (3, 0):
+        def keys(self) -> List[_KT]: ...
+        def values(self) -> List[_VT]: ...
+        def items(self) -> List[Tuple[_KT, _VT]]: ...
+        def iterkeys(self) -> Iterator[_KT]: ...
+        def itervalues(self) -> Iterator[_VT]: ...
+        def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ...
+    else:
+        # These are incompatible with Mapping
+        def keys(self) -> Iterator[_KT]: ...  # type: ignore
+        def values(self) -> Iterator[_VT]: ...  # type: ignore
+        def items(self) -> Iterator[Tuple[_KT, _VT]]: ...  # type: ignore
+    def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ...
+    def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ...
+
+class KeyedRef(ref[_T], Generic[_KT, _T]):
+    key: _KT
+    def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ...
+
+class WeakKeyDictionary(MutableMapping[_KT, _VT]):
+    @overload
+    def __init__(self) -> None: ...
+    @overload
+    def __init__(self, __map: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]], **kwargs: _VT) -> None: ...
+
+    def __len__(self) -> int: ...
+    def __getitem__(self, k: _KT) -> _VT: ...
+    def __setitem__(self, k: _KT, v: _VT) -> None: ...
+    def __delitem__(self, v: _KT) -> None: ...
+    if sys.version_info < (3, 0):
+        def has_key(self, key: object) -> bool: ...
+    def __contains__(self, o: object) -> bool: ...
+    def __iter__(self) -> Iterator[_KT]: ...
+    def __str__(self) -> str: ...
+
+    def copy(self) -> WeakKeyDictionary[_KT, _VT]: ...
+
+    if sys.version_info < (3, 0):
+        def keys(self) -> List[_KT]: ...
+        def values(self) -> List[_VT]: ...
+        def items(self) -> List[Tuple[_KT, _VT]]: ...
+        def iterkeys(self) -> Iterator[_KT]: ...
+        def itervalues(self) -> Iterator[_VT]: ...
+        def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ...
+        def iterkeyrefs(self) -> Iterator[ref[_KT]]: ...
+    else:
+        # These are incompatible with Mapping
+        def keys(self) -> Iterator[_KT]: ...  # type: ignore
+        def values(self) -> Iterator[_VT]: ...  # type: ignore
+        def items(self) -> Iterator[Tuple[_KT, _VT]]: ...  # type: ignore
+    def keyrefs(self) -> List[ref[_KT]]: ...
+
+if sys.version_info >= (3, 4):
+    class finalize:
+        def __init__(self, obj: _S, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ...
+        def __call__(self, _: Any = ...) -> Optional[_T]: ...
+        def detach(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ...
+        def peek(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ...
+        alive: bool
+        atexit: bool
diff --git a/typeshed/stdlib/2and3/webbrowser.pyi b/typeshed/stdlib/2and3/webbrowser.pyi
index f4ddb15..3d276c8 100644
--- a/typeshed/stdlib/2and3/webbrowser.pyi
+++ b/typeshed/stdlib/2and3/webbrowser.pyi
@@ -1,7 +1,3 @@
-# Stubs for webbrowser (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 import sys
 from typing import Any, Optional, Callable, List, Text, Union, Sequence
 
diff --git a/typeshed/stdlib/2and3/xml/__init__.pyi b/typeshed/stdlib/2and3/xml/__init__.pyi
index a0a0a89..e69de29 100644
--- a/typeshed/stdlib/2and3/xml/__init__.pyi
+++ b/typeshed/stdlib/2and3/xml/__init__.pyi
@@ -1,20 +0,0 @@
-# Stubs for xml.sax (Python 3)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-class SAXException(Exception):
-    def __init__(self, msg, exception=None): ...
-    def getMessage(self): ...
-    def getException(self): ...
-    def __getitem__(self, ix): ...
-
-class SAXParseException(SAXException):
-    def __init__(self, msg, exception, locator): ...
-    def getColumnNumber(self): ...
-    def getLineNumber(self): ...
-    def getPublicId(self): ...
-    def getSystemId(self): ...
-
-class SAXNotRecognizedException(SAXException): ...
-class SAXNotSupportedException(SAXException): ...
-class SAXReaderNotAvailable(SAXNotSupportedException): ...
diff --git a/typeshed/stdlib/2and3/xml/sax/handler.pyi b/typeshed/stdlib/2and3/xml/sax/handler.pyi
index f3221b5..0b549b9 100644
--- a/typeshed/stdlib/2and3/xml/sax/handler.pyi
+++ b/typeshed/stdlib/2and3/xml/sax/handler.pyi
@@ -1,7 +1,3 @@
-# Stubs for xml.sax.handler (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 version = ...  # type: Any
diff --git a/typeshed/stdlib/2and3/xml/sax/saxutils.pyi b/typeshed/stdlib/2and3/xml/sax/saxutils.pyi
index 7ff053a..80a497c 100644
--- a/typeshed/stdlib/2and3/xml/sax/saxutils.pyi
+++ b/typeshed/stdlib/2and3/xml/sax/saxutils.pyi
@@ -1,18 +1,19 @@
-# Stubs for xml.sax.saxutils (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Mapping
+import sys
+from typing import AnyStr, Mapping
 
 from xml.sax import handler
 from xml.sax import xmlreader
 
-def escape(data: str, entities: Mapping[str, str] = ...) -> str: ...
-def unescape(data: str, entities: Mapping[str, str] = ...) -> str: ...
-def quoteattr(data: str, entities: Mapping[str, str] = ...) -> str: ...
+def escape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...
+def unescape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...
+def quoteattr(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...
 
 class XMLGenerator(handler.ContentHandler):
-    def __init__(self, out=..., encoding=...) -> None: ...
+    if sys.version_info >= (3, 0):
+        def __init__(self, out=..., encoding=...,
+                     short_empty_elements: bool=...) -> None: ...
+    else:
+        def __init__(self, out=..., encoding=...) -> None: ...
     def startDocument(self): ...
     def endDocument(self): ...
     def startPrefixMapping(self, prefix, uri): ...
diff --git a/typeshed/stdlib/2and3/xml/sax/xmlreader.pyi b/typeshed/stdlib/2and3/xml/sax/xmlreader.pyi
index a5f5553..fbc1ac1 100644
--- a/typeshed/stdlib/2and3/xml/sax/xmlreader.pyi
+++ b/typeshed/stdlib/2and3/xml/sax/xmlreader.pyi
@@ -1,7 +1,3 @@
-# Stubs for xml.sax.xmlreader (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 class XMLReader:
     def __init__(self) -> None: ...
     def parse(self, source): ...
diff --git a/typeshed/stdlib/2and3/zipfile.pyi b/typeshed/stdlib/2and3/zipfile.pyi
index 5a504e3..f45472e 100644
--- a/typeshed/stdlib/2and3/zipfile.pyi
+++ b/typeshed/stdlib/2and3/zipfile.pyi
@@ -14,6 +14,7 @@ if sys.version_info >= (3,):
     BadZipfile = BadZipFile
 else:
     class BadZipfile(Exception): ...
+error = BadZipfile
 
 class LargeZipFile(Exception): ...
 
diff --git a/typeshed/stdlib/2and3/zlib.pyi b/typeshed/stdlib/2and3/zlib.pyi
index 34aaf1b..3300f51 100644
--- a/typeshed/stdlib/2and3/zlib.pyi
+++ b/typeshed/stdlib/2and3/zlib.pyi
@@ -22,20 +22,20 @@ if sys.version_info >= (3,):
 class error(Exception): ...
 
 
-class Compress:
+class _Compress:
     def compress(self, data: bytes) -> bytes: ...
     def flush(self, mode: int = ...) -> bytes: ...
-    def copy(self) -> "Compress": ...
+    def copy(self) -> _Compress: ...
 
 
-class Decompress:
+class _Decompress:
     unused_data = ...  # type: bytes
     unconsumed_tail = ...  # type: bytes
     if sys.version_info >= (3,):
         eof = ...  # type: bool
     def decompress(self, data: bytes, max_length: int = ...) -> bytes: ...
     def flush(self, length: int = ...) -> bytes: ...
-    def copy(self) -> "Decompress": ...
+    def copy(self) -> _Decompress: ...
 
 
 def adler32(data: bytes, value: int = ...) -> int: ...
@@ -43,13 +43,13 @@ def compress(data: bytes, level: int = ...) -> bytes: ...
 if sys.version_info >= (3,):
     def compressobj(level: int = ..., method: int = ..., wbits: int = ...,
                     memLevel: int = ..., strategy: int = ...,
-                    zdict: bytes = ...) -> Compress: ...
+                    zdict: bytes = ...) -> _Compress: ...
 else:
     def compressobj(level: int = ..., method: int = ..., wbits: int = ...,
-                    memlevel: int = ..., strategy: int = ...) -> Compress: ...
+                    memlevel: int = ..., strategy: int = ...) -> _Compress: ...
 def crc32(data: bytes, value: int = ...) -> int: ...
 def decompress(data: bytes, wbits: int = ..., bufsize: int = ...) -> bytes: ...
 if sys.version_info >= (3,):
-    def decompressobj(wbits: int = ..., zdict: bytes = ...) -> Decompress: ...
+    def decompressobj(wbits: int = ..., zdict: bytes = ...) -> _Decompress: ...
 else:
-    def decompressobj(wbits: int = ...) -> Decompress: ...
+    def decompressobj(wbits: int = ...) -> _Decompress: ...
diff --git a/typeshed/stdlib/3.3/ipaddress.pyi b/typeshed/stdlib/3.3/ipaddress.pyi
index 69c2454..7e61fec 100644
--- a/typeshed/stdlib/3.3/ipaddress.pyi
+++ b/typeshed/stdlib/3.3/ipaddress.pyi
@@ -1,24 +1,11 @@
-# Stubs for ipaddress (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Any, Iterable, Iterator, Optional, SupportsInt, Tuple, TypeVar, Union
 
-from typing import Any
-
-IPV4LENGTH = ...  # type: Any
-IPV6LENGTH = ...  # type: Any
+IPV4LENGTH = ...  # type: int
+IPV6LENGTH = ...  # type: int
 
 class AddressValueError(ValueError): ...
 class NetmaskValueError(ValueError): ...
 
-def ip_address(address): ...
-def ip_network(address, strict=...): ...
-def ip_interface(address): ...
-def v4_int_to_packed(address): ...
-def v6_int_to_packed(address): ...
-def summarize_address_range(first, last): ...
-def collapse_addresses(addresses): ...
-def get_mixed_type_key(obj): ...
-
 class _TotalOrderingMixin:
     def __eq__(self, other): ...
     def __ne__(self, other): ...
@@ -35,9 +22,9 @@ class _IPAddressBase(_TotalOrderingMixin):
     @property
     def version(self): ...
 
-class _BaseAddress(_IPAddressBase):
+class _BaseAddress(_IPAddressBase, SupportsInt):
     def __init__(self, address) -> None: ...
-    def __int__(self): ...
+    def __int__(self) -> int: ...
     def __eq__(self, other): ...
     def __lt__(self, other): ...
     def __add__(self, other): ...
@@ -95,46 +82,46 @@ class _BaseV4:
     def version(self): ...
 
 class IPv4Address(_BaseV4, _BaseAddress):
-    def __init__(self, address) -> None: ...
+    def __init__(self, address: object) -> None: ...
     @property
-    def packed(self): ...
+    def packed(self) -> bytes: ...
     @property
-    def is_reserved(self): ...
+    def is_reserved(self) -> bool: ...
     @property
-    def is_private(self): ...
+    def is_private(self) -> bool: ...
     @property
-    def is_multicast(self): ...
+    def is_multicast(self) -> bool: ...
     @property
-    def is_unspecified(self): ...
+    def is_unspecified(self) -> bool: ...
     @property
-    def is_loopback(self): ...
+    def is_loopback(self) -> bool: ...
     @property
-    def is_link_local(self): ...
+    def is_link_local(self) -> bool: ...
 
 class IPv4Interface(IPv4Address):
-    network = ...  # type: Any
-    netmask = ...  # type: Any
-    hostmask = ...  # type: Any
-    def __init__(self, address) -> None: ...
-    def __eq__(self, other): ...
-    def __lt__(self, other): ...
-    def __hash__(self): ...
+    network = ...  # type: IPv4Network
+    netmask = ...  # type: IPv4Address
+    hostmask = ...  # type: IPv4Address
+    def __init__(self, address: object) -> None: ...
+    def __eq__(self, other: Any) -> bool: ...
+    def __lt__(self, other: Any) -> bool: ...
+    def __hash__(self) -> int: ...
     @property
-    def ip(self): ...
+    def ip(self) -> IPv4Address: ...
     @property
-    def with_prefixlen(self): ...
+    def with_prefixlen(self) -> str: ...
     @property
-    def with_netmask(self): ...
+    def with_netmask(self) -> str: ...
     @property
-    def with_hostmask(self): ...
+    def with_hostmask(self) -> str: ...
 
 class IPv4Network(_BaseV4, _BaseNetwork):
-    network_address = ...  # type: Any
-    netmask = ...  # type: Any
-    hosts = ...  # type: Any
-    def __init__(self, address, strict=...) -> None: ...
+    network_address = ...  # type: IPv4Address
+    netmask = ...  # type: IPv4Address
+    hosts = ...  # type: Iterator[IPv4Address]
+    def __init__(self, address: object, strict: bool = ...) -> None: ...
     @property
-    def is_global(self): ...
+    def is_global(self) -> bool: ...
 
 class _BaseV6:
     def __init__(self, address) -> None: ...
@@ -144,57 +131,71 @@ class _BaseV6:
     def version(self): ...
 
 class IPv6Address(_BaseV6, _BaseAddress):
-    def __init__(self, address) -> None: ...
+    def __init__(self, address: object) -> None: ...
     @property
-    def packed(self): ...
+    def packed(self) -> bytes: ...
     @property
-    def is_multicast(self): ...
+    def is_multicast(self) -> bool: ...
     @property
-    def is_reserved(self): ...
+    def is_reserved(self) -> bool: ...
     @property
-    def is_link_local(self): ...
+    def is_link_local(self) -> bool: ...
     @property
-    def is_site_local(self): ...
+    def is_site_local(self) -> bool: ...
     @property
-    def is_private(self): ...
+    def is_private(self) -> bool: ...
     @property
-    def is_global(self): ...
+    def is_global(self) -> bool: ...
     @property
-    def is_unspecified(self): ...
+    def is_unspecified(self) -> bool: ...
     @property
-    def is_loopback(self): ...
+    def is_loopback(self) -> bool: ...
     @property
-    def ipv4_mapped(self): ...
+    def ipv4_mapped(self) -> Optional[IPv4Address]: ...
     @property
-    def teredo(self): ...
+    def teredo(self) -> Optional[Tuple[IPv4Address, IPv4Address]]: ...
     @property
-    def sixtofour(self): ...
+    def sixtofour(self) -> Optional[IPv4Address]: ...
 
 class IPv6Interface(IPv6Address):
-    network = ...  # type: Any
-    netmask = ...  # type: Any
-    hostmask = ...  # type: Any
-    def __init__(self, address) -> None: ...
-    def __eq__(self, other): ...
-    def __lt__(self, other): ...
-    def __hash__(self): ...
+    network = ...  # type: IPv6Network
+    netmask = ...  # type: IPv6Address
+    hostmask = ...  # type: IPv6Address
+    def __init__(self, address: object) -> None: ...
+    def __eq__(self, other: Any) -> bool: ...
+    def __lt__(self, other: Any) -> bool: ...
+    def __hash__(self) -> int: ...
     @property
-    def ip(self): ...
+    def ip(self) -> IPv6Address: ...
     @property
-    def with_prefixlen(self): ...
+    def with_prefixlen(self) -> str: ...
     @property
-    def with_netmask(self): ...
+    def with_netmask(self) -> str: ...
     @property
-    def with_hostmask(self): ...
+    def with_hostmask(self) -> str: ...
     @property
-    def is_unspecified(self): ...
+    def is_unspecified(self) -> bool: ...
     @property
-    def is_loopback(self): ...
+    def is_loopback(self) -> bool: ...
 
 class IPv6Network(_BaseV6, _BaseNetwork):
-    network_address = ...  # type: Any
-    netmask = ...  # type: Any
-    def __init__(self, address, strict=...) -> None: ...
-    def hosts(self): ...
-    @property
-    def is_site_local(self): ...
+    network_address = ...  # type: IPv6Address
+    netmask = ...  # type: IPv6Address
+    def __init__(self, address: object, strict: bool = ...) -> None: ...
+    def hosts(self) -> Iterator[IPv6Address]: ...
+    @property
+    def is_site_local(self) -> bool: ...
+
+_ip_address = Union[IPv4Address, IPv6Address]
+_ip_network = Union[IPv4Network, IPv6Network]
+_ip_interface = Union[IPv4Interface, IPv6Interface]
+_AnyIPAddress = TypeVar("_AnyIPAddress", IPv4Address, IPv6Address)
+
+def ip_address(address: object) -> _ip_address: ...
+def ip_network(address: object, strict: bool = ...) -> _ip_network: ...
+def ip_interface(address: object) -> _ip_interface: ...
+def v4_int_to_packed(address: int) -> bytes: ...
+def v6_int_to_packed(address: int) -> bytes: ...
+def summarize_address_range(first: _AnyIPAddress, _AnyIPAddress) -> Iterator[_AnyIPAddress]: ...
+def collapse_addresses(addresses: Iterable[_AnyIPAddress]) -> Iterator[_AnyIPAddress]: ...
+def get_mixed_type_key(obj): ...
diff --git a/typeshed/stdlib/3.4/asyncio/__init__.pyi b/typeshed/stdlib/3.4/asyncio/__init__.pyi
index 60a7dde..ebd0bb2 100644
--- a/typeshed/stdlib/3.4/asyncio/__init__.pyi
+++ b/typeshed/stdlib/3.4/asyncio/__init__.pyi
@@ -1,8 +1,5 @@
-"""The asyncio package, tracking PEP 3156."""
-
-import socket
 import sys
-from typing import Type
+from typing import List, Type
 
 from asyncio.coroutines import (
     coroutine as coroutine,
@@ -49,7 +46,7 @@ from asyncio.tasks import (
     ALL_COMPLETED as ALL_COMPLETED,
     as_completed as as_completed,
     ensure_future as ensure_future,
-    ensure_future as async,
+    async as async,
     gather as gather,
     run_coroutine_threadsafe as run_coroutine_threadsafe,
     shield as shield,
@@ -63,6 +60,7 @@ from asyncio.events import (
     AbstractEventLoop as AbstractEventLoop,
     AbstractServer as AbstractServer,
     Handle as Handle,
+    TimerHandle as TimerHandle,
     get_event_loop_policy as get_event_loop_policy,
     set_event_loop_policy as set_event_loop_policy,
     get_event_loop as get_event_loop,
@@ -88,6 +86,12 @@ from asyncio.locks import (
 
 if sys.version_info < (3, 5):
     from asyncio.queues import JoinableQueue as JoinableQueue
+else:
+    from asyncio.futures import isfuture as isfuture
+    from asyncio.events import (
+        _set_running_loop as _set_running_loop,
+        _get_running_loop as _get_running_loop,
+    )
 if sys.platform != 'win32':
     from asyncio.streams import (
         open_unix_connection as open_unix_connection,
@@ -104,4 +108,4 @@ DefaultEventLoopPolicy = ...  # type: Type[AbstractEventLoopPolicy]
 
 # TODO: AbstractChildWatcher (UNIX only)
 
-__all__ = ...  # type: str
+__all__: List[str]
diff --git a/typeshed/stdlib/3.4/asyncio/coroutines.pyi b/typeshed/stdlib/3.4/asyncio/coroutines.pyi
index 9072dd7..981ccd5 100644
--- a/typeshed/stdlib/3.4/asyncio/coroutines.pyi
+++ b/typeshed/stdlib/3.4/asyncio/coroutines.pyi
@@ -1,6 +1,6 @@
-from typing import Any, Callable, Generator, TypeVar
+from typing import Any, Callable, Generator, List, TypeVar
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 _F = TypeVar('_F', bound=Callable[..., Any])
 
diff --git a/typeshed/stdlib/3.4/asyncio/events.pyi b/typeshed/stdlib/3.4/asyncio/events.pyi
index e20a023..6a444ab 100644
--- a/typeshed/stdlib/3.4/asyncio/events.pyi
+++ b/typeshed/stdlib/3.4/asyncio/events.pyi
@@ -1,3 +1,4 @@
+import selectors
 from socket import socket
 import ssl
 import sys
@@ -9,7 +10,7 @@ from asyncio.protocols import BaseProtocol
 from asyncio.tasks import Task
 from asyncio.transports import BaseTransport
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 _T = TypeVar('_T')
 _Context = Dict[str, Any]
@@ -18,11 +19,6 @@ _ProtocolFactory = Callable[[], BaseProtocol]
 _SSLContext = Union[bool, None, ssl.SSLContext]
 _TransProtPair = Tuple[BaseTransport, BaseProtocol]
 
-PIPE = ...  # type: Any  # from subprocess.PIPE
-
-AF_UNSPEC = 0     # from socket
-AI_PASSIVE = 0
-
 class Handle:
     _cancelled = False
     _args = ...  # type: List[Any]
@@ -32,6 +28,11 @@ class Handle:
     def cancel(self) -> None: ...
     def _run(self) -> None: ...
 
+class TimerHandle(Handle):
+    def __init__(self, when: float, callback: Callable[..., Any], args: List[Any],
+                 loop: AbstractEventLoop) -> None: ...
+    def __hash__(self) -> int: ...
+
 class AbstractServer:
     def close(self) -> None: ...
     @coroutine
@@ -76,7 +77,7 @@ class AbstractEventLoop(metaclass=ABCMeta):
         def create_future(self) -> Future[Any]: ...
     # Tasks methods
     @abstractmethod
-    def create_task(self, coro: Union[Future[_T], Generator[Any, None, _T]]) -> Task[_T]: ...
+    def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]]) -> Task[_T]: ...
     @abstractmethod
     def set_task_factory(self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]) -> None: ...
     @abstractmethod
@@ -124,7 +125,7 @@ class AbstractEventLoop(metaclass=ABCMeta):
     @abstractmethod
     @coroutine
     def create_datagram_endpoint(self, protocol_factory: _ProtocolFactory,
-                                 local_addr: str = ..., remote_addr: str = ..., *,
+                                 local_addr: Optional[Tuple[str, int]] = ..., remote_addr: Optional[Tuple[str, int]] = ..., *,
                                  family: int = ..., proto: int = ..., flags: int = ...,
                                  reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ...,
                                  allow_broadcast: Optional[bool] = ...,
@@ -146,17 +147,17 @@ class AbstractEventLoop(metaclass=ABCMeta):
                          **kwargs: Any) -> Generator[Any, None, _TransProtPair]: ...
     @abstractmethod
     @coroutine
-    def subprocess_exec(self, protocol_factory: _ProtocolFactory, *args: List[Any], stdin: Any = ...,
+    def subprocess_exec(self, protocol_factory: _ProtocolFactory, *args: Any, stdin: Any = ...,
                         stdout: Any = ..., stderr: Any = ...,
                         **kwargs: Any) -> Generator[Any, None, _TransProtPair]: ...
     @abstractmethod
-    def add_reader(self, fd: int, callback: Callable[..., Any], *args: List[Any]) -> None: ...
+    def add_reader(self, fd: selectors._FileObject, callback: Callable[..., Any], *args: Any) -> None: ...
     @abstractmethod
-    def remove_reader(self, fd: int) -> None: ...
+    def remove_reader(self, fd: selectors._FileObject) -> None: ...
     @abstractmethod
-    def add_writer(self, fd: int, callback: Callable[..., Any], *args: List[Any]) -> None: ...
+    def add_writer(self, fd: selectors._FileObject, callback: Callable[..., Any], *args: Any) -> None: ...
     @abstractmethod
-    def remove_writer(self, fd: int) -> None: ...
+    def remove_writer(self, fd: selectors._FileObject) -> None: ...
     # Completion based I/O methods returning Futures.
     @abstractmethod
     @coroutine
@@ -172,7 +173,7 @@ class AbstractEventLoop(metaclass=ABCMeta):
     def sock_accept(self, sock: socket) -> Generator[Any, None, Tuple[socket, Any]]: ...
     # Signal handling.
     @abstractmethod
-    def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: List[Any]) -> None: ...
+    def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ...
     @abstractmethod
     def remove_signal_handler(self, sig: int) -> None: ...
     # Error handlers.
@@ -194,7 +195,7 @@ class AbstractEventLoopPolicy(metaclass=ABCMeta):
     @abstractmethod
     def get_event_loop(self) -> AbstractEventLoop: ...
     @abstractmethod
-    def set_event_loop(self, loop: AbstractEventLoop): ...
+    def set_event_loop(self, loop: AbstractEventLoop) -> None: ...
     @abstractmethod
     def new_event_loop(self) -> AbstractEventLoop: ...
     # Child processes handling (Unix only).
@@ -206,7 +207,7 @@ class AbstractEventLoopPolicy(metaclass=ABCMeta):
 class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
     def __init__(self) -> None: ...
     def get_event_loop(self) -> AbstractEventLoop: ...
-    def set_event_loop(self, loop: AbstractEventLoop): ...
+    def set_event_loop(self, loop: AbstractEventLoop) -> None: ...
     def new_event_loop(self) -> AbstractEventLoop: ...
 
 def get_event_loop_policy() -> AbstractEventLoopPolicy: ...
@@ -218,3 +219,6 @@ def new_event_loop() -> AbstractEventLoop: ...
 
 def get_child_watcher() -> Any: ...  # TODO: unix_events.AbstractChildWatcher
 def set_child_watcher(watcher: Any) -> None: ...  # TODO: unix_events.AbstractChildWatcher
+
+def _set_running_loop(loop: AbstractEventLoop) -> None: ...
+def _get_running_loop() -> AbstractEventLoop: ...
diff --git a/typeshed/stdlib/3.4/asyncio/futures.pyi b/typeshed/stdlib/3.4/asyncio/futures.pyi
index f651c66..00086f4 100644
--- a/typeshed/stdlib/3.4/asyncio/futures.pyi
+++ b/typeshed/stdlib/3.4/asyncio/futures.pyi
@@ -1,15 +1,14 @@
+import sys
 from typing import Any, Union, Callable, TypeVar, List, Generic, Iterable, Generator, Awaitable
 from .events import AbstractEventLoop
-from concurrent.futures._base import (
-    Error as Error,
-)
 from concurrent.futures import (
     CancelledError as CancelledError,
     TimeoutError as TimeoutError,
-    Future as ConcurrentFuture,
+    Future as _ConcurrentFuture,
+    Error,
 )
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 _T = TypeVar('_T')
 
@@ -23,6 +22,9 @@ class _TracebackLogger:
     def clear(self) -> None: ...
     def __del__(self) -> None: ...
 
+if sys.version_info >= (3, 5):
+    def isfuture(obj: object) -> bool: ...
+
 class Future(Iterable[_T], Awaitable[_T], Generic[_T]):
     _state = ...  # type: str
     _exception = ...  # type: BaseException
@@ -46,4 +48,4 @@ class Future(Iterable[_T], Awaitable[_T], Generic[_T]):
     def __iter__(self) -> Generator[Any, None, _T]: ...
     def __await__(self) -> Generator[Any, None, _T]: ...
 
-def wrap_future(f: Union[ConcurrentFuture[_T], Future[_T]]) -> Future[_T]: ...
+def wrap_future(f: Union[_ConcurrentFuture[_T], Future[_T]]) -> Future[_T]: ...
diff --git a/typeshed/stdlib/3.4/asyncio/locks.pyi b/typeshed/stdlib/3.4/asyncio/locks.pyi
index 559effd..16cb02b 100644
--- a/typeshed/stdlib/3.4/asyncio/locks.pyi
+++ b/typeshed/stdlib/3.4/asyncio/locks.pyi
@@ -1,12 +1,13 @@
-from typing import Any, Callable, Generator, Iterable, Iterator, TypeVar, Union, Optional
+from typing import Any, Callable, Generator, Iterable, Iterator, List, Type, TypeVar, Union, Optional
 
 from .coroutines import coroutine
 from .events import AbstractEventLoop
-from .futures import Future
+from .futures import Future, Awaitable
+from types import TracebackType
 
 _T = TypeVar('_T')
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 class _ContextManager:
     def __init__(self, lock: Union[Lock, Semaphore]) -> None: ...
@@ -17,18 +18,18 @@ class _ContextManagerMixin(Future[_ContextManager]):
     # Apparently this exists to *prohibit* use as a context manager.
     def __enter__(self) -> object: ...
     def __exit__(self, *args: Any) -> None: ...
-    def __aenter__(self): ...
-    def __aexit__(self, exc_type, exc, tb): ...
+    def __aenter__(self) -> Awaitable[None]: ...
+    def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> Awaitable[None]: ...
 
 class Lock(_ContextManagerMixin):
-    def __init__(self, *, loop: AbstractEventLoop = None) -> None: ...
+    def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ...
     def locked(self) -> bool: ...
     @coroutine
     def acquire(self) -> Generator[Any, None, bool]: ...
     def release(self) -> None: ...
 
 class Event:
-    def __init__(self, *, loop: AbstractEventLoop = None) -> None: ...
+    def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ...
     def is_set(self) -> bool: ...
     def set(self) -> None: ...
     def clear(self) -> None: ...
@@ -36,7 +37,7 @@ class Event:
     def wait(self) -> Generator[Any, None, bool]: ...
 
 class Condition(_ContextManagerMixin):
-    def __init__(self, lock: Lock = None, *, loop: AbstractEventLoop = None) -> None: ...
+    def __init__(self, lock: Optional[Lock] = None, *, loop: Optional[AbstractEventLoop] = ...) -> None: ...
     def locked(self) -> bool: ...
     @coroutine
     def acquire(self) -> Generator[Any, None, bool]: ...
diff --git a/typeshed/stdlib/3.4/asyncio/protocols.pyi b/typeshed/stdlib/3.4/asyncio/protocols.pyi
index 91b7d94..118659c 100644
--- a/typeshed/stdlib/3.4/asyncio/protocols.pyi
+++ b/typeshed/stdlib/3.4/asyncio/protocols.pyi
@@ -1,7 +1,7 @@
 from asyncio import transports
-from typing import AnyStr
+from typing import AnyStr, List
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 
 class BaseProtocol:
diff --git a/typeshed/stdlib/3.4/asyncio/queues.pyi b/typeshed/stdlib/3.4/asyncio/queues.pyi
index 847f02b..38baf66 100644
--- a/typeshed/stdlib/3.4/asyncio/queues.pyi
+++ b/typeshed/stdlib/3.4/asyncio/queues.pyi
@@ -2,9 +2,9 @@ import sys
 from asyncio.events import AbstractEventLoop
 from .coroutines import coroutine
 from .futures import Future
-from typing import Any, Generator, Generic, TypeVar
+from typing import Any, Generator, Generic, List, TypeVar
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 
 class QueueEmpty(Exception): ...
diff --git a/typeshed/stdlib/3.4/asyncio/streams.pyi b/typeshed/stdlib/3.4/asyncio/streams.pyi
index fd677ab..f8ed236 100644
--- a/typeshed/stdlib/3.4/asyncio/streams.pyi
+++ b/typeshed/stdlib/3.4/asyncio/streams.pyi
@@ -1,15 +1,15 @@
 import sys
-from typing import Any, Awaitable, Callable, Generator, Iterable, Optional, Tuple
+from typing import Any, Awaitable, Callable, Generator, Iterable, List, Optional, Tuple
 
 from . import coroutines
 from . import events
 from . import protocols
 from . import transports
 
-ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]]
+_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]]
 
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 class IncompleteReadError(EOFError):
     def __init__(self, partial: str, expected: int) -> None: ...
@@ -29,7 +29,7 @@ def open_connection(
 
 @coroutines.coroutine
 def start_server(
-    client_connected_cb: ClientConnectedCallback,
+    client_connected_cb: _ClientConnectedCallback,
     host: str = ...,
     port: int = ...,
     *,
@@ -50,7 +50,7 @@ if sys.platform != 'win32':
 
     @coroutines.coroutine
     def start_unix_server(
-        client_connected_cb: ClientConnectedCallback,
+        client_connected_cb: _ClientConnectedCallback,
         path: str = ...,
         *,
         loop: int = ...,
@@ -62,7 +62,7 @@ class FlowControlMixin(protocols.Protocol): ...
 class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
     def __init__(self,
             stream_reader: StreamReader,
-            client_connected_cb: ClientConnectedCallback = ...,
+            client_connected_cb: _ClientConnectedCallback = ...,
             loop: events.AbstractEventLoop = ...) -> None: ...
     def connection_made(self, transport: transports.BaseTransport) -> None: ...
     def connection_lost(self, exc: Exception) -> None: ...
@@ -95,12 +95,12 @@ class StreamReader:
     def set_transport(self, transport: transports.BaseTransport) -> None: ...
     def feed_eof(self) -> None: ...
     def at_eof(self) -> bool: ...
-    def feed_data(self, data: bytes): ...
+    def feed_data(self, data: bytes) -> None: ...
     @coroutines.coroutine
     def readline(self) -> Generator[Any, None, bytes]: ...
     @coroutines.coroutine
-    def readuntil(self, separator=b'\n') -> Generator[Any, None, bytes]: ...
+    def readuntil(self, separator: bytes = ...) -> Generator[Any, None, bytes]: ...
     @coroutines.coroutine
-    def read(self, n=-1) -> Generator[Any, None, bytes]: ...
+    def read(self, n: int = ...) -> Generator[Any, None, bytes]: ...
     @coroutines.coroutine
-    def readexactly(self, n) -> Generator[Any, None, bytes]: ...
+    def readexactly(self, n: int) -> Generator[Any, None, bytes]: ...
diff --git a/typeshed/stdlib/3.4/asyncio/subprocess.pyi b/typeshed/stdlib/3.4/asyncio/subprocess.pyi
index bd7fd94..78feb8e 100644
--- a/typeshed/stdlib/3.4/asyncio/subprocess.pyi
+++ b/typeshed/stdlib/3.4/asyncio/subprocess.pyi
@@ -3,9 +3,9 @@ from asyncio import protocols
 from asyncio import streams
 from asyncio import transports
 from asyncio.coroutines import coroutine
-from typing import Any, AnyStr, Generator, Optional, Tuple, Union
+from typing import Any, AnyStr, Generator, List, Optional, Tuple, Union, IO
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 PIPE = ...  # type: int
 STDOUT = ...  # type: int
@@ -19,7 +19,7 @@ class SubprocessStreamProtocol(streams.FlowControlMixin,
     def __init__(self, limit: int, loop: events.AbstractEventLoop) -> None: ...
     def connection_made(self, transport: transports.BaseTransport) -> None: ...
     def pipe_data_received(self, fd: int, data: AnyStr) -> None: ...
-    def pipe_connection_lost(self, fd: int, exc: Exception): ...
+    def pipe_connection_lost(self, fd: int, exc: Exception) -> None: ...
     def process_exited(self) -> None: ...
 
 
@@ -46,9 +46,9 @@ class Process:
 @coroutine
 def create_subprocess_shell(
     *Args: Union[str, bytes],  # Union used instead of AnyStr due to mypy issue  #1236
-    stdin: int = ...,
-    stdout: int = ...,
-    stderr: int = ...,
+    stdin: Union[int, IO[Any], None] = ...,
+    stdout: Union[int, IO[Any], None] = ...,
+    stderr: Union[int, IO[Any], None] = ...,
     loop: events.AbstractEventLoop = ...,
     limit: int = ...,
     **kwds: Any
@@ -58,9 +58,9 @@ def create_subprocess_shell(
 def create_subprocess_exec(
     program: Union[str, bytes],  # Union used instead of AnyStr due to mypy issue  #1236
     *args: Any,
-    stdin: int = ...,
-    stdout: int = ...,
-    stderr: int = ...,
+    stdin: Union[int, IO[Any], None] = ...,
+    stdout: Union[int, IO[Any], None] = ...,
+    stderr: Union[int, IO[Any], None] = ...,
     loop: events.AbstractEventLoop = ...,
     limit: int = ...,
     **kwds: Any
diff --git a/typeshed/stdlib/3.4/asyncio/tasks.pyi b/typeshed/stdlib/3.4/asyncio/tasks.pyi
index bf69df8..d50af2f 100644
--- a/typeshed/stdlib/3.4/asyncio/tasks.pyi
+++ b/typeshed/stdlib/3.4/asyncio/tasks.pyi
@@ -5,7 +5,7 @@ import concurrent.futures
 from .events import AbstractEventLoop
 from .futures import Future
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 _T = TypeVar('_T')
 _FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]]
@@ -18,6 +18,7 @@ def as_completed(fs: Sequence[_FutureT[_T]], *, loop: AbstractEventLoop = ...,
                  timeout: Optional[float] = ...) -> Iterator[Generator[Any, None, _T]]: ...
 def ensure_future(coro_or_future: _FutureT[_T],
                   *, loop: AbstractEventLoop = ...) -> Future[_T]: ...
+async = ensure_future
 # TODO: gather() should use variadic type vars instead of _TAny.
 _TAny = Any
 def gather(*coros_or_futures: _FutureT[_TAny],
diff --git a/typeshed/stdlib/3.4/asyncio/transports.pyi b/typeshed/stdlib/3.4/asyncio/transports.pyi
index 87320a1..9ea6688 100644
--- a/typeshed/stdlib/3.4/asyncio/transports.pyi
+++ b/typeshed/stdlib/3.4/asyncio/transports.pyi
@@ -1,6 +1,6 @@
-from typing import Dict, Any, TypeVar, Mapping, List
+from typing import Dict, Any, TypeVar, Mapping, List, Optional, Tuple
 
-__all__ = ...  # type: str
+__all__: List[str]
 
 class BaseTransport:
     def __init__(self, extra: Mapping[Any, Any] = ...) -> None: ...
@@ -18,7 +18,7 @@ class WriteTransport(BaseTransport):
     ) -> None: ...
     def get_write_buffer_size(self) -> int: ...
     def write(self, data: Any) -> None: ...
-    def writelines(self, list_of_data: List[Any]): ...
+    def writelines(self, list_of_data: List[Any]) -> None: ...
     def write_eof(self) -> None: ...
     def can_write_eof(self) -> bool: ...
     def abort(self) -> None: ...
@@ -26,7 +26,7 @@ class WriteTransport(BaseTransport):
 class Transport(ReadTransport, WriteTransport): ...
 
 class DatagramTransport(BaseTransport):
-    def sendto(self, data: Any, addr: str = ...) -> None: ...
+    def sendto(self, data: Any, addr: Optional[Tuple[str, int]] = ...) -> None: ...
     def abort(self) -> None: ...
 
 class SubprocessTransport(BaseTransport):
diff --git a/typeshed/stdlib/3.4/enum.pyi b/typeshed/stdlib/3.4/enum.pyi
index a7e0fd6..dbb9df3 100644
--- a/typeshed/stdlib/3.4/enum.pyi
+++ b/typeshed/stdlib/3.4/enum.pyi
@@ -5,7 +5,7 @@ _T = TypeVar('_T', bound=Enum)
 _S = TypeVar('_S', bound=Type[Enum])
 
 class EnumMeta(type, Iterable[Enum], Sized, Reversible[Enum], Container[Enum]):
-    def __iter__(self: Type[_T]) -> Iterator[_T]: ...  # type: ignore
+    def __iter__(self: Type[_T]) -> Iterator[_T]: ...
     def __reversed__(self: Type[_T]) -> Iterator[_T]: ...
     def __contains__(self, member: Any) -> bool: ...
     def __getitem__(self: Type[_T], name: str) -> _T: ...
@@ -32,7 +32,8 @@ def unique(enumeration: _S) -> _S: ...
 if sys.version_info >= (3, 6):
     _auto_null = ...  # type: Any
 
-    class auto:
+    # subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto()
+    class auto(IntFlag):
         value = ...  # type: Any
 
     class Flag(Enum):
@@ -45,11 +46,12 @@ if sys.version_info >= (3, 6):
         def __xor__(self: _T, other: _T) -> _T: ...
         def __invert__(self: _T) -> _T: ...
 
-    # All `type: ignore` comments below due to IntFlag making the function signatures more permissive.
+    # The `type: ignore` comment is needed because mypy considers the type
+    # signatures of several methods defined in int and Flag to be incompatible.
     class IntFlag(int, Flag):  # type: ignore
-        def __or__(self: _T, other: Union[int, _T]) -> _T: ...  # type: ignore
-        def __and__(self: _T, other: Union[int, _T]) -> _T: ...  # type: ignore
-        def __xor__(self: _T, other: Union[int, _T]) -> _T: ...  # type: ignore
+        def __or__(self: _T, other: Union[int, _T]) -> _T: ...
+        def __and__(self: _T, other: Union[int, _T]) -> _T: ...
+        def __xor__(self: _T, other: Union[int, _T]) -> _T: ...
         __ror__ = __or__
         __rand__ = __and__
         __rxor__ = __xor__
diff --git a/typeshed/stdlib/3.4/selectors.pyi b/typeshed/stdlib/3.4/selectors.pyi
index 832212b..547ae02 100644
--- a/typeshed/stdlib/3.4/selectors.pyi
+++ b/typeshed/stdlib/3.4/selectors.pyi
@@ -9,82 +9,82 @@ import socket
 # Type aliases added mainly to preserve some context
 #
 # See https://github.com/python/typeshed/issues/482
-# for details regarding how FileObject is typed.
-FileObject = Union[int, socket.socket]
-FileDescriptor = int
-EventMask = int
+# for details regarding how _FileObject is typed.
+_FileObject = Union[int, socket.socket]
+_FileDescriptor = int
+_EventMask = int
 
 
-EVENT_READ = ...  # type: EventMask
-EVENT_WRITE = ...  # type: EventMask
+EVENT_READ = ...  # type: _EventMask
+EVENT_WRITE = ...  # type: _EventMask
 
 
 SelectorKey = NamedTuple('SelectorKey', [
-    ('fileobj', FileObject),
-    ('fd', FileDescriptor),
-    ('events', EventMask),
+    ('fileobj', _FileObject),
+    ('fd', _FileDescriptor),
+    ('events', _EventMask),
     ('data', Any)
 ])
 
 
 class BaseSelector(metaclass=ABCMeta):
     @abstractmethod
-    def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
+    def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
 
     @abstractmethod
-    def unregister(self, fileobj: FileObject) -> SelectorKey: ...
+    def unregister(self, fileobj: _FileObject) -> SelectorKey: ...
 
-    def modify(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
+    def modify(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
 
     @abstractmethod
-    def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
+    def select(self, timeout: Optional[int] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ...
 
     def close(self) -> None: ...
 
-    def get_key(self, fileobj: FileObject) -> SelectorKey: ...
+    def get_key(self, fileobj: _FileObject) -> SelectorKey: ...
 
     @abstractmethod
-    def get_map(self) -> Mapping[FileObject, SelectorKey]: ...
+    def get_map(self) -> Mapping[_FileObject, SelectorKey]: ...
 
     def __enter__(self) -> BaseSelector: ...
 
     def __exit__(self, *args: Any) -> None: ...
 
 class SelectSelector(BaseSelector):
-    def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
-    def unregister(self, fileobj: FileObject) -> SelectorKey: ...
-    def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
-    def get_map(self) -> Mapping[FileObject, SelectorKey]: ...
+    def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
+    def unregister(self, fileobj: _FileObject) -> SelectorKey: ...
+    def select(self, timeout: Optional[int] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ...
+    def get_map(self) -> Mapping[_FileObject, SelectorKey]: ...
 
 class PollSelector(BaseSelector):
-    def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
-    def unregister(self, fileobj: FileObject) -> SelectorKey: ...
-    def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
-    def get_map(self) -> Mapping[FileObject, SelectorKey]: ...
+    def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
+    def unregister(self, fileobj: _FileObject) -> SelectorKey: ...
+    def select(self, timeout: Optional[int] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ...
+    def get_map(self) -> Mapping[_FileObject, SelectorKey]: ...
 
 class EpollSelector(BaseSelector):
     def fileno(self) -> int: ...
-    def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
-    def unregister(self, fileobj: FileObject) -> SelectorKey: ...
-    def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
-    def get_map(self) -> Mapping[FileObject, SelectorKey]: ...
+    def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
+    def unregister(self, fileobj: _FileObject) -> SelectorKey: ...
+    def select(self, timeout: Optional[int] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ...
+    def get_map(self) -> Mapping[_FileObject, SelectorKey]: ...
 
 class DevpollSelector(BaseSelector):
     def fileno(self) -> int: ...
-    def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
-    def unregister(self, fileobj: FileObject) -> SelectorKey: ...
-    def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
-    def get_map(self) -> Mapping[FileObject, SelectorKey]: ...
+    def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
+    def unregister(self, fileobj: _FileObject) -> SelectorKey: ...
+    def select(self, timeout: Optional[int] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ...
+    def get_map(self) -> Mapping[_FileObject, SelectorKey]: ...
 
 class KqueueSelector(BaseSelector):
     def fileno(self) -> int: ...
-    def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
-    def unregister(self, fileobj: FileObject) -> SelectorKey: ...
-    def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
-    def get_map(self) -> Mapping[FileObject, SelectorKey]: ...
+    def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
+    def unregister(self, fileobj: _FileObject) -> SelectorKey: ...
+    def select(self, timeout: Optional[int] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ...
+    def get_map(self) -> Mapping[_FileObject, SelectorKey]: ...
 
 class DefaultSelector(BaseSelector):
-    def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
-    def unregister(self, fileobj: FileObject) -> SelectorKey: ...
-    def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
-    def get_map(self) -> Mapping[FileObject, SelectorKey]: ...
+    def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ...
+    def unregister(self, fileobj: _FileObject) -> SelectorKey: ...
+    def select(self, timeout: Optional[int] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ...
+    def get_map(self) -> Mapping[_FileObject, SelectorKey]: ...
diff --git a/typeshed/stdlib/3/_ast.pyi b/typeshed/stdlib/3/_ast.pyi
index 6736181..ca75bca 100644
--- a/typeshed/stdlib/3/_ast.pyi
+++ b/typeshed/stdlib/3/_ast.pyi
@@ -4,7 +4,7 @@ from typing import Any, Optional, Union
 
 PyCF_ONLY_AST = ...  # type: int
 
-identifier = str
+_identifier = str
 
 class AST:
     _attributes = ...  # type: typing.Tuple[str, ...]
@@ -32,21 +32,21 @@ class stmt(AST):
     col_offset = ...  # type: int
 
 class FunctionDef(stmt):
-    name = ...  # type: identifier
+    name = ...  # type: _identifier
     args = ...  # type: arguments
     body = ...  # type: typing.List[stmt]
     decorator_list = ...  # type: typing.List[expr]
     returns = ...  # type: Optional[expr]
 
 class AsyncFunctionDef(stmt):
-    name = ...  # type: identifier
+    name = ...  # type: _identifier
     args = ...  # type: arguments
     body = ...  # type: typing.List[stmt]
     decorator_list = ...  # type: typing.List[expr]
     returns = ...  # type: Optional[expr]
 
 class ClassDef(stmt):
-    name = ...  # type: identifier
+    name = ...  # type: _identifier
     bases = ...  # type: typing.List[expr]
     keywords = ...  # type: typing.List[keyword]
     body = ...  # type: typing.List[stmt]
@@ -115,15 +115,15 @@ class Import(stmt):
     names = ...  # type: typing.List[alias]
 
 class ImportFrom(stmt):
-    module = ...  # type: Optional[identifier]
+    module = ...  # type: Optional[_identifier]
     names = ...  # type: typing.List[alias]
     level = ...  # type: Optional[int]
 
 class Global(stmt):
-    names = ...  # type: typing.List[identifier]
+    names = ...  # type: typing.List[_identifier]
 
 class Nonlocal(stmt):
-    names = ...  # type: typing.List[identifier]
+    names = ...  # type: typing.List[_identifier]
 
 class Expr(stmt):
     value = ...  # type: expr
@@ -235,7 +235,7 @@ class Ellipsis(expr): ...
 
 class Attribute(expr):
     value = ...  # type: expr
-    attr = ...  # type: identifier
+    attr = ...  # type: _identifier
     ctx = ...  # type: expr_context
 
 class Subscript(expr):
@@ -248,7 +248,7 @@ class Starred(expr):
     ctx = ...  # type: expr_context
 
 class Name(expr):
-    id = ...  # type: identifier
+    id = ...  # type: _identifier
     ctx = ...  # type: expr_context
 
 class List(expr):
@@ -325,7 +325,7 @@ class comprehension(AST):
 
 class ExceptHandler(AST):
     type = ...  # type: Optional[expr]
-    name = ...  # type: Optional[identifier]
+    name = ...  # type: Optional[_identifier]
     body = ...  # type: typing.List[stmt]
     lineno = ...  # type: int
     col_offset = ...  # type: int
@@ -340,18 +340,18 @@ class arguments(AST):
     defaults = ...  # type: typing.List[expr]
 
 class arg(AST):
-    arg = ...  # type: identifier
+    arg = ...  # type: _identifier
     annotation = ...  # type: Optional[expr]
     lineno = ...  # type: int
     col_offset = ...  # type: int
 
 class keyword(AST):
-    arg = ...  # type: Optional[identifier]
+    arg = ...  # type: Optional[_identifier]
     value = ...  # type: expr
 
 class alias(AST):
-    name = ...  # type: identifier
-    asname = ...  # type: Optional[identifier]
+    name = ...  # type: _identifier
+    asname = ...  # type: Optional[_identifier]
 
 class withitem(AST):
     context_expr = ...  # type: expr
diff --git a/typeshed/stdlib/3/_compression.pyi b/typeshed/stdlib/3/_compression.pyi
index 527d795..d84a11a 100644
--- a/typeshed/stdlib/3/_compression.pyi
+++ b/typeshed/stdlib/3/_compression.pyi
@@ -1,7 +1,3 @@
-# Stubs for _compression (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import io
 
diff --git a/typeshed/stdlib/3/_curses.pyi b/typeshed/stdlib/3/_curses.pyi
index 368dda2..a6afa7b 100644
--- a/typeshed/stdlib/3/_curses.pyi
+++ b/typeshed/stdlib/3/_curses.pyi
@@ -1,10 +1,6 @@
-# Stubs for _curses (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Any, BinaryIO, IO, Optional, Tuple, Union, overload
 
-from typing import Any, BinaryIO, Tuple, Union
-
-chtype = Union[str, bytes, int]
+_chtype = Union[str, bytes, int]
 
 ALL_MOUSE_EVENTS = ...  # type: int
 A_ALTCHARSET = ...  # type: int
@@ -246,7 +242,7 @@ def has_il() -> bool: ...
 def has_key(ch: int) -> bool: ...
 def init_color(color_number: int, r: int, g: int, b: int) -> None: ...
 def init_pair(pair_number: int, fg: int, bg: int) -> None: ...
-def initscr(): ...
+def initscr() -> _CursesWindow: ...
 def intrflush(ch: bool) -> None: ...
 def is_term_resized(nlines: int, ncols: int) -> bool: ...
 def isendwin() -> bool: ...
@@ -258,7 +254,7 @@ def mouseinterval(interval: int) -> None: ...
 def mousemask(mousemask: int) -> Tuple[int, int]: ...
 def napms(ms: int) -> int: ...
 def newpad(nlines: int, ncols: int): ...
-def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ...): ...
+def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ...) -> _CursesWindow: ...
 def nl(flag: bool = ...) -> None: ...
 def nocbreak() -> None: ...
 def noecho() -> None: ...
@@ -286,12 +282,237 @@ def tigetnum(capname: str) -> int: ...
 def tigetstr(capname: str) -> bytes: ...
 def tparm(fmt: str, i1: int = ..., i2: int = ..., i3: int = ..., i4: int = ..., i5: int = ..., i6: int = ..., i7: int = ..., i8: int = ..., i9: int = ...) -> str: ...
 def typeahead(fd: int) -> None: ...
-def unctrl(ch: chtype) -> bytes: ...
-def unget_wch(ch: chtype) -> None: ...
-def ungetch(ch: chtype) -> None: ...
+def unctrl(ch: _chtype) -> bytes: ...
+def unget_wch(ch: _chtype) -> None: ...
+def ungetch(ch: _chtype) -> None: ...
 def ungetmouse(id: int, x: int, y: int, z: int, bstate: int) -> None: ...
 def update_lines_cols() -> int: ...
 def use_default_colors() -> None: ...
 def use_env(flag: bool) -> None: ...
 
 class error(Exception): ...
+
+
+class _CursesWindow:
+    encoding = ...  # type: str
+
+    @overload
+    def addch(self, ch: _chtype, attr: Optional[int]) -> None: ...
+
+    @overload
+    def addch(self, y: int, x: int, ch: _chtype, attr: Optional[int]) -> None: ...
+
+    @overload
+    def addnstr(self, str: str, n: int, attr: Optional[int]) -> None: ...
+
+    @overload
+    def addnstr(self, y: int, x: int, str: str, n: int, attr: Optional[int]) -> None: ...
+
+    @overload
+    def addstr(self, str: str, attr: Optional[int]) -> None: ...
+
+    @overload
+    def addstr(self, y: int, x: int, str: str, attr: Optional[int]) -> None: ...
+
+    def attroff(self, attr: int) -> None: ...
+
+    def attron(self, attr: int) -> None: ...
+
+    def attrset(self, attr: int) -> None: ...
+
+    def bkgd(self, ch: _chtype, attr: Optional[int]) -> None: ...
+
+    def bkgset(self, ch: _chtype, attr: Optional[int]) -> None: ...
+
+    def border(self, ls: Optional[int], rs: Optional[int],
+               ts: Optional[int], bs: Optional[int],
+               tl: Optional[int], tr: Optional[int],
+               bl: Optional[int], br: Optional[int]) -> None: ...
+
+    def box(self, vertch: Optional[Tuple[int, int]], horch: Optional[Tuple[int, int]]) -> None: ...
+
+    @overload
+    def chgat(self, attr: int) -> None: ...
+
+    @overload
+    def chgat(self, num: int, attr: int) -> None: ...
+
+    @overload
+    def chgat(self, y: int, x: int, attr: int) -> None: ...
+
+    @overload
+    def chgat(self, y: int, x: int, num: int, attr: int) -> None: ...
+
+    def clear(self) -> None: ...
+
+    def clearok(self, yes: int): ...
+
+    def clrtobot(self) -> None: ...
+
+    def clrtoeol(self) -> None: ...
+
+    def cursyncup(self) -> None: ...
+
+    @overload
+    def delch(self) -> None: ...
+
+    @overload
+    def delch(self, y: int, x: int) -> None: ...
+
+    def deleteln(self) -> None: ...
+
+    @overload
+    def derwin(self, begin_y: int, begin_x: int) -> '_CursesWindow': ...
+
+    @overload
+    def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> '_CursesWindow': ...
+
+    def echochar(self, ch: _chtype, attr: Optional[int]) -> None: ...
+
+    def enclose(self, y: int, x: int) -> bool: ...
+
+    def erase(self) -> None: ...
+
+    def getbegyx(self) -> Tuple[int, int]: ...
+
+    def getbkgd(self) -> Tuple[int, int]: ...
+
+    def getch(self, y: Optional[int], x: Optional[int]) -> _chtype: ...
+
+    def get_wch(self, y: Optional[int], x: Optional[int]) -> _chtype: ...
+
+    def getkey(self, y: Optional[int], x: Optional[int]) -> str: ...
+
+    def getmaxyx(self) -> Tuple['_CursesWindow', int, int]: ...
+
+    def getparyx(self) -> Tuple[int, int]: ...
+
+    def getstr(self, y: Optional[int], x: Optional[int]) -> None: ...
+
+    def getyx(self) -> Tuple['_CursesWindow', int, int]: ...
+
+    @overload
+    def hline(self, ch: _chtype, n: int) -> None: ...
+
+    @overload
+    def hline(self, y: int, x: int, ch: _chtype, n: int) -> None: ...
+
+    def idcok(self, flag: bool) -> None: ...
+
+    def idlok(self, yes: bool) -> None: ...
+
+    def immedok(self, flag: bool) -> None: ...
+
+    def inch(self, y: Optional[int], x: Optional[int]) -> _chtype: ...
+
+    @overload
+    def insch(self, ch: _chtype, attr: Optional[int]) -> None: ...
+
+    @overload
+    def insch(self, y: int, x: int, ch: _chtype, attr: Optional[int]) -> None: ...
+
+    def insdelln(self, nlines: int) -> None: ...
+
+    def insertln(self) -> None: ...
+
+    @overload
+    def insnstr(self, str: str, n: int, attr: Optional[int]) -> None: ...
+
+    @overload
+    def insnstr(self, y: int, x: int, str: str, n: int, attr: Optional[int]) -> None: ...
+
+    @overload
+    def insstr(self, str: str, attr: Optional[int]) -> None: ...
+
+    @overload
+    def insstr(self, y: int, x: int, str: str, attr: Optional[int]) -> None: ...
+
+    @overload
+    def instr(self, n: Optional[int]) -> str: ...
+
+    @overload
+    def instr(self, y: int, x: int, n: Optional[int]) -> str: ...
+
+    def is_linetouched(self, line: int) -> bool: ...
+
+    def is_wintouched(self) -> bool: ...
+
+    def keypad(self, yes: bool) -> None: ...
+
+    def leaveok(self, yes: bool) -> None: ...
+
+    def move(self, new_y: int, new_x: int) -> None: ...
+
+    def mvderwin(self, y: int, x: int) -> None: ...
+
+    def mvwin(self, new_y: int, new_x: int) -> None: ...
+
+    def nodelay(self, yes: bool) -> None: ...
+
+    def notimeout(self, yes: bool) -> None: ...
+
+    def noutrefresh(self) -> None: ...
+
+    def overlay(self, destwin: '_CursesWindow',
+                sminrow: Optional[int], smincol: Optional[int],
+                dminrow: Optional[int], dmincol: Optional[int],
+                dmaxrow: Optional[int], dmaxcol: Optional[int]) -> None: ...
+
+    def overwrite(self, destwin: '_CursesWindow',
+                  sminrow: Optional[int], smincol: Optional[int],
+                  dminrow: Optional[int], dmincol: Optional[int],
+                  dmaxrow: Optional[int], dmaxcol: Optional[int]) -> None: ...
+
+    def putwin(self, file: IO[Any]) -> None: ...
+
+    def redrawln(self, beg: int, num: int) -> None: ...
+
+    def redrawwin(self) -> None: ...
+
+    def refresh(self, pminrow: Optional[int], pmincol: Optional[int],
+                sminrow: Optional[int], smincol: Optional[int],
+                smaxrow: Optional[int], smaxcol: Optional[int]) -> None: ...
+
+    def resize(self, nlines: int, ncols: int) -> None: ...
+
+    def scroll(self, lines: int) -> None: ...
+
+    def scrollok(self, flag: bool) -> None: ...
+
+    def setscrreg(self, top: int, bottom: int) -> None: ...
+
+    def standend(self) -> None: ...
+
+    def standout(self) -> None: ...
+
+    @overload
+    def subpad(self, begin_y: int, begin_x: int) -> '_CursesWindow': ...
+
+    @overload
+    def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> '_CursesWindow': ...
+
+    @overload
+    def subwin(self, begin_y: int, begin_x: int) -> '_CursesWindow': ...
+
+    @overload
+    def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> '_CursesWindow': ...
+
+    def syncdown(self) -> None: ...
+
+    def syncok(self, flag: bool) -> None: ...
+
+    def syncup(self) -> None: ...
+
+    def timeout(self, delay: int) -> None: ...
+
+    def touchline(self, start: int, count: int, changed: Optional[bool]) -> None: ...
+
+    def touchwin(self) -> None: ...
+
+    def untouchwin(self) -> None: ...
+
+    @overload
+    def vline(self, ch: _chtype, n: int) -> None: ...
+
+    @overload
+    def vline(self, y: int, x: int, ch: _chtype, n: int) -> None: ...
diff --git a/typeshed/stdlib/3/_dummy_thread.pyi b/typeshed/stdlib/3/_dummy_thread.pyi
index a4ff81c..d88d248 100644
--- a/typeshed/stdlib/3/_dummy_thread.pyi
+++ b/typeshed/stdlib/3/_dummy_thread.pyi
@@ -1,11 +1,22 @@
-# Stubs for _dummy_thread
+from mypy_extensions import NoReturn
+from typing import Any, Callable, Dict, Optional, Tuple
 
-# NOTE: These are incomplete!
+TIMEOUT_MAX: int
+error = RuntimeError
 
-from typing import Any
+def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ...
+def exit() -> NoReturn: ...
+def get_ident() -> int: ...
+def allocate_lock() -> LockType: ...
+def stack_size(size: Optional[int] = ...) -> int: ...
 
-class LockType:
-    def acquire(self) -> None: ...
-    def release(self) -> None: ...
+class LockType(object):
+    locked_status: bool
+    def __init__(self) -> None: ...
+    def acquire(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ...
+    def __enter__(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ...
+    def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ...
+    def release(self) -> bool: ...
+    def locked(self) -> bool: ...
 
-def allocate_lock() -> LockType: ...
+def interrupt_main() -> None: ...
diff --git a/typeshed/stdlib/3/_importlib_modulespec.pyi b/typeshed/stdlib/3/_importlib_modulespec.pyi
index bfd27ad..33c30d5 100644
--- a/typeshed/stdlib/3/_importlib_modulespec.pyi
+++ b/typeshed/stdlib/3/_importlib_modulespec.pyi
@@ -12,8 +12,8 @@ from typing import Dict, Any, Optional
 if sys.version_info >= (3, 4):
     class ModuleSpec:
         def __init__(self, name: str, loader: Optional['Loader'], *,
-                     origin: str = None, loader_state: Any = None,
-                     is_package: bool = None) -> None: ...
+                     origin: Optional[str] = None, loader_state: Any = None,
+                     is_package: Optional[bool] = None) -> None: ...
         name = ...  # type: str
         loader = ...  # type: Optional[Loader]
         origin = ...  # type: Optional[str]
diff --git a/typeshed/stdlib/3/builtins.pyi b/typeshed/stdlib/3/builtins.pyi
index 3cd9da4..50d9098 100644
--- a/typeshed/stdlib/3/builtins.pyi
+++ b/typeshed/stdlib/3/builtins.pyi
@@ -103,7 +103,11 @@ class super:
     def __init__(self) -> None: ...
 
 class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
-    def __init__(self, x: Union[SupportsInt, str, bytes] = ..., base: int = ...) -> None: ...
+    @overload
+    def __init__(self, x: SupportsInt = ...) -> None: ...
+    @overload
+    def __init__(self, x: Union[str, bytes], base: int = ...) -> None: ...
+
     def bit_length(self) -> int: ...
     def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ...
     @classmethod
@@ -227,17 +231,17 @@ class complex(SupportsAbs[float]):
 
 class str(Sequence[str]):
     @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, o: object) -> None: ...
+    def __init__(self, o: object = ...) -> None: ...
     @overload
-    def __init__(self, o: bytes, encoding: str = ..., errors: str = 'strict') -> None: ...
+    def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> None: ...
+
     def capitalize(self) -> str: ...
+    def casefold(self) -> str: ...
     def center(self, width: int, fillchar: str = ' ') -> str: ...
     def count(self, x: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ...
     def encode(self, encoding: str = 'utf-8', errors: str = 'strict') -> bytes: ...
-    def endswith(self, suffix: Union[str, Tuple[str, ...]], start: int = None,
-                 end: int = None) -> bool: ...
+    def endswith(self, suffix: Union[str, Tuple[str, ...]], start: Optional[int] = None,
+                 end: Optional[int] = None) -> bool: ...
     def expandtabs(self, tabsize: int = 8) -> str: ...
     def find(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ...
     def format(self, *args: Any, **kwargs: Any) -> str: ...
@@ -257,20 +261,20 @@ class str(Sequence[str]):
     def join(self, iterable: Iterable[str]) -> str: ...
     def ljust(self, width: int, fillchar: str = ' ') -> str: ...
     def lower(self) -> str: ...
-    def lstrip(self, chars: str = None) -> str: ...
+    def lstrip(self, chars: Optional[str] = None) -> str: ...
     def partition(self, sep: str) -> Tuple[str, str, str]: ...
     def replace(self, old: str, new: str, count: int = -1) -> str: ...
     def rfind(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ...
     def rindex(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ...
     def rjust(self, width: int, fillchar: str = ' ') -> str: ...
     def rpartition(self, sep: str) -> Tuple[str, str, str]: ...
-    def rsplit(self, sep: str = None, maxsplit: int = -1) -> List[str]: ...
-    def rstrip(self, chars: str = None) -> str: ...
-    def split(self, sep: str = None, maxsplit: int = -1) -> List[str]: ...
+    def rsplit(self, sep: Optional[str] = None, maxsplit: int = -1) -> List[str]: ...
+    def rstrip(self, chars: Optional[str] = None) -> str: ...
+    def split(self, sep: Optional[str] = None, maxsplit: int = -1) -> List[str]: ...
     def splitlines(self, keepends: bool = ...) -> List[str]: ...
-    def startswith(self, prefix: Union[str, Tuple[str, ...]], start: int = None,
-                   end: int = None) -> bool: ...
-    def strip(self, chars: str = None) -> str: ...
+    def startswith(self, prefix: Union[str, Tuple[str, ...]], start: Optional[int] = None,
+                   end: Optional[int] = None) -> bool: ...
+    def strip(self, chars: Optional[str] = None) -> str: ...
     def swapcase(self) -> str: ...
     def title(self) -> str: ...
     def translate(self, table: Dict[int, Any]) -> str: ...
@@ -319,22 +323,22 @@ class bytes(ByteString):
     def capitalize(self) -> bytes: ...
     def center(self, width: int, fillchar: bytes = ...) -> bytes: ...
     if sys.version_info >= (3, 3):
-        def count(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def count(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def count(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def count(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     def decode(self, encoding: str = 'utf-8', errors: str = 'strict') -> str: ...
     def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ...
     def expandtabs(self, tabsize: int = 8) -> bytes: ...
     if sys.version_info >= (3, 3):
-        def find(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def find(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def find(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def find(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     if sys.version_info >= (3, 5):
         def hex(self) -> str: ...
     if sys.version_info >= (3, 3):
-        def index(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def index(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def index(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def index(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     def isalnum(self) -> bool: ...
     def isalpha(self) -> bool: ...
     def isdigit(self) -> bool: ...
@@ -345,25 +349,25 @@ class bytes(ByteString):
     def join(self, iterable: Iterable[bytes]) -> bytes: ...
     def ljust(self, width: int, fillchar: bytes = ...) -> bytes: ...
     def lower(self) -> bytes: ...
-    def lstrip(self, chars: bytes = None) -> bytes: ...
+    def lstrip(self, chars: Optional[bytes] = None) -> bytes: ...
     def partition(self, sep: bytes) -> Tuple[bytes, bytes, bytes]: ...
     def replace(self, old: bytes, new: bytes, count: int = -1) -> bytes: ...
     if sys.version_info >= (3, 3):
-        def rfind(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def rfind(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def rfind(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def rfind(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     if sys.version_info >= (3, 3):
-        def rindex(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def rindex(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def rindex(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def rindex(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     def rjust(self, width: int, fillchar: bytes = ...) -> bytes: ...
     def rpartition(self, sep: bytes) -> Tuple[bytes, bytes, bytes]: ...
-    def rsplit(self, sep: bytes = None, maxsplit: int = -1) -> List[bytes]: ...
-    def rstrip(self, chars: bytes = None) -> bytes: ...
-    def split(self, sep: bytes = None, maxsplit: int = -1) -> List[bytes]: ...
+    def rsplit(self, sep: Optional[bytes] = None, maxsplit: int = -1) -> List[bytes]: ...
+    def rstrip(self, chars: Optional[bytes] = None) -> bytes: ...
+    def split(self, sep: Optional[bytes] = None, maxsplit: int = -1) -> List[bytes]: ...
     def splitlines(self, keepends: bool = ...) -> List[bytes]: ...
     def startswith(self, prefix: Union[bytes, Tuple[bytes, ...]]) -> bool: ...
-    def strip(self, chars: bytes = None) -> bytes: ...
+    def strip(self, chars: Optional[bytes] = None) -> bytes: ...
     def swapcase(self) -> bytes: ...
     def title(self) -> bytes: ...
     def translate(self, table: Optional[bytes], delete: bytes = ...) -> bytes: ...
@@ -410,22 +414,22 @@ class bytearray(MutableSequence[int], ByteString):
     def capitalize(self) -> bytearray: ...
     def center(self, width: int, fillchar: bytes = ...) -> bytearray: ...
     if sys.version_info >= (3, 3):
-        def count(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def count(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def count(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def count(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     def decode(self, encoding: str = 'utf-8', errors: str = 'strict') -> str: ...
     def endswith(self, suffix: bytes) -> bool: ...
     def expandtabs(self, tabsize: int = 8) -> bytearray: ...
     if sys.version_info >= (3, 3):
-        def find(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def find(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def find(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def find(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     if sys.version_info >= (3, 5):
         def hex(self) -> str: ...
     if sys.version_info >= (3, 3):
-        def index(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def index(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def index(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def index(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     def insert(self, index: int, object: int) -> None: ...
     def isalnum(self) -> bool: ...
     def isalpha(self) -> bool: ...
@@ -437,25 +441,25 @@ class bytearray(MutableSequence[int], ByteString):
     def join(self, iterable: Iterable[bytes]) -> bytearray: ...
     def ljust(self, width: int, fillchar: bytes = ...) -> bytearray: ...
     def lower(self) -> bytearray: ...
-    def lstrip(self, chars: bytes = None) -> bytearray: ...
+    def lstrip(self, chars: Optional[bytes] = None) -> bytearray: ...
     def partition(self, sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ...
     def replace(self, old: bytes, new: bytes, count: int = -1) -> bytearray: ...
     if sys.version_info >= (3, 3):
-        def rfind(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def rfind(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def rfind(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def rfind(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     if sys.version_info >= (3, 3):
-        def rindex(self, sub: Union[bytes, int], start: int = None, end: int = None) -> int: ...
+        def rindex(self, sub: Union[bytes, int], start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     else:
-        def rindex(self, sub: bytes, start: int = None, end: int = None) -> int: ...
+        def rindex(self, sub: bytes, start: Optional[int] = None, end: Optional[int] = None) -> int: ...
     def rjust(self, width: int, fillchar: bytes = ...) -> bytearray: ...
     def rpartition(self, sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ...
-    def rsplit(self, sep: bytes = None, maxsplit: int = -1) -> List[bytearray]: ...
-    def rstrip(self, chars: bytes = None) -> bytearray: ...
-    def split(self, sep: bytes = None, maxsplit: int = -1) -> List[bytearray]: ...
+    def rsplit(self, sep: Optional[bytes] = None, maxsplit: int = -1) -> List[bytearray]: ...
+    def rstrip(self, chars: Optional[bytes] = None) -> bytearray: ...
+    def split(self, sep: Optional[bytes] = None, maxsplit: int = -1) -> List[bytearray]: ...
     def splitlines(self, keepends: bool = ...) -> List[bytearray]: ...
     def startswith(self, prefix: bytes) -> bool: ...
-    def strip(self, chars: bytes = None) -> bytearray: ...
+    def strip(self, chars: Optional[bytes] = None) -> bytearray: ...
     def swapcase(self) -> bytearray: ...
     def title(self) -> bytearray: ...
     def translate(self, table: Optional[bytes], delete: bytes = ...) -> bytearray: ...
@@ -542,7 +546,7 @@ class slice:
     @overload
     def __init__(self, stop: Optional[int]) -> None: ...
     @overload
-    def __init__(self, start: Optional[int], stop: Optional[int], step: int = None) -> None: ...
+    def __init__(self, start: Optional[int], stop: Optional[int], step: Optional[int] = None) -> None: ...
     def indices(self, len: int) -> Tuple[int, int, int]: ...
 
 class tuple(Sequence[_T_co], Generic[_T_co]):
@@ -590,7 +594,7 @@ class list(MutableSequence[_T], Generic[_T]):
     def insert(self, index: int, object: _T) -> None: ...
     def remove(self, object: _T) -> None: ...
     def reverse(self) -> None: ...
-    def sort(self, *, key: Callable[[_T], Any] = None, reverse: bool = ...) -> None: ...
+    def sort(self, *, key: Optional[Callable[[_T], Any]] = None, reverse: bool = ...) -> None: ...
 
     def __len__(self) -> int: ...
     def __iter__(self) -> Iterator[_T]: ...
@@ -632,11 +636,13 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
     def clear(self) -> None: ...
     def copy(self) -> Dict[_KT, _VT]: ...
     def popitem(self) -> Tuple[_KT, _VT]: ...
-    def setdefault(self, k: _KT, default: _VT = None) -> _VT: ...
+    def setdefault(self, k: _KT, default: Optional[_VT] = None) -> _VT: ...
+    @overload
+    def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
     @overload
-    def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
     @overload
-    def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
+    def update(self, **kwargs: _VT) -> None: ...
     def keys(self) -> KeysView[_KT]: ...
     def values(self) -> ValuesView[_VT]: ...
     def items(self) -> ItemsView[_KT, _VT]: ...
@@ -724,7 +730,7 @@ class range(Sequence[int]):
     @overload
     def __init__(self, start: int, stop: int, step: int = 1) -> None: ...
     def count(self, value: int) -> int: ...
-    def index(self, value: int, start: int = 0, stop: int = None) -> int: ...
+    def index(self, value: int, start: int = 0, stop: Optional[int] = None) -> int: ...
     def __len__(self) -> int: ...
     def __contains__(self, o: object) -> bool: ...
     def __iter__(self) -> Iterator[int]: ...
@@ -736,13 +742,14 @@ class range(Sequence[int]):
     def __reversed__(self) -> Iterator[int]: ...
 
 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 __init__(self, fget: Optional[Callable[[Any], Any]] = None,
+                 fset: Optional[Callable[[Any, Any], None]] = None,
+                 fdel: Optional[Callable[[Any], None]] = None,
+                 doc: Optional[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 __get__(self, obj: Any, type: Optional[type] = None) -> Any: ...
     def __set__(self, obj: Any, value: Any) -> None: ...
     def __delete__(self, obj: Any) -> None: ...
     def fget(self) -> Any: ...
@@ -766,13 +773,14 @@ def delattr(o: Any, name: str) -> None: ...
 def dir(o: object = ...) -> List[str]: ...
 _N = TypeVar('_N', int, float)
 def divmod(a: _N, b: _N) -> Tuple[_N, _N]: ...
-def eval(source: str, globals: Dict[str, Any] = None,
-         locals: Mapping[str, Any] = None) -> Any: ...  # TODO code object as source
-def exec(object: str, globals: Dict[str, Any] = None,
-         locals: Mapping[str, Any] = None) -> Any: ...  # TODO code object as source
+def eval(source: str, globals: Optional[Dict[str, Any]] = None,
+         locals: Optional[Mapping[str, Any]] = None) -> Any: ...  # TODO code object as source
+def exec(object: str, globals: Optional[Dict[str, Any]] = None,
+         locals: Optional[Mapping[str, Any]] = None) -> Any: ...  # TODO code object as source
 def exit(code: Any = ...) -> NoReturn: ...
 @overload
-def filter(function: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterator[_T]: ...
+def filter(function: Optional[Callable[[_T], Any]],
+           iterable: Iterable[_T]) -> Iterator[_T]: ...
 @overload
 def filter(function: None, iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ...
 def format(o: object, format_spec: str = '') -> str: ...
@@ -783,7 +791,7 @@ def hash(o: object) -> int: ...
 def help(*args: Any, **kwds: Any) -> None: ...
 def hex(i: int) -> str: ...  # TODO __index__
 def id(o: object) -> int: ...
-def input(prompt: Any = None) -> str: ...
+def input(prompt: Optional[Any] = None) -> str: ...
 @overload
 def iter(iterable: Iterable[_T]) -> Iterator[_T]: ...
 @overload
@@ -819,15 +827,15 @@ if sys.version_info >= (3, 6):
     class _PathLike(Generic[AnyStr]):
         def __fspath__(self) -> AnyStr: ...
 
-    def open(file: Union[str, bytes, int, _PathLike], mode: str = 'r', buffering: int = -1, encoding: str = None,
-             errors: str = None, newline: str = None, closefd: bool = ...) -> IO[Any]: ...
+    def open(file: Union[str, bytes, int, _PathLike], mode: str = 'r', buffering: int = -1, encoding: Optional[str] = None,
+             errors: Optional[str] = None, newline: Optional[str] = None, closefd: bool = ...) -> IO[Any]: ...
 else:
-    def open(file: Union[str, bytes, int], mode: str = 'r', buffering: int = -1, encoding: str = None,
-             errors: str = None, newline: str = None, closefd: bool = ...) -> IO[Any]: ...
+    def open(file: Union[str, bytes, int], mode: str = 'r', buffering: int = -1, encoding: Optional[str] = None,
+             errors: Optional[str] = None, newline: Optional[str] = None, closefd: bool = ...) -> IO[Any]: ...
 
 def ord(c: Union[str, bytes, bytearray]) -> int: ...
 # TODO: in Python 3.2, print() does not support flush
-def print(*values: Any, sep: str = ' ', end: str = '\n', file: IO[str] = None, flush: bool = False) -> None: ...
+def print(*values: Any, sep: str = ' ', end: str = '\n', file: Optional[IO[str]] = None, flush: bool = False) -> None: ...
 @overload
 def pow(x: int, y: int) -> Any: ...  # The return type can be int or float, depending on y
 @overload
@@ -836,7 +844,7 @@ def pow(x: int, y: int, z: int) -> Any: ...
 def pow(x: float, y: float) -> float: ...
 @overload
 def pow(x: float, y: float, z: float) -> float: ...
-def quit(code: int = None) -> None: ...
+def quit(code: Optional[int] = None) -> None: ...
 @overload
 def reversed(object: Reversible[_T]) -> Iterator[_T]: ...
 @overload
@@ -851,7 +859,8 @@ def round(number: SupportsRound[_T]) -> _T: ...
 @overload
 def round(number: SupportsRound[_T], ndigits: int) -> _T: ...
 def setattr(object: Any, name: str, value: Any) -> None: ...
-def sorted(iterable: Iterable[_T], *, key: Callable[[_T], Any] = None,
+def sorted(iterable: Iterable[_T], *,
+           key: Optional[Callable[[_T], Any]] = None,
            reverse: bool = False) -> List[_T]: ...
 def sum(iterable: Iterable[_T], start: _T = ...) -> _T: ...
 def vars(object: Any = ...) -> Dict[str, Any]: ...
diff --git a/typeshed/stdlib/3/collections/__init__.pyi b/typeshed/stdlib/3/collections/__init__.pyi
index 4e460b8..e10d861 100644
--- a/typeshed/stdlib/3/collections/__init__.pyi
+++ b/typeshed/stdlib/3/collections/__init__.pyi
@@ -52,13 +52,16 @@ _VT = TypeVar('_VT')
 
 
 # namedtuple is special-cased in the type checker; the initializer is ignored.
-def namedtuple(typename: str, field_names: Union[str, Iterable[Any]], *,
-               verbose: bool = ..., rename: bool = ..., module: str = None) -> Type[tuple]: ...
+if sys.version_info >= (3, 6):
+    def namedtuple(typename: str, field_names: Union[str, Iterable[str]], *,
+                   verbose: bool = ..., rename: bool = ..., module: Optional[str] = ...) -> Type[tuple]: ...
+else:
+    def namedtuple(typename: str, field_names: Union[str, Iterable[str]],
+                   verbose: bool = ..., rename: bool = ...) -> Type[tuple]: ...
 
 class UserDict(MutableMapping): ...
 class UserList(MutableSequence): ...
 class UserString(Sequence): ...
-class MutableString(UserString, MutableSequence): ...
 
 # Technically, deque only derives from MutableSequence in 3.5.
 # But in practice it's not worth losing sleep over.
@@ -68,11 +71,15 @@ class deque(MutableSequence[_T], Generic[_T]):
                  maxlen: int = ...) -> None: ...
     def append(self, x: _T) -> None: ...
     def appendleft(self, x: _T) -> None: ...
-    def insert(self, i: int, x: _T) -> None: ...
     def clear(self) -> None: ...
+    if sys.version_info >= (3, 5):
+        def copy(self) -> deque[_T]: ...
     def count(self, x: _T) -> int: ...
     def extend(self, iterable: Iterable[_T]) -> None: ...
     def extendleft(self, iterable: Iterable[_T]) -> None: ...
+    if sys.version_info >= (3, 5):
+        def insert(self, i: int, x: _T) -> None: ...
+        def index(self, x: _T, start: int = ..., stop: int = ...) -> int: ...
     def pop(self, i: int = ...) -> _T: ...
     def popleft(self) -> _T: ...
     def remove(self, value: _T) -> None: ...
@@ -100,28 +107,28 @@ class deque(MutableSequence[_T], Generic[_T]):
     def __delitem__(self, s: slice) -> None: raise TypeError
 
     def __contains__(self, o: object) -> bool: ...
+    def __reversed__(self) -> Iterator[_T]: ...
 
-    # TODO __reversed__
+    if sys.version_info >= (3, 5):
+        def __add__(self, other: deque[_T]) -> deque[_T]: ...
+        def __mul__(self, other: int) -> deque[_T]: ...
+        def __imul__(self, other: int) -> None: ...
 
 
 class Counter(Dict[_T, int], Generic[_T]):
     @overload
-    def __init__(self) -> None: ...
+    def __init__(self, **kwargs: int) -> None: ...
     @overload
-    def __init__(self, Mapping: Mapping[_T, int]) -> None: ...
+    def __init__(self, mapping: Mapping[_T, int]) -> None: ...
     @overload
     def __init__(self, iterable: Iterable[_T]) -> None: ...
-    # TODO keyword arguments
 
     def elements(self) -> Iterator[_T]: ...
 
-    @overload
-    def most_common(self) -> List[_T]: ...
-    @overload
-    def most_common(self, n: int) -> List[_T]: ...
+    def most_common(self, n: int = ...) -> List[_T]: ...
 
     @overload
-    def subtract(self, Mapping: Mapping[_T, int]) -> None: ...
+    def subtract(self, __mapping: Mapping[_T, int]) -> None: ...
     @overload
     def subtract(self, iterable: Iterable[_T]) -> None: ...
 
@@ -131,20 +138,22 @@ class Counter(Dict[_T, int], Generic[_T]):
     # Dict.update. Not sure if we should use '# type: ignore' instead
     # and omit the type from the union.
     @overload
-    def update(self, m: Mapping[_T, int], **kwargs: int) -> None: ...
+    def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ...
     @overload
-    def update(self, m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ...
+    def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ...
+    @overload
+    def update(self, **kwargs: int) -> None: ...
 
-    def __add__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
-    def __sub__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
-    def __and__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
-    def __or__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
-    def __pos__(self) -> typing.Counter[_T]: ...
-    def __neg__(self) -> typing.Counter[_T]: ...
-    def __iadd__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
-    def __isub__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
-    def __iand__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
-    def __ior__(self, other: typing.Counter[_T]) -> typing.Counter[_T]: ...
+    def __add__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __sub__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __and__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __or__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __pos__(self) -> Counter[_T]: ...
+    def __neg__(self) -> Counter[_T]: ...
+    def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __isub__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __iand__(self, other: Counter[_T]) -> Counter[_T]: ...
+    def __ior__(self, other: Counter[_T]) -> Counter[_T]: ...
 
 class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]):
     def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ...
@@ -155,29 +164,21 @@ class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]):
     default_factory = ...  # type: Callable[[], _VT]
 
     @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, map: Mapping[_KT, _VT]) -> None: ...
-    @overload
-    def __init__(self, iterable: Iterable[Tuple[_KT, _VT]]) -> None: ...
+    def __init__(self, **kwargs: _VT) -> None: ...
     @overload
-    def __init__(self, default_factory: Callable[[], _VT]) -> None: ...
+    def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ...
     @overload
-    def __init__(self, default_factory: Callable[[], _VT],
+    def __init__(self, default_factory: Optional[Callable[[], _VT]],
                  map: Mapping[_KT, _VT]) -> None: ...
     @overload
-    def __init__(self, default_factory: Callable[[], _VT],
+    def __init__(self, default_factory: Optional[Callable[[], _VT]],
                  iterable: Iterable[Tuple[_KT, _VT]]) -> None: ...
-    # TODO __init__ keyword args
 
     def __missing__(self, key: _KT) -> _VT: ...
     # TODO __reversed__
 
 if sys.version_info >= (3, 3):
     class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
-        @overload
-        def __init__(self) -> None: ...
-        @overload
         def __init__(self, *maps: Mapping[_KT, _VT]) -> None: ...
 
         @property
diff --git a/typeshed/stdlib/3/collections/abc.pyi b/typeshed/stdlib/3/collections/abc.pyi
index 03e7086..38db036 100644
--- a/typeshed/stdlib/3/collections/abc.pyi
+++ b/typeshed/stdlib/3/collections/abc.pyi
@@ -10,6 +10,7 @@ if sys.version_info >= (3, 3):
         Iterable as Iterable,
         Iterator as Iterator,
         Sized as Sized,
+        Callable as Callable,
         Mapping as Mapping,
         MutableMapping as MutableMapping,
         Sequence as Sequence,
diff --git a/typeshed/stdlib/3/compileall.pyi b/typeshed/stdlib/3/compileall.pyi
index d8093bf..8d2731c 100644
--- a/typeshed/stdlib/3/compileall.pyi
+++ b/typeshed/stdlib/3/compileall.pyi
@@ -6,13 +6,15 @@ from typing import Optional, Union, Pattern
 
 if sys.version_info < (3, 6):
     _Path = Union[str, bytes]
+    _SuccessType = bool
 else:
     _Path = Union[str, bytes, os.PathLike]
+    _SuccessType = int
 
-# fx can be any object with a 'search' method; once we have Protocols we can change the type
+# rx can be any object with a 'search' method; once we have Protocols we can change the type
 if sys.version_info < (3, 5):
-    def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> None: ...
+    def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> _SuccessType: ...
 else:
-    def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., workers: int = ...) -> None: ...
-def compile_file(fullname: _Path, ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> None: ...
-def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> None: ...
+    def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., workers: int = ...) -> _SuccessType: ...
+def compile_file(fullname: _Path, ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> _SuccessType: ...
+def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> _SuccessType: ...
diff --git a/typeshed/stdlib/3/concurrent/futures/_base.pyi b/typeshed/stdlib/3/concurrent/futures/_base.pyi
index 00ef5b6..510b7c0 100644
--- a/typeshed/stdlib/3/concurrent/futures/_base.pyi
+++ b/typeshed/stdlib/3/concurrent/futures/_base.pyi
@@ -1,9 +1,9 @@
 from typing import TypeVar, Generic, Any, Iterable, Iterator, Callable, Tuple, Optional, Set
 from collections import namedtuple
 
-FIRST_COMPLETED = ...  # type: Any
-FIRST_EXCEPTION = ...  # type: Any
-ALL_COMPLETED = ...  # type: Any
+FIRST_COMPLETED = ...  # type: str
+FIRST_EXCEPTION = ...  # type: str
+ALL_COMPLETED = ...  # type: str
 PENDING = ...  # type: Any
 RUNNING = ...  # type: Any
 CANCELLED = ...  # type: Any
@@ -25,20 +25,20 @@ class Future(Generic[_T]):
     def cancelled(self) -> bool: ...
     def running(self) -> bool: ...
     def done(self) -> bool: ...
-    def add_done_callback(self, fn: Callable[[Future], Any]) -> None: ...
+    def add_done_callback(self, fn: Callable[[Future[_T]], Any]) -> None: ...
     def result(self, timeout: Optional[float] = ...) -> _T: ...
-    def exception(self, timeout: Optional[float] = ...) -> BaseException: ...
+    def exception(self, timeout: Optional[float] = ...) -> Optional[BaseException]: ...
     def set_running_or_notify_cancel(self) -> None: ...
     def set_result(self, result: _T) -> None: ...
-    def set_exception(self, exception: BaseException) -> None: ...
+    def set_exception(self, exception: Optional[BaseException]) -> None: ...
 
 class Executor:
     def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ...
-    def map(self, func: Callable[..., _T], *iterables: Any, timeout: Optional[float] = ..., chunksize: int = ...) -> Iterable[_T]: ...
+    def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ..., chunksize: int = ...) -> Iterator[_T]: ...
     def shutdown(self, wait: bool = ...) -> None: ...
     def __enter__(self) -> Executor: ...
     def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool: ...
 
-def as_completed(fs: Iterable[Future], timeout: Optional[float] = ...) -> Iterator[Future]: ...
+def as_completed(fs: Iterable[Future[_T]], timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ...
 
-def wait(fs: Iterable[Future], timeout: Optional[float] = ..., return_when: str = ...) -> Tuple[Set[Future], Set[Future]]: ...
+def wait(fs: Iterable[Future[_T]], timeout: Optional[float] = ..., return_when: str = ...) -> Tuple[Set[Future[_T]], Set[Future[_T]]]: ...
diff --git a/typeshed/stdlib/3/concurrent/futures/process.pyi b/typeshed/stdlib/3/concurrent/futures/process.pyi
index b157d2b..8076c2d 100644
--- a/typeshed/stdlib/3/concurrent/futures/process.pyi
+++ b/typeshed/stdlib/3/concurrent/futures/process.pyi
@@ -1,14 +1,9 @@
-from typing import Any, Callable, TypeVar, Iterable, Optional
+from typing import Optional, Any
 from ._base import Future, Executor
 
 EXTRA_QUEUED_CALLS = ...  # type: Any
 
 class BrokenProcessPool(RuntimeError): ...
 
-_T = TypeVar('_T')
-
 class ProcessPoolExecutor(Executor):
     def __init__(self, max_workers: Optional[int] = ...) -> None: ...
-    def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ...
-    def map(self, func: Callable[..., _T], *iterables: Any, timeout: Optional[float] = ..., chunksize: int = ...) -> Iterable[_T]: ...
-    def shutdown(self, wait: bool = ...) -> None: ...
diff --git a/typeshed/stdlib/3/concurrent/futures/thread.pyi b/typeshed/stdlib/3/concurrent/futures/thread.pyi
index e366d4d..88a45a3 100644
--- a/typeshed/stdlib/3/concurrent/futures/thread.pyi
+++ b/typeshed/stdlib/3/concurrent/futures/thread.pyi
@@ -1,10 +1,10 @@
-from typing import Any, TypeVar, Callable, Iterable, Optional
+from typing import Optional
 from ._base import Executor, Future
-
-_T = TypeVar('_T')
+import sys
 
 class ThreadPoolExecutor(Executor):
-    def __init__(self, max_workers: Optional[int] = ...) -> None: ...
-    def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ...
-    def map(self, func: Callable[..., _T], *iterables: Any, timeout: Optional[float] = ..., chunksize: int = ...) -> Iterable[_T]: ...
-    def shutdown(self, wait: bool = ...) -> None: ...
+    if sys.version_info >= (3, 6):
+        def __init__(self, max_workers: Optional[int] = ...,
+                     thread_name_prefix: str = ...) -> None: ...
+    else:
+        def __init__(self, max_workers: Optional[int] = ...) -> None: ...
diff --git a/typeshed/stdlib/3/configparser.pyi b/typeshed/stdlib/3/configparser.pyi
index 22a42a1..ff90651 100644
--- a/typeshed/stdlib/3/configparser.pyi
+++ b/typeshed/stdlib/3/configparser.pyi
@@ -1,21 +1,19 @@
-# Stubs for configparser
-
 # Based on http://docs.python.org/3.5/library/configparser.html and on
 # reading configparser.py.
 
 from typing import (MutableMapping, Mapping, Dict, Sequence, List, Union,
-                    Iterable, Iterator, Callable, Any, IO, overload, Optional)
+                    Iterable, Iterator, Callable, Any, IO, overload, Optional, Pattern)
 # Types only used in type comments only
 from typing import Optional, Tuple  # noqa
 
 # Internal type aliases
-_section = Dict[str, str]
+_section = Mapping[str, str]
 _parser = MutableMapping[str, _section]
-_converters = Dict[str, Callable[[str], Any]]
-
-
-DEFAULTSECT = ...  # type: str
+_converter = Callable[[str], Any]
+_converters = Dict[str, _converter]
 
+DEFAULTSECT: str
+MAX_INTERPOLATION_DEPTH: int
 
 class Interpolation:
     def before_get(self, parser: _parser,
@@ -40,27 +38,24 @@ class Interpolation:
                      value: str) -> str: ...
 
 
-class BasicInterpolation(Interpolation):
-    pass
-
-
-class ExtendedInterpolation(Interpolation):
-    pass
+class BasicInterpolation(Interpolation): ...
+class ExtendedInterpolation(Interpolation): ...
+class LegacyInterpolation(Interpolation): ...
 
 
 class RawConfigParser(_parser):
     def __init__(self,
-                 defaults: _section = None,
+                 defaults: Optional[_section] = ...,
                  dict_type: Mapping[str, str] = ...,
                  allow_no_value: bool = ...,
                  *,
                  delimiters: Sequence[str] = ...,
                  comment_prefixes: Sequence[str] = ...,
-                 inline_comment_prefixes: Sequence[str] = None,
+                 inline_comment_prefixes: Optional[Sequence[str]] = ...,
                  strict: bool = ...,
                  empty_lines_in_values: bool = ...,
                  default_section: str = ...,
-                 interpolation: Interpolation = None) -> None: ...
+                 interpolation: Optional[Interpolation] = ...) -> None: ...
 
     def __len__(self) -> int: ...
 
@@ -85,9 +80,9 @@ class RawConfigParser(_parser):
     def has_option(self, section: str, option: str) -> bool: ...
 
     def read(self, filenames: Union[str, Sequence[str]],
-             encoding: str = None) -> List[str]: ...
+             encoding: Optional[str] = None) -> List[str]: ...
 
-    def read_file(self, f: Iterable[str], source: str = None) -> None: ...
+    def read_file(self, f: Iterable[str], source: Optional[str] = None) -> None: ...
 
     def read_string(self, string: str, source: str = ...) -> None: ...
 
@@ -122,18 +117,45 @@ class RawConfigParser(_parser):
 
 class ConfigParser(RawConfigParser):
     def __init__(self,
-                 defaults: _section = None,
+                 defaults: Optional[_section] = None,
                  dict_type: Mapping[str, str] = ...,
                  allow_no_value: bool = ...,
                  delimiters: Sequence[str] = ...,
                  comment_prefixes: Sequence[str] = ...,
-                 inline_comment_prefixes: Sequence[str] = None,
+                 inline_comment_prefixes: Optional[Sequence[str]] = None,
                  strict: bool = ...,
                  empty_lines_in_values: bool = ...,
                  default_section: str = ...,
-                 interpolation: Interpolation = None,
+                 interpolation: Optional[Interpolation] = None,
                  converters: _converters = ...) -> None: ...
 
+class SafeConfigParser(ConfigParser): ...
+
+class SectionProxy(MutableMapping[str, str]):
+    def __init__(self, parser: RawConfigParser, name: str) -> None: ...
+    def __getitem__(self, key: str) -> str: ...
+    def __setitem__(self, key: str, value: str) -> None: ...
+    def __delitem__(self, key: str) -> None: ...
+    def __contains__(self, key: object) -> bool: ...
+    def __len__(self) -> int: ...
+    def __iter__(self) -> Iterator[str]: ...
+    @property
+    def parser(self) -> RawConfigParser: ...
+    @property
+    def name(self) -> str: ...
+    def get(self, option: str, fallback: Optional[str] = ..., *, raw: bool = ..., vars: Optional[_section] = ..., **kwargs: Any) -> str: ...  # type: ignore
+    # SectionProxy can have arbitrary attributes when custon converters are used
+    def __getattr__(self, key: str) -> Callable[..., Any]: ...
+
+class ConverterMapping(MutableMapping[str, Optional[_converter]]):
+    GETTERCRE: Pattern
+    def __init__(self, parser: RawConfigParser) -> None: ...
+    def __getitem__(self, key: str) -> _converter: ...
+    def __setitem__(self, key: str, value: Optional[_converter]) -> None: ...
+    def __delitem__(self, key: str) -> None: ...
+    def __iter__(self) -> Iterator[str]: ...
+    def __len__(self) -> int: ...
+
 
 class Error(Exception):
     pass
diff --git a/typeshed/stdlib/3/csv.pyi b/typeshed/stdlib/3/csv.pyi
deleted file mode 100644
index 7b41cc8..0000000
--- a/typeshed/stdlib/3/csv.pyi
+++ /dev/null
@@ -1,77 +0,0 @@
-# Stubs for csv (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any, Iterable
-
-QUOTE_ALL = ...  # type: int
-QUOTE_MINIMAL = ...  # type: int
-QUOTE_NONE = ...  # type: int
-QUOTE_NONNUMERIC = ...  # type: int
-
-class Error(Exception): ...
-
-def writer(csvfile, dialect=..., **fmtparams): ...
-def reader(csvfile, dialect=..., **fmtparams): ...
-def register_dialect(name, dialect=..., **fmtparams): ...
-def unregister_dialect(name): ...
-def get_dialect(name): ...
-def list_dialects(): ...
-def field_size_limit(new_limit=...): ...
-
-class Dialect:
-    delimiter = ...  # type: Any
-    quotechar = ...  # type: Any
-    escapechar = ...  # type: Any
-    doublequote = ...  # type: Any
-    skipinitialspace = ...  # type: Any
-    lineterminator = ...  # type: Any
-    quoting = ...  # type: Any
-    def __init__(self) -> None: ...
-
-class excel(Dialect):
-    delimiter = ...  # type: Any
-    quotechar = ...  # type: Any
-    doublequote = ...  # type: Any
-    skipinitialspace = ...  # type: Any
-    lineterminator = ...  # type: Any
-    quoting = ...  # type: Any
-
-class excel_tab(excel):
-    delimiter = ...  # type: Any
-
-class unix_dialect(Dialect):
-    delimiter = ...  # type: Any
-    quotechar = ...  # type: Any
-    doublequote = ...  # type: Any
-    skipinitialspace = ...  # type: Any
-    lineterminator = ...  # type: Any
-    quoting = ...  # type: Any
-
-class DictReader(Iterable):
-    restkey = ...  # type: Any
-    restval = ...  # type: Any
-    reader = ...  # type: Any
-    dialect = ...  # type: Any
-    line_num = ...  # type: Any
-    fieldnames = ...  # type: Any # Actually a property
-    def __init__(self, f, fieldnames=..., restkey=..., restval=..., dialect=...,
-                 *args, **kwds): ...
-    def __iter__(self): ...
-    def __next__(self): ...
-
-class DictWriter:
-    fieldnames = ...  # type: Any
-    restval = ...  # type: Any
-    extrasaction = ...  # type: Any
-    writer = ...  # type: Any
-    def __init__(self, f, fieldnames, restval=..., extrasaction=..., dialect=..., *args, **kwds) -> None: ...
-    def writeheader(self): ...
-    def writerow(self, rowdict): ...
-    def writerows(self, rowdicts): ...
-
-class Sniffer:
-    preferred = ...  # type: Any
-    def __init__(self) -> None: ...
-    def sniff(self, sample, delimiters=...): ...
-    def has_header(self, sample): ...
diff --git a/typeshed/stdlib/3/curses/__init__.pyi b/typeshed/stdlib/3/curses/__init__.pyi
index 63a4bd9..078a6cd 100644
--- a/typeshed/stdlib/3/curses/__init__.pyi
+++ b/typeshed/stdlib/3/curses/__init__.pyi
@@ -1,12 +1,6 @@
-# Stubs for curses (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
+import _curses
 from _curses import *  # noqa: F403
-# Stubgen imports a python version of has_key only if it's not present
-# in _curses (which it is in this stub)
-# from .has_key import has_key as has_key
 
-def initscr(): ...
+def initscr() -> _curses._CursesWindow: ...
 def start_color(): ...
 def wrapper(func, *args, **kwds): ...
diff --git a/typeshed/stdlib/3/datetime.pyi b/typeshed/stdlib/3/datetime.pyi
index a894ab8..8b1b2e4 100644
--- a/typeshed/stdlib/3/datetime.pyi
+++ b/typeshed/stdlib/3/datetime.pyi
@@ -1,13 +1,10 @@
-# Stubs for datetime
-
-# NOTE: These are incomplete!
-
+import sys
 from typing import Optional, SupportsAbs, Tuple, overload
 
 MINYEAR = 0
 MAXYEAR = 0
 
-TimeTuple = Tuple[int, int, int, int, int, int, int, int, int]
+_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int]
 
 class tzinfo:
     def tzname(self, dt: Optional[datetime]) -> str: ...
@@ -191,9 +188,9 @@ class datetime:
     def strftime(self, fmt: str) -> str: ...
     def __format__(self, fmt: str) -> str: ...
     def toordinal(self) -> int: ...
-    def timetuple(self) -> TimeTuple: ...  # TODO return type
+    def timetuple(self) -> _TimeTuple: ...
     def timestamp(self) -> float: ...
-    def utctimetuple(self) -> TimeTuple: ...  # TODO return type
+    def utctimetuple(self) -> _TimeTuple: ...
     def date(self) -> _date: ...
     def time(self) -> _time: ...
     def timetz(self) -> _time: ...
@@ -202,7 +199,10 @@ class datetime:
                 Optional[_tzinfo] = None) -> datetime: ...
     def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ...
     def ctime(self) -> str: ...
-    def isoformat(self, sep: str = ...) -> str: ...
+    if sys.version_info >= (3, 6):
+        def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ...
+    else:
+        def isoformat(self, sep: str = ...) -> str: ...
     @classmethod
     def strptime(cls, date_string: str, format: str) -> datetime: ...
     def utcoffset(self) -> Optional[timedelta]: ...
diff --git a/typeshed/stdlib/3/difflib.pyi b/typeshed/stdlib/3/difflib.pyi
deleted file mode 100644
index f2fb7a8..0000000
--- a/typeshed/stdlib/3/difflib.pyi
+++ /dev/null
@@ -1,62 +0,0 @@
-# Stubs for difflib
-
-# Based on https://docs.python.org/3.2/library/difflib.html
-
-from typing import (
-    TypeVar, Callable, Iterable, Iterator, List, NamedTuple, Sequence, Tuple,
-    Generic, Optional
-)
-
-_T = TypeVar('_T')
-
-class SequenceMatcher(Generic[_T]):
-    def __init__(self, isjunk: Optional[Callable[[_T], bool]] = ...,
-                 a: Sequence[_T] = ..., b: Sequence[_T] = ...,
-                 autojunk: bool = ...) -> None: ...
-    def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ...
-    def set_seq1(self, a: Sequence[_T]) -> None: ...
-    def set_seq2(self, b: Sequence[_T]) -> None: ...
-    def find_longest_match(self, alo: int, ahi: int, blo: int,
-                           bhi: int) -> Tuple[int, int, int]: ...
-    def get_matching_blocks(self) -> List[Tuple[int, int, int]]: ...
-    def get_opcodes(self) -> List[Tuple[str, int, int, int, int]]: ...
-    def get_grouped_opcodes(self, n: int = ...
-                            ) -> Iterable[Tuple[str, int, int, int, int]]: ...
-    def ratio(self) -> float: ...
-    def quick_ratio(self) -> float: ...
-    def real_quick_ratio(self) -> float: ...
-
-def get_close_matches(word: Sequence[_T], possibilities: List[Sequence[_T]],
-                      n: int = ..., cutoff: float = ...) -> List[Sequence[_T]]: ...
-
-class Differ:
-    def __init__(self, linejunk: Callable[[str], bool] = ...,
-                 charjunk: Callable[[str], bool] = ...) -> None: ...
-    def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: ...
-
-def IS_LINE_JUNK(str) -> bool: ...
-def IS_CHARACTER_JUNK(str) -> bool: ...
-def unified_diff(a: Sequence[str], b: Sequence[str], fromfile: str = ...,
-                 tofile: str = ..., fromfiledate: str = ..., tofiledate: str = ...,
-                 n: int = ..., lineterm: str = ...) -> Iterator[str]: ...
-def context_diff(a: Sequence[str], b: Sequence[str], fromfile: str=...,
-                 tofile: str = ..., fromfiledate: str = ..., tofiledate: str = ...,
-                 n: int = ..., lineterm: str = ...) -> Iterator[str]: ...
-def ndiff(a: Sequence[str], b: Sequence[str],
-          linejunk: Callable[[str], bool] = ...,
-          charjunk: Callable[[str], bool] = ...
-          ) -> Iterator[str]: ...
-
-class HtmlDiff:
-    def __init__(self, tabsize: int = ..., wrapcolumn: int = ...,
-                 linejunk: Callable[[str], bool] = ...,
-                 charjunk: Callable[[str], bool] = ...
-                 ) -> None: ...
-    def make_file(self, fromlines: Sequence[str], tolines: Sequence[str],
-                  fromdesc: str = ..., todesc: str = ..., context: bool = ...,
-                  numlines: int = ...) -> str: ...
-    def make_table(self, fromlines: Sequence[str], tolines: Sequence[str],
-                   fromdesc: str = ..., todesc: str = ..., context: bool = ...,
-                   numlines: int = ...) -> str: ...
-
-def restore(delta: Iterable[str], which: int) -> Iterator[int]: ...
diff --git a/typeshed/stdlib/3/doctest.pyi b/typeshed/stdlib/3/doctest.pyi
deleted file mode 100644
index 5cbdc1f..0000000
--- a/typeshed/stdlib/3/doctest.pyi
+++ /dev/null
@@ -1,9 +0,0 @@
-# Stubs for doctest
-
-# NOTE: These are incomplete!
-
-from typing import Any, Tuple
-
-# TODO arguments missing
-def testmod(module: Any = ..., *, name: str = ..., globs: Any = ...,
-            verbose: bool = ...) -> Tuple[int, int]: ...
diff --git a/typeshed/stdlib/3/email/contentmanager.pyi b/typeshed/stdlib/3/email/contentmanager.pyi
index 6f37fba..6b1f2d1 100644
--- a/typeshed/stdlib/3/email/contentmanager.pyi
+++ b/typeshed/stdlib/3/email/contentmanager.pyi
@@ -2,14 +2,10 @@
 
 from typing import Any, Callable
 import sys
-import email.message
 from email.message import Message
 
 if sys.version_info >= (3, 4):
 
-    EmailMessage = email.message.EmailMessage
-    MIMEPart = email.message.MIMEPart
-
     class ContentManager:
         def __init__(self) -> None: ...
         def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ...
diff --git a/typeshed/stdlib/3/email/headerregistry.pyi b/typeshed/stdlib/3/email/headerregistry.pyi
index a39f0e2..6f14cc0 100644
--- a/typeshed/stdlib/3/email/headerregistry.pyi
+++ b/typeshed/stdlib/3/email/headerregistry.pyi
@@ -1,6 +1,6 @@
 # Stubs for email.headerregistry (Python 3.4)
 
-import datetime as dt
+from datetime import datetime as _datetime
 import sys
 from typing import Dict, Tuple, Optional, Any, Union, Mapping
 from email.errors import MessageDefect
@@ -27,9 +27,9 @@ if sys.version_info >= (3, 3):
     class UniqueUnstructuredHeader(UnstructuredHeader): ...
 
     class DateHeader:
-        datetime = ...  # type: dt.datetime
+        datetime = ...  # type: _datetime
         @classmethod
-        def parse(cls, string: Union[str, dt.datetime],
+        def parse(cls, string: Union[str, _datetime],
                   kwds: Dict[str, Any]) -> None: ...
 
     class UniqueDateHeader(DateHeader): ...
@@ -68,7 +68,7 @@ if sys.version_info >= (3, 3):
     class ContentDispositionHeader(ParameterizedMIMEHeader):
         content_disposition = ...  # type: str
 
-    class ContentTransferEncoding:
+    class ContentTransferEncodingHeader:
         cte = ...  # type: str
         @classmethod
         def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ...
@@ -97,6 +97,5 @@ if sys.version_info >= (3, 3):
         display_name = ...  # type: Optional[str]
         addresses = ...  # type: Tuple[Address, ...]
         def __init__(self, display_name: Optional[str] = ...,
-                     addresses: Optional[Tuple[Address, ...]] = ...) \
-                     -> None: ...
+                     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 3acd111..8244939 100644
--- a/typeshed/stdlib/3/email/message.pyi
+++ b/typeshed/stdlib/3/email/message.pyi
@@ -29,8 +29,7 @@ class Message:
     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 = ...) \
-                    -> Optional[_PayloadType]: ...
+    def get_payload(self, i: int = ..., decode: bool = ...) -> Optional[_PayloadType]: ...
     def set_payload(self, payload: _PayloadType,
                     charset: _CharsetType = ...) -> None: ...
     def set_charset(self, charset: _CharsetType) -> None: ...
@@ -45,8 +44,7 @@ class Message:
     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 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: ...
diff --git a/typeshed/stdlib/3/functools.pyi b/typeshed/stdlib/3/functools.pyi
index b4295c4..be88c28 100644
--- a/typeshed/stdlib/3/functools.pyi
+++ b/typeshed/stdlib/3/functools.pyi
@@ -1,11 +1,5 @@
-# Stubs for functools (Python 3)
-
-# NOTE: These are incomplete!
-
-from abc import ABCMeta, abstractmethod
 import sys
-from typing import Any, Callable, Generic, Dict, Iterable, Mapping, Optional, Sequence, Tuple, TypeVar, NamedTuple, overload
-from collections import namedtuple
+from typing import Any, Callable, Generic, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, NamedTuple, Union, overload
 
 _AnyCallable = Callable[..., Any]
 
@@ -19,15 +13,17 @@ def reduce(function: Callable[[_T, _T], _T],
            sequence: Iterable[_T]) -> _T: ...
 
 
-class CacheInfo(NamedTuple('CacheInfo', [
-    ('hits', int), ('misses', int), ('maxsize', int), ('currsize', int)])
-):
-    ...
+class _CacheInfo(NamedTuple('CacheInfo', [
+    ('hits', int),
+    ('misses', int),
+    ('maxsize', int),
+    ('currsize', int)
+])): ...
 
 class _lru_cache_wrapper(Generic[_T]):
     __wrapped__ = ...  # type: Callable[..., _T]
     def __call__(self, *args: Any, **kwargs: Any) -> _T: ...
-    def cache_info(self) -> CacheInfo: ...
+    def cache_info(self) -> _CacheInfo: ...
 
 class lru_cache():
     def __init__(self, maxsize: Optional[int] = ..., typed: bool = ...) -> None: ...
@@ -51,6 +47,22 @@ class partial(Generic[_T]):
     def __call__(self, *args: Any, **kwargs: Any) -> _T: ...
 
 if sys.version_info >= (3, 4):
+    # With protocols, this could change into a generic protocol that defines __get__ and returns _T
+    _Descriptor = Any
+
+    class partialmethod(Generic[_T]):
+        func: Union[Callable[..., _T], _Descriptor]
+        args: Tuple[Any, ...]
+        keywords: Dict[str, Any]
+
+        @overload
+        def __init__(self, func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ...
+        @overload
+        def __init__(self, func: _Descriptor, *args: Any, **keywords: Any) -> None: ...
+        def __get__(self, obj: Any, cls: Type[Any]) -> Callable[..., _T]: ...
+        @property
+        def __isabstractmethod__(self) -> bool: ...
+
     class _SingleDispatchCallable(Generic[_T]):
         registry = ...  # type: Mapping[Any, Callable[..., _T]]
         def dispatch(self, cls: Any) -> Callable[..., _T]: ...
diff --git a/typeshed/stdlib/3/getpass.pyi b/typeshed/stdlib/3/getpass.pyi
index 73c0cb9..f55023c 100644
--- a/typeshed/stdlib/3/getpass.pyi
+++ b/typeshed/stdlib/3/getpass.pyi
@@ -1,9 +1,9 @@
 # Stubs for getpass
 
-from typing import TextIO
+from typing import Optional, TextIO
 
 
-def getpass(prompt: str = ..., stream: TextIO = None) -> str: ...
+def getpass(prompt: str = ..., stream: Optional[TextIO] = None) -> str: ...
 
 
 def getuser() -> str: ...
diff --git a/typeshed/stdlib/3/glob.pyi b/typeshed/stdlib/3/glob.pyi
index ab58e9a..f36d26c 100644
--- a/typeshed/stdlib/3/glob.pyi
+++ b/typeshed/stdlib/3/glob.pyi
@@ -4,6 +4,13 @@
 from typing import List, Iterator, AnyStr
 import sys
 
+if sys.version_info >= (3, 6):
+    def glob0(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ...
+else:
+    def glob0(dirname: AnyStr, basename: AnyStr) -> List[AnyStr]: ...
+
+def glob1(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ...
+
 if sys.version_info >= (3, 5):
     def glob(pathname: AnyStr, *, recursive: bool = ...) -> List[AnyStr]: ...
     def iglob(pathname: AnyStr, *, recursive: bool = ...) -> Iterator[AnyStr]: ...
diff --git a/typeshed/stdlib/3/grp.pyi b/typeshed/stdlib/3/grp.pyi
deleted file mode 100644
index ad14951..0000000
--- a/typeshed/stdlib/3/grp.pyi
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import List
-
-# TODO group database entry object type
-
-class struct_group:
-    gr_name = ...  # type: str
-    gr_passwd = ...  # type: str
-    gr_gid = 0
-    gr_mem = ...  # type: List[str]
-
-def getgrgid(gid: int) -> struct_group: ...
-def getgrnam(name: str) -> struct_group: ...
-def getgrall() -> List[struct_group]: ...
diff --git a/typeshed/stdlib/3/gzip.pyi b/typeshed/stdlib/3/gzip.pyi
index 44d8064..c4420fb 100644
--- a/typeshed/stdlib/3/gzip.pyi
+++ b/typeshed/stdlib/3/gzip.pyi
@@ -1,7 +1,3 @@
-# Stubs for gzip (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import _compression
 
diff --git a/typeshed/stdlib/3/hashlib.pyi b/typeshed/stdlib/3/hashlib.pyi
index fd47015..64ef707 100644
--- a/typeshed/stdlib/3/hashlib.pyi
+++ b/typeshed/stdlib/3/hashlib.pyi
@@ -1,11 +1,12 @@
 # Stubs for hashlib
 
+import sys
 from abc import abstractmethod, ABCMeta
-from typing import AbstractSet, Union
+from typing import AbstractSet, Optional, Union
 
 _DataType = Union[bytes, bytearray, memoryview]
 
-class Hash(metaclass=ABCMeta):
+class _Hash(metaclass=ABCMeta):
     digest_size = ...  # type: int
     block_size = ...  # type: int
 
@@ -21,20 +22,57 @@ class Hash(metaclass=ABCMeta):
     @abstractmethod
     def hexdigest(self) -> str: ...
     @abstractmethod
-    def copy(self) -> 'Hash': ...
+    def copy(self) -> _Hash: ...
 
-def md5(arg: _DataType = ...) -> Hash: ...
-def sha1(arg: _DataType = ...) -> Hash: ...
-def sha224(arg: _DataType = ...) -> Hash: ...
-def sha256(arg: _DataType = ...) -> Hash: ...
-def sha384(arg: _DataType = ...) -> Hash: ...
-def sha512(arg: _DataType = ...) -> Hash: ...
+def md5(arg: _DataType = ...) -> _Hash: ...
+def sha1(arg: _DataType = ...) -> _Hash: ...
+def sha224(arg: _DataType = ...) -> _Hash: ...
+def sha256(arg: _DataType = ...) -> _Hash: ...
+def sha384(arg: _DataType = ...) -> _Hash: ...
+def sha512(arg: _DataType = ...) -> _Hash: ...
 
-def new(name: str, data: _DataType = ...) -> Hash: ...
+def new(name: str, data: _DataType = ...) -> _Hash: ...
 
 # New in version 3.2
 algorithms_guaranteed = ...  # type: AbstractSet[str]
 algorithms_available = ...  # type: AbstractSet[str]
 
 # New in version 3.4
-def pbkdf2_hmac(name: str, password: _DataType, salt: _DataType, rounds: int, dklen: int = ...) -> bytes: ...
+if sys.version_info >= (3, 4):
+    def pbkdf2_hmac(hash_name: str, password: _DataType, salt: _DataType, iterations: int, dklen: Optional[int] = ...) -> bytes: ...
+
+if sys.version_info >= (3, 6):
+    class _VarLenHash(metaclass=ABCMeta):
+        digest_size = ...  # type: int
+        block_size = ...  # type: int
+        name = ...  # type: str
+
+        @abstractmethod
+        def digest(self, length: int) -> bytes: ...
+        @abstractmethod
+        def hexdigest(self, length: int) -> str: ...
+        @abstractmethod
+        def update(self, arg: _DataType) -> None: ...
+        @abstractmethod
+        def copy(self) -> _VarLenHash: ...
+
+    def sha3_224(arg: _DataType = ...) -> _Hash: ...
+    def sha3_256(arg: _DataType = ...) -> _Hash: ...
+    def sha3_384(arg: _DataType = ...) -> _Hash: ...
+    def sha3_512(arg: _DataType = ...) -> _Hash: ...
+
+    def shake_128(arg: _DataType = ...) -> _VarLenHash: ...
+    def shake_256(arg: _DataType = ...) -> _VarLenHash: ...
+
+    def scrypt(password: _DataType, *, salt: _DataType, n: int, r: int, p: int, maxmem: int = ..., dklen: int = ...) -> bytes: ...
+
+    class _BlakeHash(_Hash):
+        MAX_DIGEST_SIZE = ...  # type: int
+        MAX_KEY_SIZE = ...  # type: int
+        PERSON_SIZE = ...  # type: int
+        SALT_SIZE = ...  # type: int
+
+        def __init__(self, data: _DataType, digest_size: int = ..., key: _DataType = ..., salt: _DataType = ..., person: _DataType = ..., fanout: int = ..., depth: int = ..., leaf_size: int = ..., node_offset: int = ..., node_depth: int = ..., inner_size: int = ..., last_node: bool = ...) -> None: ...
+
+    blake2b = _BlakeHash
+    blake2s = _BlakeHash
diff --git a/typeshed/stdlib/3/html/entities.pyi b/typeshed/stdlib/3/html/entities.pyi
index b3fa66b..470217b 100644
--- a/typeshed/stdlib/3/html/entities.pyi
+++ b/typeshed/stdlib/3/html/entities.pyi
@@ -1,7 +1,3 @@
-# Stubs for html.entities (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 name2codepoint = ...  # type: Any
diff --git a/typeshed/stdlib/3/http/client.pyi b/typeshed/stdlib/3/http/client.pyi
index 340f090..30f45d8 100644
--- a/typeshed/stdlib/3/http/client.pyi
+++ b/typeshed/stdlib/3/http/client.pyi
@@ -1,5 +1,3 @@
-# Stubs for http.client (Python 3.4)
-
 from typing import (
     Any, Dict, IO, Iterable, List, Iterator, Mapping, Optional, Tuple, TypeVar,
     Union,
@@ -178,6 +176,7 @@ class HTTPSConnection(HTTPConnection):
                      check_hostname: Optional[bool] = ...) -> None: ...
 
 class HTTPException(Exception): ...
+error = HTTPException
 
 class NotConnected(HTTPException): ...
 class InvalidURL(HTTPException): ...
diff --git a/typeshed/stdlib/3/http/cookiejar.pyi b/typeshed/stdlib/3/http/cookiejar.pyi
index 38de5a3..801a5a6 100644
--- a/typeshed/stdlib/3/http/cookiejar.pyi
+++ b/typeshed/stdlib/3/http/cookiejar.pyi
@@ -83,8 +83,7 @@ class DefaultCookiePolicy(CookiePolicy):
     def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ...
     def is_blocked(self, domain: str) -> bool: ...
     def allowed_domains(self) -> Optional[Tuple[str, ...]]: ...
-    def set_allowed_domains(self, allowed_domains: Optional[Sequence[str]]) \
-                            -> None: ...
+    def set_allowed_domains(self, allowed_domains: Optional[Sequence[str]]) -> None: ...
     def is_not_allowed(self, domain: str) -> bool: ...
 
 
diff --git a/typeshed/stdlib/3/importlib/__init__.pyi b/typeshed/stdlib/3/importlib/__init__.pyi
index 7969a3c..08b3a81 100644
--- a/typeshed/stdlib/3/importlib/__init__.pyi
+++ b/typeshed/stdlib/3/importlib/__init__.pyi
@@ -1,16 +1,18 @@
+from importlib import util
 from importlib.abc import Loader
 import sys
 import types
 from typing import Any, Mapping, Optional, Sequence
 
-def __import__(name: str, globals: Mapping[str, Any] = None,
-               locals: Mapping[str, Any] = None, fromlist: Sequence[str] = (),
-               level: int = 0) -> types.ModuleType: ...
+def __import__(name: str, globals: Optional[Mapping[str, Any]] = None,
+               locals: Optional[Mapping[str, Any]] = None,
+               fromlist: Sequence[str] = ...,
+               level: int = ...) -> types.ModuleType: ...
 
-def import_module(name: str, package: str = None) -> types.ModuleType: ...
+def import_module(name: str, package: Optional[str] = None) -> types.ModuleType: ...
 
 if sys.version_info >= (3, 3):
-    def find_loader(name: str, path: str = None) -> Optional[Loader]: ...
+    def find_loader(name: str, path: Optional[str] = None) -> Optional[Loader]: ...
 
     def invalidate_caches() -> None: ...
 
diff --git a/typeshed/stdlib/3/importlib/abc.pyi b/typeshed/stdlib/3/importlib/abc.pyi
index 6ae74d6..f7cd81d 100644
--- a/typeshed/stdlib/3/importlib/abc.pyi
+++ b/typeshed/stdlib/3/importlib/abc.pyi
@@ -19,7 +19,7 @@ class Finder(metaclass=ABCMeta):
     # easier to simply ignore that this method exists.
     # @abstractmethod
     # def find_module(self, fullname: str,
-    #                 path: Sequence[_Path] = None) -> Optional[Loader]: ...
+    #                 path: Optional[Sequence[_Path]] = None) -> Optional[Loader]: ...
 
 class ResourceLoader(Loader):
     @abstractmethod
@@ -35,11 +35,11 @@ class InspectLoader(Loader):
         def exec_module(self, module: types.ModuleType) -> None: ...
     if sys.version_info[:2] == (3, 4):
         def source_to_code(self, data: Union[bytes, str],
-                           path: str = '<string>') -> types.CodeType: ...
+                           path: str = ...) -> types.CodeType: ...
     elif sys.version_info >= (3, 5):
         @staticmethod
         def source_to_code(data: Union[bytes, str],
-                           path: str = '<string>') -> types.CodeType: ...
+                           path: str = ...) -> types.CodeType: ...
 
 class ExecutionLoader(InspectLoader):
     @abstractmethod
@@ -64,7 +64,7 @@ if sys.version_info >= (3, 3):
             # Not defined on the actual class, but expected to exist.
             def find_spec(
                 self, fullname: str, path: Optional[Sequence[_Path]],
-                target: types.ModuleType = None
+                target: Optional[types.ModuleType] = None
             ) -> Optional[ModuleSpec]:
                 ...
 
@@ -78,7 +78,7 @@ if sys.version_info >= (3, 3):
             # Not defined on the actual class, but expected to exist.
             def find_spec(
                 self, fullname: str,
-                target: types.ModuleType = None
+                target: Optional[types.ModuleType] = None
             ) -> Optional[ModuleSpec]: ...
 
     class FileLoader(ResourceLoader, ExecutionLoader):
diff --git a/typeshed/stdlib/3/importlib/machinery.pyi b/typeshed/stdlib/3/importlib/machinery.pyi
index 78aaf80..f9e1907 100644
--- a/typeshed/stdlib/3/importlib/machinery.pyi
+++ b/typeshed/stdlib/3/importlib/machinery.pyi
@@ -22,7 +22,7 @@ if sys.version_info >= (3, 3):
             @classmethod
             def find_spec(cls, fullname: str,
                           path: Optional[Sequence[importlib.abc._Path]],
-                          target: types.ModuleType = None) -> Optional[ModuleSpec]:
+                          target: Optional[types.ModuleType] = None) -> Optional[ModuleSpec]:
                 ...
         # InspectLoader
         @classmethod
@@ -30,9 +30,9 @@ if sys.version_info >= (3, 3):
         @classmethod
         def load_module(cls, fullname: str) -> types.ModuleType: ...
         @classmethod
-        def get_code(cls, fullname: str) -> None: ...  # type: ignore
+        def get_code(cls, fullname: str) -> None: ...
         @classmethod
-        def get_source(cls, fullname: str) -> None: ...  # type: ignore
+        def get_source(cls, fullname: str) -> None: ...
         # Loader
         @classmethod
         def load_module(cls, fullname: str) -> types.ModuleType: ...
@@ -59,9 +59,9 @@ else:
         @classmethod
         def load_module(cls, fullname: str) -> types.ModuleType: ...
         @classmethod
-        def get_code(cls, fullname: str) -> None: ...  # type: ignore
+        def get_code(cls, fullname: str) -> None: ...
         @classmethod
-        def get_source(cls, fullname: str) -> None: ...  # type: ignore
+        def get_source(cls, fullname: str) -> None: ...
         # Loader
         @classmethod
         def load_module(cls, fullname: str) -> types.ModuleType: ...
@@ -79,7 +79,7 @@ if sys.version_info >= (3, 3):
             @classmethod
             def find_spec(cls, fullname: str,
                           path: Optional[Sequence[importlib.abc._Path]],
-                          target: types.ModuleType = None) -> Optional[ModuleSpec]:
+                          target: Optional[types.ModuleType] = None) -> Optional[ModuleSpec]:
                 ...
         # InspectLoader
         @classmethod
@@ -87,9 +87,9 @@ if sys.version_info >= (3, 3):
         @classmethod
         def load_module(cls, fullname: str) -> types.ModuleType: ...
         @classmethod
-        def get_code(cls, fullname: str) -> None: ...  # type: ignore
+        def get_code(cls, fullname: str) -> None: ...
         @classmethod
-        def get_source(cls, fullname: str) -> None: ...  # type: ignore
+        def get_source(cls, fullname: str) -> None: ...
         # Loader
         @classmethod
         def load_module(cls, fullname: str) -> types.ModuleType: ...
@@ -125,7 +125,7 @@ else:
         def load_module(cls, fullname: str) -> types.ModuleType: ...
 
 if sys.version_info >= (3, 3):
-    class WindowsRegisteryFinder(importlib.abc.MetaPathFinder):
+    class WindowsRegistryFinder(importlib.abc.MetaPathFinder):
         @classmethod
         def find_module(
             cls, fullname: str,
@@ -136,7 +136,7 @@ if sys.version_info >= (3, 3):
             @classmethod
             def find_spec(cls, fullname: str,
                           path: Optional[Sequence[importlib.abc._Path]],
-                          target: types.ModuleType = None) -> Optional[ModuleSpec]:
+                          target: Optional[types.ModuleType] = None) -> Optional[ModuleSpec]:
                 ...
 else:
     class WindowsRegisteryFinder:
diff --git a/typeshed/stdlib/3/importlib/util.pyi b/typeshed/stdlib/3/importlib/util.pyi
index 6f0232b..0a56b9c 100644
--- a/typeshed/stdlib/3/importlib/util.pyi
+++ b/typeshed/stdlib/3/importlib/util.pyi
@@ -20,22 +20,22 @@ if sys.version_info >= (3, 3):
 if sys.version_info >= (3, 4):
     MAGIC_NUMBER = ...  # type: bytes
 
-    def cache_from_source(path: str, debug_override: bool = None, *,
-                          optimization: Any = None) -> str: ...
+    def cache_from_source(path: str, debug_override: Optional[bool] = None, *,
+                          optimization: Optional[Any] = None) -> str: ...
     def source_from_cache(path: str) -> str: ...
     def decode_source(source_bytes: bytes) -> str: ...
     def find_spec(
-        name: str, package: str = None
+        name: str, package: Optional[str] = None
     ) -> importlib.machinery.ModuleSpec: ...
     def spec_from_loader(
         name: str, loader: Optional[importlib.abc.Loader], *,
-        origin: str = None, loader_state: Any = None,
-        is_package: bool = None
+        origin: Optional[str] = None, loader_state: Optional[Any] = None,
+        is_package: Optional[bool] = None
     ) -> importlib.machinery.ModuleSpec: ...
     def spec_from_file_location(
         name: str, location: str, *,
-        loader: importlib.abc.Loader = None,
-        submodule_search_locations: List[str]=None
+        loader: Optional[importlib.abc.Loader] = None,
+        submodule_search_locations: Optional[List[str]] = None
     ) -> importlib.machinery.ModuleSpec: ...
 
 if sys.version_info >= (3, 5):
diff --git a/typeshed/stdlib/3/inspect.pyi b/typeshed/stdlib/3/inspect.pyi
index ddf28b9..6b90ad9 100644
--- a/typeshed/stdlib/3/inspect.pyi
+++ b/typeshed/stdlib/3/inspect.pyi
@@ -1,5 +1,4 @@
-# Stubs for inspect
-
+import sys
 from typing import (AbstractSet, Any, Tuple, List, Dict, Callable, Generator,
                     Mapping, MutableMapping, NamedTuple, Optional, Sequence, Union,
                     )
@@ -8,15 +7,17 @@ from types import FrameType, ModuleType, TracebackType
 #
 # Types and members
 #
-ModuleInfo = NamedTuple('ModuleInfo', [('name', str),
-                                       ('suffix', str),
-                                       ('mode', str),
-                                       ('module_type', int),
-                                       ])
+if sys.version_info < (3, 6):
+    ModuleInfo = NamedTuple('ModuleInfo', [('name', str),
+                                           ('suffix', str),
+                                           ('mode', str),
+                                           ('module_type', int),
+                                           ])
+    def getmoduleinfo(path: str) -> Optional[ModuleInfo]: ...
+
 def getmembers(object: object,
                predicate: Callable[[Any], bool] = ...,
                ) -> List[Tuple[str, Any]]: ...
-def getmoduleinfo(path: str) -> Optional[ModuleInfo]: ...
 def getmodulename(path: str) -> Optional[str]: ...
 
 def ismodule(object: object) -> bool: ...
diff --git a/typeshed/stdlib/3/io.pyi b/typeshed/stdlib/3/io.pyi
index 1673853..4b1deb7 100644
--- a/typeshed/stdlib/3/io.pyi
+++ b/typeshed/stdlib/3/io.pyi
@@ -106,8 +106,8 @@ class BytesIO(BinaryIO):
     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: ...
+    def __exit__(self, t: Optional[type] = None, value: Optional[BaseException] = None,
+                 traceback: Optional[Any] = None) -> bool: ...
     def close(self) -> None: ...
     def fileno(self) -> int: ...
     def flush(self) -> None: ...
@@ -210,8 +210,8 @@ class TextIOWrapper(TextIO):
         write_through: bool = ...
     ) -> None: ...
     # copied from IOBase
-    def __exit__(self, t: type = None, value: BaseException = None,
-                 traceback: Any = None) -> bool: ...
+    def __exit__(self, t: Optional[type] = None, value: Optional[BaseException] = None,
+                 traceback: Optional[Any] = None) -> bool: ...
     def close(self) -> None: ...
     def fileno(self) -> int: ...
     def flush(self) -> None: ...
@@ -255,5 +255,6 @@ class StringIO(TextIOWrapper):
                  newline: Optional[str] = ...) -> None: ...
     name = ...  # type: str
     def getvalue(self) -> str: ...
+    def __enter__(self) -> 'StringIO': ...
 
 class IncrementalNewlineDecoder(codecs.IncrementalDecoder): ...
diff --git a/typeshed/stdlib/3/itertools.pyi b/typeshed/stdlib/3/itertools.pyi
index 774d68f..1f79cd2 100644
--- a/typeshed/stdlib/3/itertools.pyi
+++ b/typeshed/stdlib/3/itertools.pyi
@@ -29,7 +29,7 @@ class chain(Iterator[_T], Generic[_T]):
 def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ...
 def dropwhile(predicate: Callable[[_T], Any],
               iterable: Iterable[_T]) -> Iterator[_T]: ...
-def filterfalse(predicate: Callable[[_T], Any],
+def filterfalse(predicate: Optional[Callable[[_T], Any]],
                 iterable: Iterable[_T]) -> Iterator[_T]: ...
 
 @overload
@@ -51,7 +51,55 @@ def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ...
 def zip_longest(*p: Iterable[Any],
                 fillvalue: Any = ...) -> Iterator[Any]: ...
 
-def product(*p: Iterable[_T], repeat: int = ...) -> Iterator[Tuple[_T, ...]]: ...
+_T1 = TypeVar('_T1')
+_T2 = TypeVar('_T2')
+_T3 = TypeVar('_T3')
+_T4 = TypeVar('_T4')
+_T5 = TypeVar('_T5')
+_T6 = TypeVar('_T6')
+
+ at overload
+def product(iter1: Iterable[_T1], *,
+            repeat: int = ...) -> Iterator[Tuple[_T1]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2], *,
+            repeat: int = ...) -> Iterator[Tuple[_T1, _T2]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3], *,
+            repeat: int = ...) -> Iterator[Tuple[_T1, _T2, _T3]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3],
+            iter4: Iterable[_T4], *,
+            repeat: int = ...) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3],
+            iter4: Iterable[_T4],
+            iter5: Iterable[_T5], *,
+            repeat: int = ...) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ...
+ at overload
+def product(iter1: Iterable[_T1],
+            iter2: Iterable[_T2],
+            iter3: Iterable[_T3],
+            iter4: Iterable[_T4],
+            iter5: Iterable[_T5],
+            iter6: Iterable[_T6], *,
+            repeat: int = ...) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ...
+ at overload
+def product(iter1: Iterable[Any],
+            iter2: Iterable[Any],
+            iter3: Iterable[Any],
+            iter4: Iterable[Any],
+            iter5: Iterable[Any],
+            iter6: Iterable[Any],
+            iter7: Iterable[Any], *iterables: Iterable,
+            repeat: int = ...) -> Iterator[Tuple]: ...
 
 def permutations(iterable: Iterable[_T],
                  r: Optional[int] = ...) -> Iterator[Tuple[_T, ...]]: ...
diff --git a/typeshed/stdlib/3/json/decoder.pyi b/typeshed/stdlib/3/json/decoder.pyi
index 919039e..1c3e9a0 100644
--- a/typeshed/stdlib/3/json/decoder.pyi
+++ b/typeshed/stdlib/3/json/decoder.pyi
@@ -1,5 +1,5 @@
 import sys
-from typing import Any, Callable, Dict, List, Tuple
+from typing import Any, Callable, Dict, List, Optional, Tuple
 
 if sys.version_info >= (3, 5):
     class JSONDecodeError(ValueError):
@@ -18,11 +18,11 @@ class JSONDecoder:
     strict = ...  # type: bool
     object_pairs_hook = None  # type: Callable[[List[Tuple[str, Any]]], Any]
 
-    def __init__(self, object_hook: Callable[[Dict[str, Any]], Any]=None,
-            parse_float: Callable[[str], Any]=None,
-            parse_int: Callable[[str], Any]=None,
-            parse_constant: Callable[[str], Any]=None,
-            strict: bool=True,
-            object_pairs_hook: Callable[[List[Tuple[str, Any]]], Any]=None) -> None: ...
+    def __init__(self, object_hook: Optional[Callable[[Dict[str, Any]], Any]] = None,
+            parse_float: Optional[Callable[[str], Any]] = None,
+            parse_int: Optional[Callable[[str], Any]] = None,
+            parse_constant: Optional[Callable[[str], Any]] = None,
+            strict: bool = True,
+            object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = None) -> None: ...
     def decode(self, s: str) -> Any: ...
-    def raw_decode(self, s: str, idx: int=...) -> Tuple[Any, int]: ...
+    def raw_decode(self, s: str, idx: int = ...) -> Tuple[Any, int]: ...
diff --git a/typeshed/stdlib/3/json/encoder.pyi b/typeshed/stdlib/3/json/encoder.pyi
index f75304d..c423c18 100644
--- a/typeshed/stdlib/3/json/encoder.pyi
+++ b/typeshed/stdlib/3/json/encoder.pyi
@@ -1,4 +1,4 @@
-from typing import Any, Callable, Iterator, Tuple
+from typing import Any, Callable, Iterator, Optional, Tuple
 
 class JSONEncoder:
     item_separator = ...  # type: str
@@ -11,10 +11,10 @@ class JSONEncoder:
     sort_keys = ...  # type: bool
     indent = None  # type: int
 
-    def __init__(self, skipkeys: bool=..., ensure_ascii: bool=...,
-            check_circular: bool=..., allow_nan: bool=..., sort_keys: bool=...,
-            indent: int=None, separators: Tuple[str, str]=None, default: Callable=None) -> None: ...
+    def __init__(self, skipkeys: bool = ..., ensure_ascii: bool = ...,
+            check_circular: bool = ..., allow_nan: bool = ..., sort_keys: bool = ...,
+            indent: Optional[int] = None, separators: Optional[Tuple[str, str]] = None, default: Optional[Callable] = None) -> None: ...
 
     def default(self, o: Any) -> Any: ...
     def encode(self, o: Any) -> str: ...
-    def iterencode(self, o: Any, _one_shot: bool=False) -> Iterator[str]: ...
+    def iterencode(self, o: Any, _one_shot: bool = False) -> Iterator[str]: ...
diff --git a/typeshed/stdlib/3/linecache.pyi b/typeshed/stdlib/3/linecache.pyi
deleted file mode 100644
index 4f14f6a..0000000
--- a/typeshed/stdlib/3/linecache.pyi
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing import Any
-
-def getline(filename: str, lineno: int, module_globals: Any=...) -> str: ...
-def clearcache() -> None: ...
-def getlines(filename: str, module_globals: Any=...) -> None: ...
diff --git a/typeshed/stdlib/3/multiprocessing/__init__.pyi b/typeshed/stdlib/3/multiprocessing/__init__.pyi
index 8ab505e..167353a 100644
--- a/typeshed/stdlib/3/multiprocessing/__init__.pyi
+++ b/typeshed/stdlib/3/multiprocessing/__init__.pyi
@@ -1,62 +1,70 @@
 # Stubs for multiprocessing
 
-from typing import Any, Callable, Iterable, Mapping, Optional, Dict, List
+from typing import Any, Callable, Iterable, Mapping, Optional, Dict, List, Union
 
+from logging import Logger
+from multiprocessing.context import BaseContext
+from multiprocessing.managers import SyncManager
+from multiprocessing.pool import AsyncResult
 from multiprocessing.process import current_process as current_process
+import sys
 
 class Lock():
     def acquire(self, block: bool = ..., timeout: int = ...) -> None: ...
     def release(self) -> None: ...
+    def __enter__(self) -> 'Lock': ...
+    def __exit__(self, exc_type, exc_value, tb) -> None: ...
 
-class AsyncResult():
-    def get(self, timeout: float = -1) -> Any: ...
-    def wait(self, timeout: float = -1) -> None: ...
-    def ready(self) -> bool: ...
-    def successful(self) -> bool: ...
+class Event(object):
+    def __init__(self, *, ctx: BaseContext) -> None: ...
+    def is_set(self) -> bool: ...
+    def set(self) -> None: ...
+    def clear(self) -> None: ...
+    def wait(self, timeout: Optional[int] = ...) -> bool: ...
 
 class Pool():
-    def __init__(self, processes: Optional[int] = None,
-                 initializer: Optional[Callable[..., None]] = None,
-                 initargs: Iterable[Any] = (),
-                 maxtasksperchild: Optional[int] = None,
-                 context: Any = None) -> None: ...
+    def __init__(self, processes: Optional[int] = ...,
+                 initializer: Optional[Callable[..., None]] = ...,
+                 initargs: Iterable[Any] = ...,
+                 maxtasksperchild: Optional[int] = ...,
+                 context: Optional[Any] = None) -> None: ...
     def apply(self,
               func: Callable[..., Any],
-              args: Iterable[Any]=(),
+              args: Iterable[Any] = ...,
               kwds: Dict[str, Any]=...) -> Any: ...
     def apply_async(self,
                 func: Callable[..., Any],
-                args: Iterable[Any]=(),
-                kwds: Dict[str, Any]=...,
-                callback: Callable[..., None] = None,
-                error_callback: Callable[[BaseException], None] = None) -> AsyncResult: ...
+                args: Iterable[Any] = ...,
+                kwds: Dict[str, Any] = ...,
+                callback: Optional[Callable[..., None]] = None,
+                error_callback: Optional[Callable[[BaseException], None]] = None) -> AsyncResult: ...
     def map(self,
             func: Callable[..., Any],
-            iterable: Iterable[Any]=(),
-            chunksize: Optional[int] = None) -> List[Any]: ...
+            iterable: Iterable[Any] = ...,
+            chunksize: Optional[int] = ...) -> List[Any]: ...
     def map_async(self, func: Callable[..., Any],
-                  iterable: Iterable[Any] = (),
-                  chunksize: Optional[int] = None,
-                  callback: Callable[..., None] = None,
-                  error_callback: Callable[[BaseException], None] = None) -> AsyncResult: ...
+                  iterable: Iterable[Any] = ...,
+                  chunksize: Optional[int] = ...,
+                  callback: Optional[Callable[..., None]] = None,
+                  error_callback: Optional[Callable[[BaseException], None]] = None) -> AsyncResult: ...
     def imap(self,
              func: Callable[..., Any],
-             iterable: Iterable[Any]=(),
+             iterable: Iterable[Any] = ...,
              chunksize: Optional[int] = None) -> Iterable[Any]: ...
     def imap_unordered(self,
                        func: Callable[..., Any],
-                       iterable: Iterable[Any]=(),
+                       iterable: Iterable[Any] = ...,
                        chunksize: Optional[int] = None) -> Iterable[Any]: ...
     def starmap(self,
                 func: Callable[..., Any],
-                iterable: Iterable[Iterable[Any]]=(),
+                iterable: Iterable[Iterable[Any]] = ...,
                 chunksize: Optional[int] = None) -> List[Any]: ...
     def starmap_async(self,
                       func: Callable[..., Any],
-                      iterable: Iterable[Iterable[Any]] = (),
-                      chunksize: Optional[int] = None,
-                      callback: Callable[..., None] = None,
-                      error_callback: Callable[[BaseException], None] = None) -> AsyncResult: ...
+                      iterable: Iterable[Iterable[Any]] = ...,
+                      chunksize: Optional[int] = ...,
+                      callback: Optional[Callable[..., None]] = None,
+                      error_callback: Optional[Callable[[BaseException], None]] = None) -> AsyncResult: ...
     def close(self) -> None: ...
     def terminate(self) -> None: ...
     def join(self) -> None: ...
@@ -95,5 +103,18 @@ class Value():
     def __init__(self, typecode_or_type: str, *args: Any, lock: bool = ...) -> None: ...
 
 # ----- multiprocessing function stubs -----
+def active_children() -> List[Process]: ...
+def allow_connection_pickling() -> None: ...
 def cpu_count() -> int: ...
 def freeze_support() -> None: ...
+def get_logger() -> Logger: ...
+def log_to_stderr(level: Optional[Union[str, int]] = ...) -> Logger: ...
+def Manager() -> SyncManager: ...
+def set_forkserver_preload(module_names: List[str]) -> None: ...
+if sys.platform == 'win32' or sys.version_info >= (3, 4):
+    def set_executable(executable: str) -> None: ...
+if sys.version_info >= (3, 4):
+    def get_all_start_methods() -> List[str]: ...
+    def get_context(method: Optional[str] = ...) -> BaseContext: ...
+    def get_start_method(allow_none: Optional[bool]) -> Optional[str]: ...
+    def set_start_method(method: str, force: Optional[bool] = ...) -> None: ...
diff --git a/typeshed/stdlib/3/multiprocessing/context.pyi b/typeshed/stdlib/3/multiprocessing/context.pyi
new file mode 100644
index 0000000..bd1eed7
--- /dev/null
+++ b/typeshed/stdlib/3/multiprocessing/context.pyi
@@ -0,0 +1,163 @@
+# Stubs for multiprocessing.context
+
+from logging import Logger
+import multiprocessing
+import sys
+from typing import Any, Callable, Optional, List, Sequence, Tuple, Type, Union
+
+class ProcessError(Exception): ...
+
+class BufferTooShort(ProcessError): ...
+
+class TimeoutError(ProcessError): ...
+
+class AuthenticationError(ProcessError): ...
+
+class BaseContext(object):
+    ProcessError = ...  # type: Type[Exception]
+    BufferTooShort = ...  # type: Type[Exception]
+    TimeoutError = ...  # type: Type[Exception]
+    AuthenticationError = ...  # type: Type[Exception]
+
+    @staticmethod
+    def current_process() -> multiprocessing.Process: ...
+    @staticmethod
+    def active_children() -> List[multiprocessing.Process]: ...
+    def cpu_count(self) -> int: ...
+    # TODO: change return to SyncManager once a stub exists in multiprocessing.managers
+    def Manager(self) -> Any: ...
+    # TODO: change return to Pipe once a stub exists in multiprocessing.connection
+    def Pipe(self, duplex: bool) -> Any: ...
+    # TODO: change return to Lock once a stub exists in multiprocessing.synchronize
+    def Lock(self) -> Any: ...
+    # TODO: change return to RLock once a stub exists in multiprocessing.synchronize
+    def RLock(self) -> Any: ...
+    # TODO: change lock param to Optional[Union[Lock, RLock]] when stubs exists in multiprocessing.synchronize
+    # TODO: change return to Condition once a stub exists in multiprocessing.synchronize
+    def Condition(self, lock: Optional[Any] = ...) -> Any: ...
+    # TODO: change return to Semaphore once a stub exists in multiprocessing.synchronize
+    def Semaphore(self, value: int = ...) -> Any: ...
+    # TODO: change return to BoundedSemaphore once a stub exists in multiprocessing.synchronize
+    def BoundedSemaphore(self, value: int = ...) -> Any: ...
+    # TODO: change return to Event once a stub exists in multiprocessing.synchronize
+    def Event(self) -> Any: ...
+    # TODO: change return to Barrier once a stub exists in multiprocessing.synchronize
+    def Barrier(self, parties: int, action: Optional[Callable[..., Any]] = ..., timeout: Optional[int] = ...) -> Any: ...
+    # TODO: change return to Queue once a stub exists in multiprocessing.queues
+    def Queue(self, maxsize: int = ...) -> Any: ...
+    # TODO: change return to Queue once a stub exists in multiprocessing.queues
+    def JoinableQueue(self, maxsize: int = ...) -> Any: ...
+    # TODO: change return to SimpleQueue once a stub exists in multiprocessing.queues
+    def SimpleQueue(self) -> Any: ...
+    def Pool(
+        self,
+        processes: Optional[int] = ...,
+        initializer: Optional[Callable[..., Any]] = ...,
+        initargs: Tuple = ...,
+        maxtasksperchild: Optional[int] = ...
+    ) -> multiprocessing.Pool: ...
+    # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out
+    # how to handle the ctype
+    # TODO: change return to RawValue once a stub exists in multiprocessing.sharedctypes
+    def RawValue(self, typecode_or_type: Any, *args: Any) -> Any: ...
+    # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out
+    # how to handle the ctype
+    # TODO: change return to RawArray once a stub exists in multiprocessing.sharedctypes
+    def RawArray(self, typecode_or_type: Any, size_or_initializer: Union[int, Sequence[Any]]) -> Any: ...
+    # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out
+    # how to handle the ctype
+    # TODO: change return to Value once a stub exists in multiprocessing.sharedctypes
+    def Value(
+        self,
+        typecode_or_type: Any,
+        *args: Any,
+        lock: bool = ...
+    ) -> Any: ...
+    # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out
+    # how to handle the ctype
+    # TODO: change return to Array once a stub exists in multiprocessing.sharedctypes
+    def Array(
+        self,
+        typecode_or_type: Any,
+        size_or_initializer: Union[int, Sequence[Any]],
+        *,
+        lock: bool = ...
+    ) -> Any: ...
+    def freeze_support(self) -> None: ...
+    def get_logger(self) -> Logger: ...
+    def log_to_stderr(self, level: Optional[str] = ...) -> Logger: ...
+    def allow_connection_pickling(self) -> None: ...
+    def set_executable(self, executable: str) -> None: ...
+    def set_forkserver_preload(self, module_names: List[str]) -> None: ...
+    def get_context(self, method: Optional[str] = ...) -> BaseContext: ...
+    def get_start_method(self, allow_none: bool = ...) -> str: ...
+    def set_start_method(self, method: Optional[str] = ...) -> None: ...
+    @property
+    def reducer(self) -> str: ...
+    @reducer.setter
+    def reducer(self, reduction: str) -> None: ...
+    def _check_available(self) -> None: ...
+
+class Process(object):
+    _start_method: Optional[str]
+    @staticmethod
+    # TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+    def _Popen(process_obj: Any) -> DefaultContext: ...
+
+class DefaultContext(object):
+    Process = ...  # type: Type[multiprocessing.Process]
+
+    def __init__(self, context: BaseContext) -> None: ...
+    def get_context(self, method: Optional[str] = ...) -> BaseContext: ...
+    def set_start_method(self, method: str, force: bool = ...) -> None: ...
+    def get_start_method(self, allow_none: bool = ...) -> str: ...
+    def get_all_start_methods(self) -> List[str]: ...
+
+if sys.platform != 'win32':
+    # TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+    class ForkProcess(Any):  # type: ignore
+        _start_method: str
+        @staticmethod
+        def _Popen(process_obj: Any) -> Any: ...
+
+    # TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+    class SpawnProcess(Any):  # type: ignore
+        _start_method: str
+        @staticmethod
+        def _Popen(process_obj: Any) -> SpawnProcess: ...
+
+    # TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+    class ForkServerProcess(Any):  # type: ignore
+        _start_method: str
+        @staticmethod
+        def _Popen(process_obj: Any) -> Any: ...
+
+    class ForkContext(BaseContext):
+        _name: str
+        Process = ...  # type: Type[ForkProcess]
+
+    class SpawnContext(BaseContext):
+        _name: str
+        Process = ...  # type: Type[SpawnProcess]
+
+    class ForkServerContext(BaseContext):
+        _name: str
+        Process = ...  # type: Type[ForkServerProcess]
+else:
+    # TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+    class SpawnProcess(Any):  # type: ignore
+        _start_method: str
+        @staticmethod
+        # TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+        def _Popen(process_obj: Process) -> Any: ...
+
+    class SpawnContext(BaseContext):
+        _name: str
+        Process = ...  # type: Type[SpawnProcess]
+
+def _force_start_method(method: str) -> None: ...
+# TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+def get_spawning_popen() -> Optional[Any]: ...
+# TODO: type should be BaseProcess once a stub in multiprocessing.process exists
+def set_spawning_popen(popen: Any) -> None: ...
+def assert_spawning(obj: Any) -> None: ...
diff --git a/typeshed/stdlib/3/multiprocessing/managers.pyi b/typeshed/stdlib/3/multiprocessing/managers.pyi
index c5d053e..c2bad5b 100644
--- a/typeshed/stdlib/3/multiprocessing/managers.pyi
+++ b/typeshed/stdlib/3/multiprocessing/managers.pyi
@@ -2,9 +2,40 @@
 
 # NOTE: These are incomplete!
 
-from typing import Any
+import queue
+import threading
+from typing import (
+    Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, TypeVar
+)
+
+_T = TypeVar('_T')
+_KT = TypeVar('_KT')
+_VT = TypeVar('_VT')
+
+class Namespace: ...
+
+_Namespace = Namespace
 
 class BaseManager:
     def register(self, typeid: str, callable: Any = ...) -> None: ...
+    def shutdown(self) -> None: ...
+    def start(self, initializer: Optional[Callable[..., Any]] = ...,
+              initargs: Iterable[Any] = ...) -> None: ...
+    def __enter__(self) -> 'BaseManager': ...
+    def __exit__(self, exc_type, exc_value, tb) -> None: ...
+
+class SyncManager(BaseManager):
+    def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ...
+    def Condition(self, lock: Any = ...) -> threading.Condition: ...
+    def Event(self) -> threading.Event: ...
+    def Lock(self) -> threading.Lock: ...
+    def Namespace(self) -> _Namespace: ...
+    def Queue(self, maxsize: int = ...) -> queue.Queue: ...
+    def RLock(self) -> threading.RLock: ...
+    def Semaphore(self, value: Any = ...) -> threading.Semaphore: ...
+    def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ...
+    def Value(self, typecode: Any, value: _T) -> _T: ...
+    def dict(self, sequence: Mapping[_KT, _VT] = ...) -> Dict[_KT, _VT]: ...
+    def list(self, sequence: Sequence[_T] = ...) -> List[_T]: ...
 
 class RemoteError(Exception): ...
diff --git a/typeshed/stdlib/3/multiprocessing/pool.pyi b/typeshed/stdlib/3/multiprocessing/pool.pyi
index ed91749..c3b7893 100644
--- a/typeshed/stdlib/3/multiprocessing/pool.pyi
+++ b/typeshed/stdlib/3/multiprocessing/pool.pyi
@@ -5,52 +5,52 @@
 from typing import Any, Callable, Iterable, Mapping, Optional, Dict, List
 
 class AsyncResult():
-    def get(self, timeout: float = -1) -> Any: ...
-    def wait(self, timeout: float = -1) -> None: ...
+    def get(self, timeout: float = ...) -> Any: ...
+    def wait(self, timeout: float = ...) -> None: ...
     def ready(self) -> bool: ...
     def successful(self) -> bool: ...
 
 class ThreadPool():
     def __init__(self, processes: Optional[int] = None,
-                 initializer: Optional[Callable[..., None]] = None,
-                 initargs: Iterable[Any] = ()) -> None: ...
+                 initializer: Optional[Callable[..., Any]] = None,
+                 initargs: Iterable[Any] = ...) -> None: ...
     def apply(self,
               func: Callable[..., Any],
-              args: Iterable[Any]=(),
-              kwds: Dict[str, Any]=...) -> Any: ...
+              args: Iterable[Any] = ...,
+              kwds: Dict[str, Any] = ...) -> Any: ...
     def apply_async(self,
                 func: Callable[..., Any],
-                args: Iterable[Any]=(),
-                kwds: Dict[str, Any]=...,
-                callback: Callable[..., None] = None,
-                error_callback: Callable[[BaseException], None] = None) -> AsyncResult: ...
+                args: Iterable[Any] = ...,
+                kwds: Dict[str, Any] = ...,
+                callback: Optional[Callable[..., None]] = None,
+                error_callback: Optional[Callable[[BaseException], None]] = None) -> AsyncResult: ...
     def map(self,
             func: Callable[..., Any],
-            iterable: Iterable[Any]=(),
+            iterable: Iterable[Any] = ...,
             chunksize: Optional[int] = None) -> List[Any]: ...
     def map_async(self, func: Callable[..., Any],
-                  iterable: Iterable[Any] = (),
-                  chunksize: Optional[int] = None,
-                  callback: Callable[..., None] = None,
-                  error_callback: Callable[[BaseException], None] = None) -> AsyncResult: ...
+                  iterable: Iterable[Any] = ...,
+                  chunksize: Optional[Optional[int]] = None,
+                  callback: Optional[Callable[..., None]] = None,
+                  error_callback: Optional[Callable[[BaseException], None]] = None) -> AsyncResult: ...
     def imap(self,
              func: Callable[..., Any],
-             iterable: Iterable[Any]=(),
+             iterable: Iterable[Any] = ...,
              chunksize: Optional[int] = None) -> Iterable[Any]: ...
     def imap_unordered(self,
                        func: Callable[..., Any],
-                       iterable: Iterable[Any]=(),
+                       iterable: Iterable[Any] = ...,
                        chunksize: Optional[int] = None) -> Iterable[Any]: ...
     def starmap(self,
                 func: Callable[..., Any],
-                iterable: Iterable[Iterable[Any]]=(),
+                iterable: Iterable[Iterable[Any]] = ...,
                 chunksize: Optional[int] = None) -> List[Any]: ...
     def starmap_async(self,
                       func: Callable[..., Any],
-                      iterable: Iterable[Iterable[Any]] = (),
+                      iterable: Iterable[Iterable[Any]] = ...,
                       chunksize: Optional[int] = None,
-                      callback: Callable[..., None] = None,
-                      error_callback: Callable[[BaseException], None] = None) -> AsyncResult: ...
+                      callback: Optional[Callable[..., None]] = None,
+                      error_callback: Optional[Callable[[BaseException], None]] = None) -> AsyncResult: ...
     def close(self) -> None: ...
     def terminate(self) -> None: ...
     def join(self) -> None: ...
diff --git a/typeshed/stdlib/3/os/__init__.pyi b/typeshed/stdlib/3/os/__init__.pyi
index 827a817..3f4a35c 100644
--- a/typeshed/stdlib/3/os/__init__.pyi
+++ b/typeshed/stdlib/3/os/__init__.pyi
@@ -1,14 +1,12 @@
 # Stubs for os
 # Ron Murawski <ron at horizonchess.com>
 
-# based on http: //docs.python.org/3.2/library/os.html
-
 from builtins import OSError as error
 from io import TextIOWrapper as _TextIOWrapper
 import sys
 from typing import (
     Mapping, MutableMapping, Dict, List, Any, Tuple, Iterator, overload, Union, AnyStr,
-    Optional, Generic, Set, Callable, Text, Sequence, NamedTuple, TypeVar
+    Optional, Generic, Set, Callable, Text, Sequence, IO, NamedTuple, TypeVar
 )
 from . import path as path
 from mypy_extensions import NoReturn
@@ -17,102 +15,106 @@ _T = TypeVar('_T')
 
 # ----- os variables -----
 
-supports_bytes_environ = False  # TODO: True when bytes implemented?
+if sys.version_info >= (3, 2):
+    supports_bytes_environ: bool
 
 if sys.version_info >= (3, 3):
-    supports_dir_fd = ...  # type: Set[Callable[..., Any]]
-    supports_fd = ...  # type: Set[Callable[..., Any]]
-    supports_effective_ids = ...  # type: Set[Callable[..., Any]]
-    supports_follow_symlinks = ...  # type: Set[Callable[..., Any]]
-
-SEEK_SET = 0
-SEEK_CUR = 0
-SEEK_END = 0
-
-O_RDONLY = 0
-O_WRONLY = 0
-O_RDWR = 0
-O_APPEND = 0
-O_CREAT = 0
-O_EXCL = 0
-O_TRUNC = 0
-O_DSYNC = 0    # Unix only
-O_RSYNC = 0    # Unix only
-O_SYNC = 0     # Unix only
-O_NDELAY = 0   # Unix only
-O_NONBLOCK = 0  # Unix only
-O_NOCTTY = 0   # Unix only
-O_SHLOCK = 0   # Unix only
-O_EXLOCK = 0   # Unix only
-O_BINARY = 0     # Windows only
-O_NOINHERIT = 0  # Windows only
-O_SHORT_LIVED = 0  # Windows only
-O_TEMPORARY = 0  # Windows only
-O_RANDOM = 0     # Windows only
-O_SEQUENTIAL = 0  # Windows only
-O_TEXT = 0       # Windows only
-O_ASYNC = 0      # Gnu extension if in C library
-O_DIRECT = 0     # Gnu extension if in C library
-O_DIRECTORY = 0  # Gnu extension if in C library
-O_NOFOLLOW = 0   # Gnu extension if in C library
-O_NOATIME = 0    # Gnu extension if in C library
-
-curdir = ...  # type: str
-pardir = ...  # type: str
-sep = ...  # type: str
-altsep = ...  # type: str
-extsep = ...  # type: str
-pathsep = ...  # type: str
-defpath = ...  # type: str
-linesep = ...  # type: str
-devnull = ...  # type: str
-name = ...  # type: str
-
-F_OK = 0
-R_OK = 0
-W_OK = 0
-X_OK = 0
+    supports_dir_fd: Set[Callable[..., Any]]
+    supports_fd: Set[Callable[..., Any]]
+    supports_effective_ids: Set[Callable[..., Any]]
+    supports_follow_symlinks: Set[Callable[..., Any]]
+
+SEEK_SET: int
+SEEK_CUR: int
+SEEK_END: int
+
+O_RDONLY: int
+O_WRONLY: int
+O_RDWR: int
+O_APPEND: int
+O_CREAT: int
+O_EXCL: int
+O_TRUNC: int
+O_DSYNC: int    # Unix only
+O_RSYNC: int    # Unix only
+O_SYNC: int     # Unix only
+O_NDELAY: int   # Unix only
+O_NONBLOCK: int  # Unix only
+O_NOCTTY: int   # Unix only
+O_SHLOCK: int   # Unix only
+O_EXLOCK: int   # Unix only
+O_BINARY: int     # Windows only
+O_NOINHERIT: int  # Windows only
+O_SHORT_LIVED: int  # Windows only
+O_TEMPORARY: int  # Windows only
+O_RANDOM: int     # Windows only
+O_SEQUENTIAL: int  # Windows only
+O_TEXT: int       # Windows only
+O_ASYNC: int      # Gnu extension if in C library
+O_DIRECT: int     # Gnu extension if in C library
+O_DIRECTORY: int  # Gnu extension if in C library
+O_NOFOLLOW: int   # Gnu extension if in C library
+O_NOATIME: int    # Gnu extension if in C library
+O_LARGEFILE: int  # Gnu extension if in C library
+
+curdir: str
+pardir: str
+sep: str
+altsep: str
+extsep: str
+pathsep: str
+defpath: str
+linesep: str
+devnull: str
+name: str
+
+F_OK: int
+R_OK: int
+W_OK: int
+X_OK: int
 
 class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]):
     def copy(self) -> Dict[AnyStr, AnyStr]: ...
 
-environ = ...  # type: _Environ[str]
-environb = ...  # type: _Environ[bytes]
-
-confstr_names = ...  # type: Dict[str, int]  # Unix only
-pathconf_names = ...  # type: Dict[str, int]  # Unix only
-sysconf_names = ...  # type: Dict[str, int]  # Unix only
-
-EX_OK = 0        # Unix only
-EX_USAGE = 0     # Unix only
-EX_DATAERR = 0   # Unix only
-EX_NOINPUT = 0   # Unix only
-EX_NOUSER = 0    # Unix only
-EX_NOHOST = 0    # Unix only
-EX_UNAVAILABLE = 0  # Unix only
-EX_SOFTWARE = 0  # Unix only
-EX_OSERR = 0     # Unix only
-EX_OSFILE = 0    # Unix only
-EX_CANTCREAT = 0  # Unix only
-EX_IOERR = 0     # Unix only
-EX_TEMPFAIL = 0  # Unix only
-EX_PROTOCOL = 0  # Unix only
-EX_NOPERM = 0    # Unix only
-EX_CONFIG = 0    # Unix only
-EX_NOTFOUND = 0  # Unix only
-
-P_NOWAIT = 0
-P_NOWAITO = 0
-P_WAIT = 0
-# P_DETACH = 0  # Windows only
-# P_OVERLAY = 0  # Windows only
+environ: _Environ[str]
+if sys.version_info >= (3, 2):
+    environb: _Environ[bytes]
+
+confstr_names: Dict[str, int]  # Unix only
+pathconf_names: Dict[str, int]  # Unix only
+sysconf_names: Dict[str, int]  # Unix only
+
+EX_OK: int        # Unix only
+EX_USAGE: int     # Unix only
+EX_DATAERR: int   # Unix only
+EX_NOINPUT: int   # Unix only
+EX_NOUSER: int    # Unix only
+EX_NOHOST: int    # Unix only
+EX_UNAVAILABLE: int  # Unix only
+EX_SOFTWARE: int  # Unix only
+EX_OSERR: int     # Unix only
+EX_OSFILE: int    # Unix only
+EX_CANTCREAT: int  # Unix only
+EX_IOERR: int     # Unix only
+EX_TEMPFAIL: int  # Unix only
+EX_PROTOCOL: int  # Unix only
+EX_NOPERM: int    # Unix only
+EX_CONFIG: int    # Unix only
+EX_NOTFOUND: int  # Unix only
+
+P_NOWAIT: int
+P_NOWAITO: int
+P_WAIT: int
+if sys.platform == 'win32':
+    P_DETACH: int  # Windows only
+    P_OVERLAY: int  # Windows only
 
 # wait()/waitpid() options
-WNOHANG = 0  # Unix only
-# WCONTINUED = 0  # some Unix systems
-# WUNTRACED = 0  # Unix only
+WNOHANG: int  # Unix only
+WCONTINUED: int  # some Unix systems
+WUNTRACED: int  # Unix only
 
-TMP_MAX = 0  # Undocumented, but used by tempfile
+TMP_MAX: int  # Undocumented, but used by tempfile
 
 # ----- os classes (structures) -----
 if sys.version_info >= (3, 6):
@@ -125,8 +127,8 @@ if sys.version_info >= (3, 6):
         # This is what the scandir interator yields
         # The constructor is hidden
 
-        name = ...  # type: AnyStr
-        path = ...  # type: AnyStr
+        name: AnyStr
+        path: AnyStr
         def inode(self) -> int: ...
         def is_dir(self, follow_symlinks: bool = ...) -> bool: ...
         def is_file(self, follow_symlinks: bool = ...) -> bool: ...
@@ -139,8 +141,8 @@ elif sys.version_info >= (3, 5):
         # This is what the scandir interator yields
         # The constructor is hidden
 
-        name = ...  # type: AnyStr
-        path = ...  # type: AnyStr
+        name: AnyStr
+        path: AnyStr
         def inode(self) -> int: ...
         def is_dir(self, follow_symlinks: bool = ...) -> bool: ...
         def is_file(self, follow_symlinks: bool = ...) -> bool: ...
@@ -155,53 +157,53 @@ class stat_result:
     # st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime,
     # st_ctime. More items may be added at the end by some implementations.
 
-    st_mode = 0  # protection bits,
-    st_ino = 0  # inode number,
-    st_dev = 0  # device,
-    st_nlink = 0  # number of hard links,
-    st_uid = 0  # user id of owner,
-    st_gid = 0  # group id of owner,
-    st_size = 0  # size of file, in bytes,
-    st_atime = 0.0  # time of most recent access,
-    st_mtime = 0.0  # time of most recent content modification,
-    st_ctime = 0.0  # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows)
+    st_mode: int  # protection bits,
+    st_ino: int  # inode number,
+    st_dev: int  # device,
+    st_nlink: int  # number of hard links,
+    st_uid: int  # user id of owner,
+    st_gid: int  # group id of owner,
+    st_size: int  # size of file, in bytes,
+    st_atime: float  # time of most recent access,
+    st_mtime: float  # time of most recent content modification,
+    st_ctime: float  # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows)
 
     if sys.version_info >= (3, 3):
-        st_atime_ns = 0  # time of most recent access, in nanoseconds
-        st_mtime_ns = 0  # time of most recent content modification in nanoseconds
-        st_ctime_ns = 0  # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds
+        st_atime_ns: int  # time of most recent access, in nanoseconds
+        st_mtime_ns: int  # time of most recent content modification in nanoseconds
+        st_ctime_ns: int  # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds
 
     # not documented
     def __init__(self, tuple: Tuple[int, ...]) -> None: ...
 
     # On some Unix systems (such as Linux), the following attributes may also
     # be available:
-    st_blocks = 0  # number of blocks allocated for file
-    st_blksize = 0  # filesystem blocksize
-    st_rdev = 0  # type of device if an inode device
-    st_flags = 0  # user defined flags for file
+    st_blocks: int  # number of blocks allocated for file
+    st_blksize: int  # filesystem blocksize
+    st_rdev: int  # type of device if an inode device
+    st_flags: int  # user defined flags for file
 
     # On other Unix systems (such as FreeBSD), the following attributes may be
     # available (but may be only filled out if root tries to use them):
-    st_gen = 0  # file generation number
-    st_birthtime = 0  # time of file creation
+    st_gen: int  # file generation number
+    st_birthtime: int  # time of file creation
 
     # On Mac OS systems, the following attributes may also be available:
-    st_rsize = 0
-    st_creator = 0
-    st_type = 0
+    st_rsize: int
+    st_creator: int
+    st_type: int
 
 class statvfs_result:  # Unix only
-    f_bsize = 0
-    f_frsize = 0
-    f_blocks = 0
-    f_bfree = 0
-    f_bavail = 0
-    f_files = 0
-    f_ffree = 0
-    f_favail = 0
-    f_flag = 0
-    f_namemax = 0
+    f_bsize: int
+    f_frsize: int
+    f_blocks: int
+    f_bfree: int
+    f_bavail: int
+    f_files: int
+    f_ffree: int
+    f_favail: int
+    f_flag: int
+    f_namemax: int
 
 # ----- os function stubs -----
 if sys.version_info >= (3, 6):
@@ -253,7 +255,11 @@ def setsid() -> None: ...  # Unix only
 def setuid(uid: int) -> None: ...  # Unix only
 def strerror(code: int) -> str: ...
 def umask(mask: int) -> int: ...
-def uname() -> Tuple[str, str, str, str, str]: ...  # Unix only
+if sys.version_info >= (3, 3):
+    from posix import uname_result
+    def uname() -> uname_result: ...  # Unix only
+else:
+    def uname() -> Tuple[str, str, str, str, str]: ...  # Unix only
 
 @overload
 def getenv(key: Text) -> Optional[str]: ...
@@ -318,7 +324,10 @@ def mkdir(path: _PathType, mode: int = ...) -> None: ...
 def makedirs(path: _PathType, mode: int = ...,
              exist_ok: bool = ...) -> None: ...
 def pathconf(path: _PathType, name: Union[str, int]) -> int: ...  # Unix only
-def readlink(path: AnyStr) -> AnyStr: ...
+if sys.version_info >= (3, 6):
+    def readlink(path: Union[AnyStr, PathLike[AnyStr]]) -> AnyStr: ...
+else:
+    def readlink(path: AnyStr) -> AnyStr: ...
 def remove(path: _PathType) -> None: ...
 def removedirs(path: _PathType) -> None: ...
 def rename(src: _PathType, dst: _PathType) -> None: ...
@@ -338,12 +347,21 @@ def symlink(source: _PathType, link_name: _PathType,
             target_is_directory: bool = ...) -> None:
     ...  # final argument in Windows only
 def unlink(path: _PathType) -> None: ...
-def utime(path: _PathType, times: Optional[Tuple[float, float]] = ...) -> None: ...
+# TODO: add ns, dir_fd, follow_symlinks argument
+if sys.version_info >= (3, 0):
+    def utime(path: _PathType, times: Optional[Tuple[float, float]] = ...) -> None: ...
+else:
+    def utime(path: _PathType, times: Optional[Tuple[float, float]]) -> None: ...
 
-# TODO onerror: function from OSError to void
-def walk(top: AnyStr, topdown: bool = ..., onerror: Any = ...,
-         followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr],
-                                                    List[AnyStr]]]: ...
+if sys.version_info >= (3, 6):
+    def walk(top: Union[AnyStr, PathLike[AnyStr]], topdown: bool = ...,
+             onerror: Optional[Callable[[OSError], Any]] = ...,
+             followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr],
+                                                        List[AnyStr]]]: ...
+else:
+    def walk(top: AnyStr, topdown: bool = ..., onerror: Optional[Callable[[OSError], Any]] = ...,
+             followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr],
+                                                        List[AnyStr]]]: ...
 
 def abort() -> NoReturn: ...
 # These are defined as execl(file, *args) but the first *arg is mandatory.
@@ -370,11 +388,17 @@ def killpg(pgid: int, sig: int) -> None: ...  # Unix only
 def nice(increment: int) -> int: ...  # Unix only
 def plock(op: int) -> None: ...  # Unix only ???op is int?
 
-class popen(_TextIOWrapper):
-    # TODO 'b' modes or bytes command not accepted?
-    def __init__(self, command: str, mode: str = ...,
-                 bufsize: int = ...) -> None: ...
-    def close(self) -> Any: ...  # may return int
+if sys.version_info >= (3, 0):
+    class popen(_TextIOWrapper):
+        # TODO 'b' modes or bytes command not accepted?
+        def __init__(self, command: str, mode: str = ...,
+                     bufsize: int = ...) -> None: ...
+        def close(self) -> Any: ...  # may return int
+else:
+    def popen(command: str, *args, **kwargs) -> Optional[IO[Any]]: ...
+    def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ...
+    def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ...
+    def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ...
 
 def spawnl(mode: int, path: _PathType, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ...
 def spawnle(mode: int, path: _PathType, arg0: Union[bytes, Text],
@@ -410,13 +434,21 @@ def getloadavg() -> Tuple[float, float, float]: ...  # Unix only
 def sysconf(name: Union[str, int]) -> int: ...  # Unix only
 def urandom(n: int) -> bytes: ...
 
-def sched_getaffinity(id: int) -> Set[int]: ...
-class waitresult:
-    si_pid = 0
-def waitid(idtype: int, id: int, options: int) -> waitresult: ...
-P_ALL = 0
-WEXITED = 0
-WNOWAIT = 0
+if sys.version_info >= (3, 0):
+    def sched_getaffinity(id: int) -> Set[int]: ...
+if sys.version_info >= (3, 3):
+    class waitresult:
+        si_pid: int
+    def waitid(idtype: int, id: int, options: int) -> waitresult: ...
+
+if sys.version_info < (3, 0):
+    def tmpfile() -> IO[Any]: ...
+    def tmpnam() -> str: ...
+    def tempnam(dir: str = ..., prefix: str = ...) -> str: ...
+
+P_ALL: int
+WEXITED: int
+WNOWAIT: int
 
 if sys.version_info >= (3, 3):
     def sync() -> None: ...  # Unix only
diff --git a/typeshed/stdlib/3/os/path.pyi b/typeshed/stdlib/3/os/path.pyi
index eb930c7..961c7a8 100644
--- a/typeshed/stdlib/3/os/path.pyi
+++ b/typeshed/stdlib/3/os/path.pyi
@@ -60,12 +60,31 @@ def isdir(path: _PathType) -> bool: ...
 def islink(path: _PathType) -> bool: ...
 def ismount(path: _PathType) -> bool: ...
 
-def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ...
+if sys.version_info < (3, 0):
+    # Make sure signatures are disjunct, and allow combinations of bytes and unicode.
+    # (Since Python 2 allows that, too)
+    # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in
+    # a type error.
+    @overload
+    def join(__p1: bytes, *p: bytes) -> bytes: ...
+    @overload
+    def join(__p1: Text, *p: _PathType) -> Text: ...
+    @overload
+    def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ...
+    @overload
+    def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ...
+    @overload
+    def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ...
+else:
+    def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ...
 
 def normcase(path: AnyStr) -> AnyStr: ...
 def normpath(path: AnyStr) -> AnyStr: ...
-def realpath(path: AnyStr) -> AnyStr: ...
-def relpath(path: AnyStr, start: AnyStr = ...) -> AnyStr: ...
+if sys.platform == 'win32':
+    def realpath(path: AnyStr) -> AnyStr: ...
+else:
+    def realpath(filename: AnyStr) -> AnyStr: ...
+def relpath(path: AnyStr, start: _PathType = ...) -> AnyStr: ...
 
 def samefile(path1: _PathType, path2: _PathType) -> bool: ...
 def sameopenfile(fp1: int, fp2: int) -> bool: ...
diff --git a/typeshed/stdlib/3/pdb.pyi b/typeshed/stdlib/3/pdb.pyi
deleted file mode 100644
index 1c375fe..0000000
--- a/typeshed/stdlib/3/pdb.pyi
+++ /dev/null
@@ -1,30 +0,0 @@
-# Stub for pdb (incomplete, only some global functions)
-
-from typing import Any, Dict
-
-def run(statement: str,
-        globals: Dict[str, Any] = None,
-        locals: Dict[str, Any] = None) -> None:
-    ...
-
-def runeval(expression: str,
-            globals: Dict[str, Any] = None,
-            locals: Dict[str, Any] = None) -> Any:
-    ...
-
-def runctx(statement: str,
-        globals: Dict[str, Any],
-        locals: Dict[str, Any]) -> None:
-    ...
-
-def runcall(*args: Any, **kwds: Any) -> Any:
-    ...
-
-def set_trace() -> None:
-    ...
-
-def post_mortem(t: Any = None) -> None:
-    ...
-
-def pm() -> None:
-    ...
diff --git a/typeshed/stdlib/3/pickle.pyi b/typeshed/stdlib/3/pickle.pyi
deleted file mode 100644
index e6a14b2..0000000
--- a/typeshed/stdlib/3/pickle.pyi
+++ /dev/null
@@ -1,67 +0,0 @@
-# Stubs for pickle
-
-from typing import Any, IO, Union, Tuple, Callable, Optional, Iterator
-# Imports used in type comments only.
-from typing import Mapping  # noqa
-
-HIGHEST_PROTOCOL = ...  # type: int
-DEFAULT_PROTOCOL = ...  # type: int
-
-
-def dump(obj: Any, file: IO[bytes], protocol: int = None, *,
-         fix_imports: bool = ...) -> None: ...
-
-
-def dumps(obj: Any, protocol: int = ..., *,
-          fix_imports: bool = ...) -> bytes: ...
-
-
-def loads(bytes_object: bytes, *, fix_imports: bool = ...,
-          encoding: str = ..., errors: str = ...) -> Any: ...
-
-
-def load(file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ...,
-         errors: str = ...) -> Any: ...
-
-
-class PickleError(Exception):
-    pass
-
-
-class PicklingError(PickleError):
-    pass
-
-
-class UnpicklingError(PickleError):
-    pass
-
-
-_reducedtype = Union[str,
-                     Tuple[Callable[..., Any], Tuple],
-                     Tuple[Callable[..., Any], Tuple, Any],
-                     Tuple[Callable[..., Any], Tuple, Any,
-                           Optional[Iterator]],
-                     Tuple[Callable[..., Any], Tuple, Any,
-                           Optional[Iterator], Optional[Iterator]]]
-
-
-class Pickler:
-    dispatch_table = ...  # type: Mapping[type, Callable[[Any], _reducedtype]]
-
-    def __init__(self, file: IO[bytes], protocol: int = None, *,
-                 fix_imports: bool = ...) -> None: ...
-
-    def dump(self, obj: Any) -> None: ...
-
-    def persistent_id(self, obj: Any) -> Any: ...
-
-
-class Unpickler:
-    def __init__(self, file: IO[bytes], *, fix_imports: bool = ...,
-                 encoding: str = ..., errors: str = ...) -> None: ...
-
-    def load(self) -> Any: ...
-
-    def persistent_load(self, pid: Any) -> Any: ...
-
-    def find_class(self, module: str, name: str) -> Any: ...
diff --git a/typeshed/stdlib/3/posix.pyi b/typeshed/stdlib/3/posix.pyi
index 03e4523..09e2e4f 100644
--- a/typeshed/stdlib/3/posix.pyi
+++ b/typeshed/stdlib/3/posix.pyi
@@ -2,5 +2,11 @@
 
 # NOTE: These are incomplete!
 
+import sys
 import typing
 from os import stat_result
+from typing import NamedTuple
+
+if sys.version_info >= (3, 3):
+    uname_result = NamedTuple('uname_result', [('sysname', str), ('nodename', str),
+        ('release', str), ('version', str), ('machine', str)])
diff --git a/typeshed/stdlib/3/pwd.pyi b/typeshed/stdlib/3/pwd.pyi
deleted file mode 100644
index a5a8171..0000000
--- a/typeshed/stdlib/3/pwd.pyi
+++ /dev/null
@@ -1,18 +0,0 @@
-# Stubs for pwd
-
-# NOTE: These are incomplete!
-
-import typing
-
-class struct_passwd:
-    # TODO use namedtuple
-    pw_name = ...  # type: str
-    pw_passwd = ...  # type: str
-    pw_uid = 0
-    pw_gid = 0
-    pw_gecos = ...  # type: str
-    pw_dir = ...  # type: str
-    pw_shell = ...  # type: str
-
-def getpwuid(uid: int) -> struct_passwd: ...
-def getpwnam(name: str) -> struct_passwd: ...
diff --git a/typeshed/stdlib/3/queue.pyi b/typeshed/stdlib/3/queue.pyi
index 9827bc7..1d218c7 100644
--- a/typeshed/stdlib/3/queue.pyi
+++ b/typeshed/stdlib/3/queue.pyi
@@ -10,7 +10,9 @@ class Empty(Exception): ...
 class Full(Exception): ...
 
 class Queue(Generic[_T]):
+    maxsize = ...  # type: int
     def __init__(self, maxsize: int = ...) -> None: ...
+    def empty(self) -> bool: ...
     def full(self) -> bool: ...
     def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ...
     def get_nowait(self) -> _T: ...
diff --git a/typeshed/stdlib/3/random.pyi b/typeshed/stdlib/3/random.pyi
index f40d973..e32f1bb 100644
--- a/typeshed/stdlib/3/random.pyi
+++ b/typeshed/stdlib/3/random.pyi
@@ -7,8 +7,9 @@
 # ----- random classes -----
 
 import _random
+import sys
 from typing import (
-    Any, TypeVar, Sequence, List, Callable, AbstractSet, Union
+    Any, TypeVar, Sequence, List, Callable, AbstractSet, Union, Optional
 )
 
 _T = TypeVar('_T')
@@ -50,6 +51,8 @@ def getrandbits(k: int) -> int: ...
 def randrange(start: int, stop: Union[None, int] = ..., step: int = ...) -> int: ...
 def randint(a: int, b: int) -> int: ...
 def choice(seq: Sequence[_T]) -> _T: ...
+if sys.version_info >= (3, 6):
+    def choices(population: Sequence[_T], weights: Optional[Sequence[float]] = ..., *, cum_weights: Optional[Sequence[float]] = ..., k: int = ...) -> List[_T]: ...
 def shuffle(x: List[Any], random: Union[Callable[[], float], None] = ...) -> None: ...
 def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ...
 def random() -> float: ...
diff --git a/typeshed/stdlib/3/re.pyi b/typeshed/stdlib/3/re.pyi
index 5bdd083..68a06f7 100644
--- a/typeshed/stdlib/3/re.pyi
+++ b/typeshed/stdlib/3/re.pyi
@@ -7,7 +7,7 @@
 
 from typing import (
     List, Iterator, overload, Callable, Tuple, Sequence, Dict,
-    Generic, AnyStr, Match, Pattern, Any, Optional
+    Generic, AnyStr, Match, Pattern, Any, Optional, Union
 )
 
 # ----- re variables and constants -----
@@ -26,6 +26,8 @@ X = 0
 VERBOSE = 0
 U = 0
 UNICODE = 0
+T = 0
+TEMPLATE = 0
 
 class error(Exception): ...
 
@@ -104,3 +106,4 @@ def subn(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr],
 def escape(string: AnyStr) -> AnyStr: ...
 
 def purge() -> None: ...
+def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: int = ...) -> Pattern[AnyStr]: ...
diff --git a/typeshed/stdlib/3/runpy.pyi b/typeshed/stdlib/3/runpy.pyi
index 5768a4c..193a320 100644
--- a/typeshed/stdlib/3/runpy.pyi
+++ b/typeshed/stdlib/3/runpy.pyi
@@ -1,7 +1,3 @@
-# Stubs for runpy (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class _TempModule:
diff --git a/typeshed/stdlib/3/select.pyi b/typeshed/stdlib/3/select.pyi
deleted file mode 100644
index 83446f0..0000000
--- a/typeshed/stdlib/3/select.pyi
+++ /dev/null
@@ -1,27 +0,0 @@
-# Stubs for select
-
-# NOTE: These are incomplete!
-
-from typing import Any, Tuple, List, Sequence
-
-class error(Exception): ...
-
-POLLIN = 0
-POLLPRI = 0
-POLLOUT = 0
-POLLERR = 0
-POLLHUP = 0
-POLLNVAL = 0
-
-class poll:
-    def __init__(self) -> None: ...
-    def register(self, fd: Any,
-                 eventmask: int = ...) -> None: ...
-    def modify(self, fd: Any, eventmask: int) -> None: ...
-    def unregister(self, fd: Any) -> None: ...
-    def poll(self, timeout: int = ...) -> List[Tuple[int, int]]: ...
-
-def select(rlist: Sequence, wlist: Sequence, xlist: Sequence,
-           timeout: float = ...) -> Tuple[List[Any],
-                                           List[Any],
-                                           List[Any]]: ...
diff --git a/typeshed/stdlib/3/shutil.pyi b/typeshed/stdlib/3/shutil.pyi
index 2939a37..afb2e8e 100644
--- a/typeshed/stdlib/3/shutil.pyi
+++ b/typeshed/stdlib/3/shutil.pyi
@@ -80,9 +80,18 @@ if sys.version_info >= (3, 3):
     def which(cmd: _Path, mode: int = ...,
               path: Optional[_Path] = ...) -> Optional[str]: ...
 
-class Error(Exception): ...
 if sys.version_info >= (3, 4):
+    class Error(OSError): ...
     class SameFileError(Error): ...
+    class SpecialFileError(OSError): ...
+    class ExecError(OSError): ...
+    class ReadError(OSError): ...
+else:
+    class Error(EnvironmentError): ...
+    class SpecialFileError(EnvironmentError): ...
+    class ExecError(EnvironmentError): ...
+    class ReadError(EnvironmentError): ...
+class RegistryError(Exception): ...
 
 def make_archive(base_name: str, format: str, root_dir: _Path = ...,
                  base_dir: _Path = ..., verbose: bool = ...,
diff --git a/typeshed/stdlib/3/smtplib.pyi b/typeshed/stdlib/3/smtplib.pyi
index 56a4729..eea342e 100644
--- a/typeshed/stdlib/3/smtplib.pyi
+++ b/typeshed/stdlib/3/smtplib.pyi
@@ -1,7 +1,3 @@
-# Stubs for smtplib (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class SMTPException(OSError): ...
diff --git a/typeshed/stdlib/3/socketserver.pyi b/typeshed/stdlib/3/socketserver.pyi
index 14a739b..8d03b8f 100644
--- a/typeshed/stdlib/3/socketserver.pyi
+++ b/typeshed/stdlib/3/socketserver.pyi
@@ -50,15 +50,16 @@ class UDPServer(BaseServer):
                  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: ...
+if sys.platform != 'win32':
+    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 UnixDatagramServer(BaseServer):
+        def __init__(self, server_address: Tuple[str, int],
+                     RequestHandlerClass: type,
+                     bind_and_activate: bool = ...) -> None: ...
 
 class ForkingMixIn: ...
 class ThreadingMixIn: ...
@@ -67,6 +68,9 @@ class ForkingTCPServer(ForkingMixIn, TCPServer): ...
 class ForkingUDPServer(ForkingMixIn, UDPServer): ...
 class ThreadingTCPServer(ThreadingMixIn, TCPServer): ...
 class ThreadingUDPServer(ThreadingMixIn, UDPServer): ...
+if sys.platform != 'win32':
+    class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ...
+    class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ...
 
 
 class BaseRequestHandler:
diff --git a/typeshed/stdlib/3/spwd.pyi b/typeshed/stdlib/3/spwd.pyi
new file mode 100644
index 0000000..0e55d74
--- /dev/null
+++ b/typeshed/stdlib/3/spwd.pyi
@@ -0,0 +1,14 @@
+from typing import List, NamedTuple
+
+struct_spwd = NamedTuple("struct_spwd", [("sp_namp", str),
+                                         ("sp_pwdp", str),
+                                         ("sp_lstchg", int),
+                                         ("sp_min", int),
+                                         ("sp_max", int),
+                                         ("sp_warn", int),
+                                         ("sp_inact", int),
+                                         ("sp_expire", int),
+                                         ("sp_flag", int)])
+
+def getspall() -> List[struct_spwd]: ...
+def getspnam(name: str) -> struct_spwd: ...
diff --git a/typeshed/stdlib/3/sqlite3/__init__.pyi b/typeshed/stdlib/3/sqlite3/__init__.pyi
index fc22e5d..d5d20d6 100644
--- a/typeshed/stdlib/3/sqlite3/__init__.pyi
+++ b/typeshed/stdlib/3/sqlite3/__init__.pyi
@@ -1,5 +1 @@
-# Stubs for sqlite3 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from sqlite3.dbapi2 import *  # noqa: F403
diff --git a/typeshed/stdlib/3/sqlite3/dbapi2.pyi b/typeshed/stdlib/3/sqlite3/dbapi2.pyi
index 2c47843..fc748e2 100644
--- a/typeshed/stdlib/3/sqlite3/dbapi2.pyi
+++ b/typeshed/stdlib/3/sqlite3/dbapi2.pyi
@@ -1,12 +1,12 @@
 # Filip Hron <filip.hron at gmail.com>
 # based heavily on Andrey Vlasovskikh's python-skeletons https://github.com/JetBrains/python-skeletons/blob/master/sqlite3.py
 
-from typing import Any, Union, List, Iterator, Optional
-from numbers import Integral
+import sys
+from typing import Any, Union, List, Iterator, Optional, TypeVar, Callable
 from datetime import time, datetime
 from collections import Iterable
 
-import sys
+_T = TypeVar('_T')
 
 paramstyle = ...  # type: str
 threadsafety = ...  # type: int
@@ -74,9 +74,9 @@ else:
     def connect(database: Union[bytes, str], timeout: float = ..., detect_types: int = ..., isolation_level: Union[str, None] = ..., check_same_thread: bool = ..., factory: Union[Connection, None] = ..., cached_statements: int = ...) -> Connection: ...
 def enable_callback_tracebacks(flag: bool) -> None: ...
 def enable_shared_cache(do_enable: int) -> None: ...
-def register_adapter(type: type, callable: Any) -> None: ...
+def register_adapter(type: _T, callable: Callable[[_T], Union[int, float, str, bytes]]) -> None: ...
 # TODO: sqlite3.register_converter.__doc__ specifies callable as unknown
-def register_converter(typename: str, callable: bytes) -> None: ...
+def register_converter(typename: str, callable: Callable[[bytes], Any]) -> None: ...
 
 class Cache:
     def __init__(self, *args, **kwargs) -> None: ...
@@ -140,7 +140,7 @@ class Cursor(Iterator[Any]):
     def executemany(self, sql: str, seq_of_parameters: Iterable[Iterable]): ...
     def executescript(self, sql_script: Union[bytes, str]) -> Cursor: ...
     def fetchall(self) -> List[Any]: ...
-    def fetchmany(self, size: Integral = ...) -> List[Any]: ...
+    def fetchmany(self, size: Optional[int] = ...) -> List[Any]: ...
     def fetchone(self) -> Any: ...
     def setinputsizes(self, *args, **kwargs): ...
     def setoutputsize(self, *args, **kwargs): ...
diff --git a/typeshed/stdlib/3/ssl.pyi b/typeshed/stdlib/3/ssl.pyi
index 87ddd65..9880504 100644
--- a/typeshed/stdlib/3/ssl.pyi
+++ b/typeshed/stdlib/3/ssl.pyi
@@ -205,11 +205,9 @@ class SSLContext:
         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: ...
+                                  cadata: Union[str, bytes, None] = ...) -> None: ...
         def get_ca_certs(self,
-                         binary_form: bool = ...) \
-                         -> Union[List[_PeerCertRetDictType], List[bytes]]: ...
+                         binary_form: bool = ...) -> Union[List[_PeerCertRetDictType], List[bytes]]: ...
     else:
         def load_verify_locations(self,
                                   cafile: Optional[str] = ...,
@@ -220,8 +218,7 @@ class SSLContext:
         def set_alpn_protocols(self, protocols: List[str]) -> None: ...
     def set_npn_protocols(self, protocols: List[str]) -> None: ...
     def set_servername_callback(self,
-                                server_name_callback: Optional[_SrvnmeCbType]) \
-                                -> None: ...
+                                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 = ...,
diff --git a/typeshed/stdlib/3/subprocess.pyi b/typeshed/stdlib/3/subprocess.pyi
index 36e5c5c..75d19fe 100644
--- a/typeshed/stdlib/3/subprocess.pyi
+++ b/typeshed/stdlib/3/subprocess.pyi
@@ -5,7 +5,7 @@ import sys
 from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Optional, Union, List, Type, Text
 from types import TracebackType
 
-_FILE = Union[int, IO[Any]]
+_FILE = Union[None, int, IO[Any]]
 _TXT = Union[bytes, Text]
 _CMD = Union[_TXT, Sequence[_TXT]]
 _ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]
@@ -27,8 +27,8 @@ if sys.version_info >= (3, 5):
     if sys.version_info >= (3, 6):
         # Nearly same args as Popen.__init__ except for timeout, input, and check
         def run(args: _CMD,
-                timeout: float = ...,
-                input: _TXT = ...,
+                timeout: Optional[float] = ...,
+                input: Optional[_TXT] = ...,
                 check: bool = ...,
                 bufsize: int = ...,
                 executable: _TXT = ...,
@@ -38,8 +38,8 @@ if sys.version_info >= (3, 5):
                 preexec_fn: Callable[[], Any] = ...,
                 close_fds: bool = ...,
                 shell: bool = ...,
-                cwd: _TXT = ...,
-                env: _ENV = ...,
+                cwd: Optional[_TXT] = ...,
+                env: Optional[_ENV] = ...,
                 universal_newlines: bool = ...,
                 startupinfo: Any = ...,
                 creationflags: int = ...,
@@ -52,8 +52,8 @@ if sys.version_info >= (3, 5):
     else:
         # Nearly same args as Popen.__init__ except for timeout, input, and check
         def run(args: _CMD,
-                timeout: float = ...,
-                input: _TXT = ...,
+                timeout: Optional[float] = ...,
+                input: Optional[_TXT] = ...,
                 check: bool = ...,
                 bufsize: int = ...,
                 executable: _TXT = ...,
@@ -63,8 +63,8 @@ if sys.version_info >= (3, 5):
                 preexec_fn: Callable[[], Any] = ...,
                 close_fds: bool = ...,
                 shell: bool = ...,
-                cwd: _TXT = ...,
-                env: _ENV = ...,
+                cwd: Optional[_TXT] = ...,
+                env: Optional[_ENV] = ...,
                 universal_newlines: bool = ...,
                 startupinfo: Any = ...,
                 creationflags: int = ...,
@@ -84,8 +84,8 @@ if sys.version_info >= (3, 3):
              preexec_fn: Callable[[], Any] = ...,
              close_fds: bool = ...,
              shell: bool = ...,
-             cwd: _TXT = ...,
-             env: _ENV = ...,
+             cwd: Optional[_TXT] = ...,
+             env: Optional[_ENV] = ...,
              universal_newlines: bool = ...,
              startupinfo: Any = ...,
              creationflags: int = ...,
@@ -103,8 +103,8 @@ else:
              preexec_fn: Callable[[], Any] = ...,
              close_fds: bool = ...,
              shell: bool = ...,
-             cwd: _TXT = ...,
-             env: _ENV = ...,
+             cwd: Optional[_TXT] = ...,
+             env: Optional[_ENV] = ...,
              universal_newlines: bool = ...,
              startupinfo: Any = ...,
              creationflags: int = ...,
@@ -124,8 +124,8 @@ if sys.version_info >= (3, 3):
                    preexec_fn: Callable[[], Any] = ...,
                    close_fds: bool = ...,
                    shell: bool = ...,
-                   cwd: _TXT = ...,
-                   env: _ENV = ...,
+                   cwd: Optional[_TXT] = ...,
+                   env: Optional[_ENV] = ...,
                    universal_newlines: bool = ...,
                    startupinfo: Any = ...,
                    creationflags: int = ...,
@@ -143,8 +143,8 @@ else:
                    preexec_fn: Callable[[], Any] = ...,
                    close_fds: bool = ...,
                    shell: bool = ...,
-                   cwd: _TXT = ...,
-                   env: _ENV = ...,
+                   cwd: Optional[_TXT] = ...,
+                   env: Optional[_ENV] = ...,
                    universal_newlines: bool = ...,
                    startupinfo: Any = ...,
                    creationflags: int = ...,
@@ -162,8 +162,8 @@ if sys.version_info >= (3, 6):
                      preexec_fn: Callable[[], Any] = ...,
                      close_fds: bool = ...,
                      shell: bool = ...,
-                     cwd: _TXT = ...,
-                     env: _ENV = ...,
+                     cwd: Optional[_TXT] = ...,
+                     env: Optional[_ENV] = ...,
                      universal_newlines: bool = ...,
                      startupinfo: Any = ...,
                      creationflags: int = ...,
@@ -186,8 +186,8 @@ elif sys.version_info >= (3, 4):
                      preexec_fn: Callable[[], Any] = ...,
                      close_fds: bool = ...,
                      shell: bool = ...,
-                     cwd: _TXT = ...,
-                     env: _ENV = ...,
+                     cwd: Optional[_TXT] = ...,
+                     env: Optional[_ENV] = ...,
                      universal_newlines: bool = ...,
                      startupinfo: Any = ...,
                      creationflags: int = ...,
@@ -207,8 +207,8 @@ elif sys.version_info >= (3, 3):
                      preexec_fn: Callable[[], Any] = ...,
                      close_fds: bool = ...,
                      shell: bool = ...,
-                     cwd: _TXT = ...,
-                     env: _ENV = ...,
+                     cwd: Optional[_TXT] = ...,
+                     env: Optional[_ENV] = ...,
                      universal_newlines: bool = ...,
                      startupinfo: Any = ...,
                      creationflags: int = ...,
@@ -227,8 +227,8 @@ else:
                      preexec_fn: Callable[[], Any] = ...,
                      close_fds: bool = ...,
                      shell: bool = ...,
-                     cwd: _TXT = ...,
-                     env: _ENV = ...,
+                     cwd: Optional[_TXT] = ...,
+                     env: Optional[_ENV] = ...,
                      universal_newlines: bool = ...,
                      startupinfo: Any = ...,
                      creationflags: int = ...,
@@ -266,6 +266,8 @@ class CalledProcessError(Exception):
                  stderr: Optional[_TXT] = ...) -> None: ...
 
 class Popen:
+    if sys.version_info >= (3, 3):
+        args = ...  # type: _CMD
     stdin = ...  # type: IO[Any]
     stdout = ...  # type: IO[Any]
     stderr = ...  # type: IO[Any]
diff --git a/typeshed/stdlib/3/tempfile.pyi b/typeshed/stdlib/3/tempfile.pyi
index ab8c380..7c96260 100644
--- a/typeshed/stdlib/3/tempfile.pyi
+++ b/typeshed/stdlib/3/tempfile.pyi
@@ -8,6 +8,7 @@ from types import TracebackType
 from typing import Any, AnyStr, Generic, IO, Optional, Tuple, Type
 
 # global variables
+TMP_MAX: int
 tempdir = ...  # type: Optional[str]
 template = ...  # type: str
 
diff --git a/typeshed/stdlib/3/time.pyi b/typeshed/stdlib/3/time.pyi
index 57884b2..597fb8e 100644
--- a/typeshed/stdlib/3/time.pyi
+++ b/typeshed/stdlib/3/time.pyi
@@ -45,6 +45,15 @@ if sys.version_info >= (3, 3):
             ],
             _arg: Any = ...,
         ) -> None: ...
+        def __new__(
+            cls,
+            o: Union[
+                Tuple[int, int, int, int, int, int, int, int, int],
+                Tuple[int, int, int, int, int, int, int, int, int, str],
+                Tuple[int, int, int, int, int, int, int, int, int, str, int]
+            ],
+            _arg: Any = ...,
+        ) -> struct_time: ...
 else:
     class struct_time(
         NamedTuple(
@@ -55,6 +64,7 @@ else:
         )
     ):
         def __init__(self, o: TimeTuple, _arg: Any = ...) -> None: ...
+        def __new__(cls, o: TimeTuple, _arg: Any = ...) -> struct_time: ...
 
 
 # ----- functions -----
diff --git a/typeshed/stdlib/3/tkinter/__init__.pyi b/typeshed/stdlib/3/tkinter/__init__.pyi
index ec61243..4ef7079 100644
--- a/typeshed/stdlib/3/tkinter/__init__.pyi
+++ b/typeshed/stdlib/3/tkinter/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for tkinter (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from tkinter.constants import *  # noqa: F403
 
diff --git a/typeshed/stdlib/3/tkinter/constants.pyi b/typeshed/stdlib/3/tkinter/constants.pyi
index 77645ef..d613dc6 100644
--- a/typeshed/stdlib/3/tkinter/constants.pyi
+++ b/typeshed/stdlib/3/tkinter/constants.pyi
@@ -1,7 +1,3 @@
-# Stubs for tkinter.constants (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 NO = ...  # type: Any
diff --git a/typeshed/stdlib/3/tkinter/ttk.pyi b/typeshed/stdlib/3/tkinter/ttk.pyi
index 099f308..2ce9dc0 100644
--- a/typeshed/stdlib/3/tkinter/ttk.pyi
+++ b/typeshed/stdlib/3/tkinter/ttk.pyi
@@ -1,7 +1,3 @@
-# Stubs for tkinter.ttk (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import tkinter
 
diff --git a/typeshed/stdlib/3/tokenize.pyi b/typeshed/stdlib/3/tokenize.pyi
index 8e8fc13..bf1339f 100644
--- a/typeshed/stdlib/3/tokenize.pyi
+++ b/typeshed/stdlib/3/tokenize.pyi
@@ -1,7 +1,3 @@
-# Stubs for tokenize (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Callable, Generator, Iterable, List, NamedTuple, Optional, Union, Sequence, TextIO, Tuple
 from builtins import open as _builtin_open
 from token import *  # noqa: F403
@@ -43,6 +39,7 @@ class Untokenizer:
 def untokenize(iterable: Iterable[_Token]) -> Any: ...
 def detect_encoding(readline: Callable[[], bytes]) -> Tuple[str, Sequence[bytes]]: ...
 def tokenize(readline: Callable[[], bytes]) -> Generator[TokenInfo, None, None]: ...
+def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo, None, None]: ...
 
 def open(filename: Union[str, bytes, int]) -> TextIO: ...
 
diff --git a/typeshed/stdlib/3/types.pyi b/typeshed/stdlib/3/types.pyi
index 084a1b4..9894742 100644
--- a/typeshed/stdlib/3/types.pyi
+++ b/typeshed/stdlib/3/types.pyi
@@ -5,8 +5,8 @@
 
 import sys
 from typing import (
-    Any, Callable, Dict, Generic, Iterator, Mapping, Optional, Tuple, TypeVar,
-    Union, overload
+    Any, Awaitable, Callable, Dict, Generic, Iterator, Mapping, Optional, Tuple, TypeVar,
+    Union, overload, Type
 )
 
 # ModuleType is exported from this module, but for circular import
@@ -14,6 +14,8 @@ from typing import (
 from _importlib_modulespec import ModuleType as ModuleType  # Exported
 
 _T = TypeVar('_T')
+_T_co = TypeVar('_T_co', covariant=True)
+_T_contra = TypeVar('_T_contra', contravariant=True)
 _KT = TypeVar('_KT')
 _VT = TypeVar('_VT')
 
@@ -92,6 +94,21 @@ class GeneratorType:
     @overload
     def throw(self, typ: type, val: BaseException = ..., tb: 'TracebackType' = ...) -> Any: ...
 
+if sys.version_info >= (3, 6):
+    class AsyncGeneratorType(Generic[_T_co, _T_contra]):
+        ag_await: Optional[Awaitable[Any]]
+        ag_frame: FrameType
+        ag_running: bool
+        ag_code: CodeType
+        def __aiter__(self) -> Awaitable[AsyncGeneratorType[_T_co, _T_contra]]: ...
+        def __anext__(self) -> Awaitable[_T_co]: ...
+        def asend(self, val: _T_contra) -> Awaitable[_T_co]: ...
+        @overload
+        def athrow(self, val: BaseException) -> Awaitable[_T_co]: ...
+        @overload
+        def athrow(self, typ: Type[BaseException], val: BaseException, tb: TracebackType = ...) -> Awaitable[_T_co]: ...
+        def aclose(self) -> Awaitable[_T_co]: ...
+
 class CoroutineType:
     cr_await = ...  # type: Optional[Any]
     cr_code = ...  # type: CodeType
@@ -104,9 +121,25 @@ class CoroutineType:
     @overload
     def throw(self, typ: type, val: BaseException = ..., tb: 'TracebackType' = ...) -> Any: ...
 
+class _StaticFunctionType:
+    """Fictional type to correct the type of MethodType.__func__.
+
+    FunctionType is a descriptor, so mypy follows the descriptor protocol and
+    converts MethodType.__func__ back to MethodType (the return type of
+    FunctionType.__get__). But this is actually a special case; MethodType is
+    implemented in C and its attribute access doesn't go through
+    __getattribute__.
+
+    By wrapping FunctionType in _StaticFunctionType, we get the right result;
+    similar to wrapping a function in staticmethod() at runtime to prevent it
+    being bound as a method.
+    """
+    def __get__(self, obj: Optional[object], type: Optional[type]) -> 'FunctionType': ...
+
 class MethodType:
-    __func__ = ...  # type: FunctionType
+    __func__ = ...  # type: _StaticFunctionType
     __self__ = ...  # type: object
+    __name__ = ...  # type: str
     def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
 class BuiltinFunctionType:
     __self__ = ...  # type: Union[object, ModuleType]
diff --git a/typeshed/stdlib/3/typing.pyi b/typeshed/stdlib/3/typing.pyi
index e57bcc1..b8d7327 100644
--- a/typeshed/stdlib/3/typing.pyi
+++ b/typeshed/stdlib/3/typing.pyi
@@ -2,7 +2,8 @@
 
 import sys
 from abc import abstractmethod, ABCMeta
-from types import CodeType, FrameType
+from types import CodeType, FrameType, TracebackType
+import collections  # Needed by aliases like DefaultDict, see mypy issue 2986
 
 # Definitions of special type checking related constructs.  Their definition
 # are not used, so their value does not matter.
@@ -10,13 +11,17 @@ from types import CodeType, FrameType
 overload = object()
 Any = object()
 TypeVar = object()
-Generic = object()
-Tuple = object()
-Callable = object()
-Type = object()
 _promote = object()
 no_type_check = object()
-ClassVar = object()
+
+class _SpecialForm:
+    def __getitem__(self, typeargs: Any) -> Any: ...
+
+Tuple: _SpecialForm = ...
+Generic: _SpecialForm = ...
+Callable: _SpecialForm = ...
+Type: _SpecialForm = ...
+ClassVar: _SpecialForm = ...
 
 class GenericMeta(type): ...
 
@@ -127,7 +132,7 @@ class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
     gi_yieldfrom = ...  # type: Optional[Generator]
 
 # TODO: Several types should only be defined if sys.python_version >= (3, 5):
-# Awaitable, AsyncIterator, AsyncIterable, Coroutine, Collection, ContextManager.
+# Awaitable, AsyncIterator, AsyncIterable, Coroutine, Collection.
 # See https: //github.com/python/typeshed/issues/655 for why this is not easy.
 
 class Awaitable(Generic[_T_co]):
@@ -155,7 +160,7 @@ class AwaitableGenerator(Generator[_T_co, _T_contra, _V_co], Awaitable[_V_co],
 
 class AsyncIterable(Generic[_T_co]):
     @abstractmethod
-    def __anext__(self) -> Awaitable[_T_co]: ...
+    def __aiter__(self) -> 'AsyncIterator[_T_co]': ...
 
 class AsyncIterator(AsyncIterable[_T_co],
                     Generic[_T_co]):
@@ -281,7 +286,18 @@ class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]):
     def __contains__(self, o: object) -> bool: ...
     def __iter__(self) -> Iterator[_VT_co]: ...
 
-# TODO: ContextManager (only if contextlib.AbstractContextManager exists)
+class ContextManager(Generic[_T_co]):
+    def __enter__(self) -> _T_co: ...
+    def __exit__(self, exc_type: Optional[Type[BaseException]],
+                 exc_value: Optional[BaseException],
+                 traceback: Optional[TracebackType]) -> Optional[bool]: ...
+
+if sys.version_info >= (3, 5):
+    class AsyncContextManager(Generic[_T_co]):
+        def __aenter__(self) -> Awaitable[_T_co]: ...
+        def __aexit__(self, exc_type: Optional[Type[BaseException]],
+                      exc_value: Optional[BaseException],
+                      traceback: Optional[TracebackType]) -> Awaitable[Optional[bool]]: ...
 
 class Mapping(_Collection[_KT], Generic[_KT, _VT_co]):
     # TODO: We wish the key type could also be covariant, but that doesn't work,
@@ -290,9 +306,9 @@ class Mapping(_Collection[_KT], Generic[_KT, _VT_co]):
     def __getitem__(self, k: _KT) -> _VT_co:
         ...
     # Mixin methods
-    @overload  # type: ignore
+    @overload
     def get(self, k: _KT) -> Optional[_VT_co]: ...
-    @overload  # type: ignore
+    @overload
     def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ...
     def items(self) -> AbstractSet[Tuple[_KT, _VT_co]]: ...
     def keys(self) -> AbstractSet[_KT]: ...
@@ -323,9 +339,11 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]):
     # known to be a Mapping with unknown type parameters, which is closer
     # to the behavior we want. See mypy issue  #1430.
     @overload
-    def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
+    @overload
+    def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
     @overload
-    def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ...
+    def update(self, **kwargs: _VT) -> None: ...
 
 Text = str
 
@@ -482,7 +500,8 @@ class Pattern(Generic[AnyStr]):
 
 # Functions
 
-def get_type_hints(obj: Callable) -> dict[str, Any]: ...
+def get_type_hints(obj: Callable, globalns: Optional[dict[str, Any]] = ...,
+                   localns: Optional[dict[str, Any]] = ...) -> dict[str, Any]: ...
 
 def cast(tp: Type[_T], obj: Any) -> _T: ...
 
@@ -491,9 +510,10 @@ def cast(tp: Type[_T], obj: Any) -> _T: ...
 # NamedTuple is special-cased in the type checker
 class NamedTuple(tuple):
     _fields = ...  # type: Tuple[str, ...]
+    _source = ...  # type: str
 
-    def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]], *,
-                 verbose: bool = ..., rename: bool = ..., module: Any = ...) -> None: ...
+    def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]] = ..., *,
+                 verbose: bool = ..., rename: bool = ..., **kwargs: Any) -> None: ...
 
     @classmethod
     def _make(cls, iterable: Iterable[Any]) -> NamedTuple: ...
diff --git a/typeshed/stdlib/3/unittest/__init__.pyi b/typeshed/stdlib/3/unittest/__init__.pyi
index f27ee66..68d1f56 100644
--- a/typeshed/stdlib/3/unittest/__init__.pyi
+++ b/typeshed/stdlib/3/unittest/__init__.pyi
@@ -3,12 +3,11 @@
 from typing import (
     Any, Callable, Dict, Iterable, Iterator, List, Optional, Pattern, Sequence,
     Set, FrozenSet, TextIO, Tuple, Type, TypeVar, Union, Generic,
-    overload,
+    overload, ContextManager
 )
 import logging
 import sys
 from types import ModuleType, TracebackType
-from contextlib import ContextManager
 
 
 _T = TypeVar('_T')
diff --git a/typeshed/stdlib/3/unittest/mock.pyi b/typeshed/stdlib/3/unittest/mock.pyi
index 84fe40e..38b4669 100644
--- a/typeshed/stdlib/3/unittest/mock.pyi
+++ b/typeshed/stdlib/3/unittest/mock.pyi
@@ -1,7 +1,7 @@
 # Stubs for unittest.mock
 
 import sys
-from typing import Any
+from typing import Any, Optional
 
 if sys.version_info >= (3, 3):
     FILTER_DIR = ...  # type: Any
@@ -33,7 +33,7 @@ if sys.version_info >= (3, 3):
 
     class NonCallableMock(Any):
         def __new__(cls, *args: Any, **kw: Any) -> Any: ...
-        def __init__(self, spec: Any = None, wraps: Any = None, name: Any = None, spec_set: Any = None, parent: Any = None, _spec_state: Any = None, _new_name: Any ='', _new_parent: Any = None, _spec_as_instance: Any = False, _eat_self: Any = None, unsafe: Any = False, **kwargs: Any) -> None: ...
+        def __init__(self, spec: Optional[Any] = None, wraps: Optional[Any] = None, name: Optional[Any] = None, spec_set: Optional[Any] = None, parent: Optional[Any] = None, _spec_state: Optional[Any] = None, _new_name: Any ='', _new_parent: Optional[Any] = None, _spec_as_instance: Any = False, _eat_self: Optional[Any] = None, unsafe: Any = False, **kwargs: Any) -> None: ...
         def attach_mock(self, mock: Any, attribute: Any) -> Any: ...
         def mock_add_spec(self, spec: Any, spec_set: Any = False) -> Any: ...
         return_value = ...  # type: Any
@@ -45,7 +45,7 @@ if sys.version_info >= (3, 3):
         mock_calls = ...  # type: Any
         side_effect = ...  # type: Any
         method_calls = ...  # type: Any
-        def reset_mock(self, visited: bool = None) -> None: ...
+        def reset_mock(self, visited: Optional[bool] = None) -> None: ...
         def configure_mock(self, **kwargs: Any) -> None: ...
         def __getattr__(self, name: Any) -> Any: ...
         def __dir__(self) -> Any: ...
@@ -59,11 +59,11 @@ if sys.version_info >= (3, 3):
 
     class CallableMixin(Base):
         side_effect = ...  # type: Any
-        def __init__(self, spec: Any = None, side_effect: Any = None, return_value: Any = ..., wraps: Any = None, name: Any = None, spec_set: Any = None, parent: Any = None, _spec_state: Any = None, _new_name: Any = '', _new_parent: Any = None, **kwargs: Any) -> None: ...
+        def __init__(self, spec: Optional[Any] = None, side_effect: Optional[Any] = None, return_value: Any = ..., wraps: Optional[Any] = None, name: Optional[Any] = None, spec_set: Optional[Any] = None, parent: Optional[Any] = None, _spec_state: Optional[Any] = None, _new_name: Any = '', _new_parent: Optional[Any] = None, **kwargs: Any) -> None: ...
         def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ...
 
     class Mock(CallableMixin, NonCallableMock):
-        def __init__(self) -> None: ...
+        def __init__(self, spec: Any = ..., spec_set: Any = ..., side_effect: Any = ..., return_value: Any = ..., wraps: Any = ..., name: Any = ..., **kwargs: Any) -> None: ...
 
     class _patch:
         attribute_name = ...  # type: Any
@@ -93,8 +93,8 @@ if sys.version_info >= (3, 3):
         def stop(self) -> Any: ...
 
     class _patcher:
-        def __call__(self, target: Any, new: Any = None, spec: Any = None, create: Any = False, spec_set: Any = None, autospec: Any = None, new_callable: Any = None, **kwargs: Any) -> Any: ...
-        def object(self, target: Any, attribute: str, new: Any = None, spec: Any = None, create: Any = False, spec_set: Any = None, autospec: Any = None, new_callable: Any = None, **kwargs: Any) -> _patch: ...
+        def __call__(self, target: Any, new: Optional[Any] = None, spec: Optional[Any] = None, create: Any = False, spec_set: Optional[Any] = None, autospec: Optional[Any] = None, new_callable: Optional[Any] = None, **kwargs: Any) -> Any: ...
+        def object(self, target: Any, attribute: str, new: Optional[Any] = None, spec: Optional[Any] = None, create: Any = False, spec_set: Optional[Any] = None, autospec: Optional[Any] = None, new_callable: Optional[Any] = None, **kwargs: Any) -> _patch: ...
 
     patch = ...  # type: _patcher
 
@@ -118,7 +118,7 @@ if sys.version_info >= (3, 3):
         def mock_add_spec(self, spec: Any, spec_set: Any = False) -> Any: ...
 
     class MagicMock(MagicMixin, Mock):
-        def __init__(self) -> None: ...
+        def __init__(self, spec: Any = ..., spec_set: Any = ..., side_effect: Any = ..., return_value: Any = ..., wraps: Any = ..., name: Any = ..., **kwargs: Any) -> None: ...
         def mock_add_spec(self, spec: Any, spec_set: Any = False) -> Any: ...
 
     class MagicProxy:
@@ -127,7 +127,7 @@ if sys.version_info >= (3, 3):
         def __init__(self, name: Any, parent: Any) -> None: ...
         def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
         def create_mock(self) -> Any: ...
-        def __get__(self, obj: Any, _type: Any = None) -> Any: ...
+        def __get__(self, obj: Any, _type: Optional[Any] = None) -> Any: ...
 
     class _ANY:
         def __eq__(self, other: Any) -> bool: ...
@@ -136,11 +136,11 @@ if sys.version_info >= (3, 3):
     ANY = ...  # type: Any
 
     class _Call(tuple):
-        def __new__(cls, value: Any = ..., name: Any = None, parent: Any = None, two: bool = False, from_kall: bool = True) -> Any: ...
+        def __new__(cls, value: Any = ..., name: Optional[Any] = None, parent: Optional[Any] = None, two: bool = False, from_kall: bool = True) -> Any: ...
         name = ...  # type: Any
         parent = ...  # type: Any
         from_kall = ...  # type: Any
-        def __init__(self, value: Any = ..., name: Any = None, parent: Any = None, two: bool = False, from_kall: bool = True) -> None: ...
+        def __init__(self, value: Any = ..., name: Optional[Any] = None, parent: Optional[Any] = None, two: bool = False, from_kall: bool = True) -> None: ...
         def __eq__(self, other: Any) -> bool: ...
         __ne__ = ...  # type: Any
         def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
@@ -151,7 +151,7 @@ if sys.version_info >= (3, 3):
 
     call = ...  # type: Any
 
-    def create_autospec(spec: Any, spec_set: Any = False, instance: Any = False, _parent: Any = None, _name: Any = None, **kwargs: Any) -> Any: ...
+    def create_autospec(spec: Any, spec_set: Any = False, instance: Any = False, _parent: Optional[Any] = None, _name: Optional[Any] = None, **kwargs: Any) -> Any: ...
 
     class _SpecState:
         spec = ...  # type: Any
@@ -160,9 +160,9 @@ if sys.version_info >= (3, 3):
         parent = ...  # type: Any
         instance = ...  # type: Any
         name = ...  # type: Any
-        def __init__(self, spec: Any, spec_set: Any = False, parent: Any = None, name: Any = None, ids: Any = None, instance: Any = False) -> None: ...
+        def __init__(self, spec: Any, spec_set: Any = False, parent: Optional[Any] = None, name: Optional[Any] = None, ids: Optional[Any] = None, instance: Any = False) -> None: ...
 
-    def mock_open(mock: Any = None, read_data: Any = '') -> Any: ...
+    def mock_open(mock: Optional[Any] = None, read_data: Any = '') -> Any: ...
 
     class PropertyMock(Mock):
         def __get__(self, obj: Any, obj_type: Any) -> Any: ...
diff --git a/typeshed/stdlib/3/urllib/request.pyi b/typeshed/stdlib/3/urllib/request.pyi
index dca209f..8548a88 100644
--- a/typeshed/stdlib/3/urllib/request.pyi
+++ b/typeshed/stdlib/3/urllib/request.pyi
@@ -106,14 +106,12 @@ class ProxyHandler(BaseHandler):
 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]]: ...
+    def find_user_password(self, realm: str, authuri: str) -> Tuple[Optional[str], Optional[str]]: ...
 
 class HTTPPasswordMgrWithDefaultRealm(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]]: ...
+    def find_user_password(self, realm: str, authuri: str) -> Tuple[Optional[str], Optional[str]]: ...
 
 if sys.version_info >= (3, 5):
     class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm):
diff --git a/typeshed/stdlib/3/weakref.pyi b/typeshed/stdlib/3/weakref.pyi
deleted file mode 100644
index 6c4981a..0000000
--- a/typeshed/stdlib/3/weakref.pyi
+++ /dev/null
@@ -1,120 +0,0 @@
-# Stubs for weakref
-
-# NOTE: These are incomplete!
-
-from typing import (
-    TypeVar, Generic, Any, Callable, overload, Mapping, Iterator, Dict, Tuple,
-    Iterable, Optional
-)
-
-_T = TypeVar('_T')
-_KT = TypeVar('_KT')
-_VT = TypeVar('_VT')
-
-class ReferenceType(Generic[_T]):
-    # TODO rest of members
-    def __init__(self, o: _T, callback: Callable[[ReferenceType[_T]],
-                                           Any] = ...) -> None: ...
-    def __call__(self) -> Optional[_T]: ...
-
-ref = ReferenceType
-
-# TODO callback
-def proxy(object: _T) -> _T: ...
-
-class WeakValueDictionary(Generic[_KT, _VT]):
-    # TODO tuple iterable argument?
-    @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, map: Mapping[_KT, _VT]) -> None: ...
-
-    def __len__(self) -> int: ...
-    def __getitem__(self, k: _KT) -> _VT: ...
-    def __setitem__(self, k: _KT, v: _VT) -> None: ...
-    def __delitem__(self, v: _KT) -> None: ...
-    def __contains__(self, o: object) -> bool: ...
-    def __iter__(self) -> Iterator[_KT]: ...
-    def __str__(self) -> str: ...
-
-    def clear(self) -> None: ...
-    def copy(self) -> Dict[_KT, _VT]: ...
-
-    @overload
-    def get(self, k: _KT) -> _VT: ...
-    @overload
-    def get(self, k: _KT, default: _VT) -> _VT: ...
-
-    @overload
-    def pop(self, k: _KT) -> _VT: ...
-    @overload
-    def pop(self, k: _KT, default: _VT) -> _VT: ...
-
-    def popitem(self) -> Tuple[_KT, _VT]: ...
-
-    @overload
-    def setdefault(self, k: _KT) -> _VT: ...
-    @overload
-    def setdefault(self, k: _KT, default: _VT) -> _VT: ...
-
-    @overload
-    def update(self, m: Mapping[_KT, _VT]) -> None: ...
-    @overload
-    def update(self, m: Iterable[Tuple[_KT, _VT]]) -> None: ...
-
-    # NOTE: incompatible with Mapping
-    def keys(self) -> Iterator[_KT]: ...
-    def values(self) -> Iterator[_VT]: ...
-    def items(self) -> Iterator[Tuple[_KT, _VT]]: ...
-
-    # TODO return type
-    def valuerefs(self) -> Iterable[Any]: ...
-
-
-class WeakKeyDictionary(Generic[_KT, _VT]):
-    # TODO tuple iterable argument?
-    @overload
-    def __init__(self) -> None: ...
-    @overload
-    def __init__(self, map: Mapping[_KT, _VT]) -> None: ...
-
-    def __len__(self) -> int: ...
-    def __getitem__(self, k: _KT) -> _VT: ...
-    def __setitem__(self, k: _KT, v: _VT) -> None: ...
-    def __delitem__(self, v: _KT) -> None: ...
-    def __contains__(self, o: object) -> bool: ...
-    def __iter__(self) -> Iterator[_KT]: ...
-    def __str__(self) -> str: ...
-
-    def clear(self) -> None: ...
-    def copy(self) -> Dict[_KT, _VT]: ...
-
-    @overload
-    def get(self, k: _KT) -> _VT: ...
-    @overload
-    def get(self, k: _KT, default: _VT) -> _VT: ...
-
-    @overload
-    def pop(self, k: _KT) -> _VT: ...
-    @overload
-    def pop(self, k: _KT, default: _VT) -> _VT: ...
-
-    def popitem(self) -> Tuple[_KT, _VT]: ...
-
-    @overload
-    def setdefault(self, k: _KT) -> _VT: ...
-    @overload
-    def setdefault(self, k: _KT, default: _VT) -> _VT: ...
-
-    @overload
-    def update(self, m: Mapping[_KT, _VT]) -> None: ...
-    @overload
-    def update(self, m: Iterable[Tuple[_KT, _VT]]) -> None: ...
-
-    # NOTE: incompatible with Mapping
-    def keys(self) -> Iterator[_KT]: ...
-    def values(self) -> Iterator[_VT]: ...
-    def items(self) -> Iterator[Tuple[_KT, _VT]]: ...
-
-    # TODO return type
-    def valuerefs(self) -> Iterable[Any]: ...
diff --git a/typeshed/stdlib/3/wsgiref/validate.pyi b/typeshed/stdlib/3/wsgiref/validate.pyi
index bd7fd16..c8b9b29 100644
--- a/typeshed/stdlib/3/wsgiref/validate.pyi
+++ b/typeshed/stdlib/3/wsgiref/validate.pyi
@@ -1,7 +1,3 @@
-# Stubs for wsgiref.validate (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class WSGIWarning(Warning): ...
diff --git a/typeshed/tests/mypy_selftest.py b/typeshed/tests/mypy_selftest.py
index 3dc3928..4ee98f7 100755
--- a/typeshed/tests/mypy_selftest.py
+++ b/typeshed/tests/mypy_selftest.py
@@ -11,6 +11,7 @@ import tempfile
 if __name__ == '__main__':
     with tempfile.TemporaryDirectory() as tempdir:
         dirpath = Path(tempdir)
+        subprocess.run(['python2.7', '-m', 'pip', 'install', '--user', 'typing'], check=True)
         subprocess.run(['git', 'clone', '--depth', '1', 'git://github.com/python/mypy',
                         str(dirpath / 'mypy')], check=True)
         subprocess.run([sys.executable, '-m', 'pip', 'install', '-U', '-r',
diff --git a/typeshed/tests/mypy_test.py b/typeshed/tests/mypy_test.py
index 841d067..cb4dace 100755
--- a/typeshed/tests/mypy_test.py
+++ b/typeshed/tests/mypy_test.py
@@ -24,6 +24,13 @@ parser.add_argument('-n', '--dry-run', action='store_true', help="Don't actually
 parser.add_argument('-x', '--exclude', type=str, nargs='*', help="Exclude pattern")
 parser.add_argument('-p', '--python-version', type=str, nargs='*',
                     help="These versions only (major[.minor])")
+parser.add_argument('--no-implicit-optional', action='store_true',
+                    help="Run mypy with --no-implicit-optional (causes lots of errors)")
+parser.add_argument('--warn-unused-ignores', action='store_true',
+                    help="Run mypy with --warn-unused-ignores "
+                    "(hint: only git rid of warnings that are "
+                    "unused for all platforms and Python versions)")
+
 parser.add_argument('filter', type=str, nargs='*', help="Include pattern (default all)")
 
 
@@ -124,7 +131,10 @@ def main():
             runs += 1
             flags = ['--python-version', '%d.%d' % (major, minor)]
             flags.append('--strict-optional')
-            # flags.append('--warn-unused-ignores')  # Fast parser and regular parser disagree.
+            if args.no_implicit_optional:
+                flags.append('--no-implicit-optional')
+            if args.warn_unused_ignores:
+                flags.append('--warn-unused-ignores')
             sys.argv = ['mypy'] + flags + files
             if args.verbose:
                 print("running", ' '.join(sys.argv))
diff --git a/typeshed/tests/pytype_test.py b/typeshed/tests/pytype_test.py
index e7475c0..3d6f363 100755
--- a/typeshed/tests/pytype_test.py
+++ b/typeshed/tests/pytype_test.py
@@ -70,7 +70,7 @@ def pytype_test(args):
         print("Cannot run pytd. Did you install pytype?")
         return 0, 0
 
-    wanted = re.compile(r"stdlib/(2|2\.7|2and3)/.*\.pyi$")
+    wanted = re.compile(r"stdlib/.*\.pyi$")
     skipped = re.compile("(%s)$" % "|".join(load_blacklist()))
     files = []
 
diff --git a/typeshed/third_party/2/concurrent/futures/__init__.pyi b/typeshed/third_party/2/concurrent/futures/__init__.pyi
index 49c0de6..4604830 100644
--- a/typeshed/third_party/2/concurrent/futures/__init__.pyi
+++ b/typeshed/third_party/2/concurrent/futures/__init__.pyi
@@ -1,4 +1,7 @@
+# Stubs for concurrent.futures (Python 2)
+
 from typing import TypeVar, Generic, Any, Iterable, Iterator, Callable, Optional, Set, Tuple, Union
+from types import TracebackType
 
 _T = TypeVar('_T')
 
@@ -11,26 +14,28 @@ class Future(Generic[_T]):
     def cancelled(self) -> bool: ...
     def running(self) -> bool: ...
     def done(self) -> bool: ...
-    def result(self, timeout: float = ...) -> _T: ...
-    def exception(self, timeout: float = ...) -> Any: ...
+    def result(self, timeout: Optional[float] = ...) -> _T: ...
+    def exception(self, timeout: Optional[float] = ...) -> Any: ...
+    def exception_info(self, timeout: Optional[float] = ...) -> Tuple[Any, Optional[TracebackType]]: ...
     def add_done_callback(self, fn: Callable[[Future], Any]) -> None: ...
 
     def set_running_or_notify_cancel(self) -> bool: ...
     def set_result(self, result: _T) -> None: ...
     def set_exception(self, exception: Any) -> None: ...
+    def set_exception_info(self, exception: Any, traceback: TracebackType) -> None: ...
 
 class Executor:
     def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ...
-    def map(self, func: Callable[..., _T], *iterables: Any, timeout: float = ...) -> Iterable[_T]: ...
+    def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ...) -> Iterator[_T]: ...
     def shutdown(self, wait: bool = ...) -> None: ...
     def __enter__(self) -> Executor: ...
     def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool: ...
 
 class ThreadPoolExecutor(Executor):
-    def __init__(self, max_workers: int) -> None: ...
+    def __init__(self, max_workers: Optional[int] = ...) -> None: ...
 
 class ProcessPoolExecutor(Executor):
-    def __init__(self, max_workers: Union[int, None] = ...) -> None: ...
+    def __init__(self, max_workers: Optional[int] = ...) -> None: ...
 
 def wait(fs: Iterable[Future], timeout: Optional[float] = ..., return_when: str = ...) -> Tuple[Set[Future], Set[Future]]: ...
 
@@ -38,4 +43,4 @@ FIRST_COMPLETED = ...  # type: str
 FIRST_EXCEPTION = ...  # type: str
 ALL_COMPLETED = ...  # type: str
 
-def as_completed(fs: Iterable[Future], timeout: float = ...) -> Iterator[Future]: ...
+def as_completed(fs: Iterable[Future], timeout: Optional[float] = ...) -> Iterator[Future]: ...
diff --git a/typeshed/third_party/2/croniter.pyi b/typeshed/third_party/2/croniter.pyi
index 2495495..c164213 100644
--- a/typeshed/third_party/2/croniter.pyi
+++ b/typeshed/third_party/2/croniter.pyi
@@ -1,7 +1,3 @@
-# Stubs for croniter.croniter (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class croniter:
diff --git a/typeshed/third_party/2/cryptography/hazmat/primitives/serialization.pyi b/typeshed/third_party/2/cryptography/hazmat/primitives/serialization.pyi
index 57ff681..e2c506b 100644
--- a/typeshed/third_party/2/cryptography/hazmat/primitives/serialization.pyi
+++ b/typeshed/third_party/2/cryptography/hazmat/primitives/serialization.pyi
@@ -1,7 +1,3 @@
-# Stubs for cryptography.hazmat.primitives.serialization (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from enum import Enum
 
diff --git a/typeshed/third_party/2/dateutil/parser.pyi b/typeshed/third_party/2/dateutil/parser.pyi
index d2927e8..855538b 100644
--- a/typeshed/third_party/2/dateutil/parser.pyi
+++ b/typeshed/third_party/2/dateutil/parser.pyi
@@ -27,13 +27,13 @@ class parserinfo(object):
     def validate(self, res: datetime) -> bool: ...
 
 class parser(object):
-    def __init__(self, info: parserinfo = None) -> None: ...
+    def __init__(self, info: Optional[parserinfo] = None) -> None: ...
     def parse(self, timestr: Union[str, unicode, IO[unicode]],
-              default: datetime = None,
-              ignoretz: bool = ..., tzinfos: Dict[Union[str, unicode], tzinfo] = None,
+              default: Optional[datetime] = None,
+              ignoretz: bool = ..., tzinfos: Optional[Dict[Union[str, unicode], tzinfo]] = None,
               **kwargs: Any) -> datetime: ...
 
 DEFAULTPARSER = ...  # type: parser
 def parse(timestr: Union[str, unicode, IO[unicode]],
-          parserinfo: parserinfo = None,
+          parserinfo: Optional[parserinfo] = None,
           **kwargs: Any) -> datetime: ...
diff --git a/typeshed/third_party/2/dateutil/tz/__init__.pyi b/typeshed/third_party/2/dateutil/tz/__init__.pyi
index 30a7ab3..4c8a6d2 100644
--- a/typeshed/third_party/2/dateutil/tz/__init__.pyi
+++ b/typeshed/third_party/2/dateutil/tz/__init__.pyi
@@ -1,5 +1 @@
-# Stubs for dateutil.tz (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from .tz import tzutc, tzoffset, tzlocal, tzfile, tzrange, tzstr, tzical, gettz, datetime_exists, datetime_ambiguous
diff --git a/typeshed/third_party/2/dateutil/tz/_common.pyi b/typeshed/third_party/2/dateutil/tz/_common.pyi
index e0856d2..8a684e3 100644
--- a/typeshed/third_party/2/dateutil/tz/_common.pyi
+++ b/typeshed/third_party/2/dateutil/tz/_common.pyi
@@ -1,7 +1,3 @@
-# Stubs for dateutil.tz._common (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from datetime import datetime, tzinfo, timedelta
 
diff --git a/typeshed/third_party/2/dateutil/tz/tz.pyi b/typeshed/third_party/2/dateutil/tz/tz.pyi
index 5027e62..5fcd6d8 100644
--- a/typeshed/third_party/2/dateutil/tz/tz.pyi
+++ b/typeshed/third_party/2/dateutil/tz/tz.pyi
@@ -1,7 +1,3 @@
-# Stubs for dateutil.tz.tz (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, IO, List, Optional, Tuple, Union
 import datetime
 from ._common import tzname_in_python2 as tzname_in_python2, _tzinfo as _tzinfo
diff --git a/typeshed/third_party/2/enum.pyi b/typeshed/third_party/2/enum.pyi
index 4032e81..ae8a91c 100644
--- a/typeshed/third_party/2/enum.pyi
+++ b/typeshed/third_party/2/enum.pyi
@@ -1,7 +1,11 @@
-from typing import List, Any, TypeVar
+from typing import List, Any, TypeVar, Type, Iterable, Iterator
 
-class Enum:
-    def __new__(cls, value: Any) -> None: ...
+_T = TypeVar('_T', bound=Enum)
+class EnumMeta(type, Iterable[Enum]):
+    def __iter__(self: Type[_T]) -> Iterator[_T]: ...  # type: ignore
+
+class Enum(metaclass=EnumMeta):
+    def __new__(cls: Type[_T], value: Any) -> _T: ...
     def __repr__(self) -> str: ...
     def __str__(self) -> str: ...
     def __dir__(self) -> List[str]: ...
@@ -14,6 +18,4 @@ class Enum:
 
 class IntEnum(int, Enum): ...
 
-_T = TypeVar('_T')
-
 def unique(enumeration: _T) -> _T: ...
diff --git a/typeshed/third_party/2/fb303/FacebookService.pyi b/typeshed/third_party/2/fb303/FacebookService.pyi
index 09c6ef1..c863f28 100644
--- a/typeshed/third_party/2/fb303/FacebookService.pyi
+++ b/typeshed/third_party/2/fb303/FacebookService.pyi
@@ -1,7 +1,3 @@
-# Stubs for fb303.FacebookService (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from thrift.Thrift import TProcessor
 
diff --git a/typeshed/third_party/2/google/protobuf/descriptor.pyi b/typeshed/third_party/2/google/protobuf/descriptor.pyi
index 1d26f98..a11c968 100644
--- a/typeshed/third_party/2/google/protobuf/descriptor.pyi
+++ b/typeshed/third_party/2/google/protobuf/descriptor.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.descriptor (Python 2.7)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 from .message import Message
diff --git a/typeshed/third_party/2/google/protobuf/descriptor_pool.pyi b/typeshed/third_party/2/google/protobuf/descriptor_pool.pyi
index f22ea57..f1ade52 100644
--- a/typeshed/third_party/2/google/protobuf/descriptor_pool.pyi
+++ b/typeshed/third_party/2/google/protobuf/descriptor_pool.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.descriptor_pool (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class DescriptorPool:
diff --git a/typeshed/third_party/2/google/protobuf/internal/decoder.pyi b/typeshed/third_party/2/google/protobuf/internal/decoder.pyi
index e7737ee..24918b2 100644
--- a/typeshed/third_party/2/google/protobuf/internal/decoder.pyi
+++ b/typeshed/third_party/2/google/protobuf/internal/decoder.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.internal.decoder (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def ReadTag(buffer, pos): ...
diff --git a/typeshed/third_party/2/google/protobuf/internal/encoder.pyi b/typeshed/third_party/2/google/protobuf/internal/encoder.pyi
index c3ab6ff..a29caf4 100644
--- a/typeshed/third_party/2/google/protobuf/internal/encoder.pyi
+++ b/typeshed/third_party/2/google/protobuf/internal/encoder.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.internal.encoder (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 Int32Sizer = ...  # type: Any
diff --git a/typeshed/third_party/2/google/protobuf/internal/wire_format.pyi b/typeshed/third_party/2/google/protobuf/internal/wire_format.pyi
index 19b7c3f..0025a2c 100644
--- a/typeshed/third_party/2/google/protobuf/internal/wire_format.pyi
+++ b/typeshed/third_party/2/google/protobuf/internal/wire_format.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.internal.wire_format (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 TAG_TYPE_BITS = ...  # type: Any
diff --git a/typeshed/third_party/2/google/protobuf/message.pyi b/typeshed/third_party/2/google/protobuf/message.pyi
index 09c7716..b13821f 100644
--- a/typeshed/third_party/2/google/protobuf/message.pyi
+++ b/typeshed/third_party/2/google/protobuf/message.pyi
@@ -1,8 +1,4 @@
-# Stubs for google.protobuf.message (Python 2.7)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any, Sequence, Optional, Tuple
+from typing import Any, Sequence, Optional, Text, Tuple
 
 from .descriptor import FieldDescriptor
 
@@ -25,8 +21,8 @@ class Message:
     def SerializeToString(self) -> str: ...
     def SerializePartialToString(self) -> str: ...
     def ListFields(self) -> Sequence[Tuple[FieldDescriptor, Any]]: ...
-    def HasField(self, field_name: str) -> bool: ...
-    def ClearField(self, field_name: str) -> None: ...
+    def HasField(self, field_name: Text) -> bool: ...
+    def ClearField(self, field_name: Text) -> None: ...
     def WhichOneof(self, oneof_group) -> Optional[str]: ...
     def HasExtension(self, extension_handle): ...
     def ClearExtension(self, extension_handle): ...
diff --git a/typeshed/third_party/2/google/protobuf/message_factory.pyi b/typeshed/third_party/2/google/protobuf/message_factory.pyi
index a76333d..24758ff 100644
--- a/typeshed/third_party/2/google/protobuf/message_factory.pyi
+++ b/typeshed/third_party/2/google/protobuf/message_factory.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.message_factory (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Dict, Iterable, Optional, Type
 
 from .message import Message
@@ -10,7 +6,7 @@ from .descriptor_pool import DescriptorPool
 
 class MessageFactory:
     pool = ...  # type: Any
-    def __init__(self, pool: DescriptorPool=None) -> None: ...
+    def __init__(self, pool: Optional[DescriptorPool] = None) -> None: ...
     def GetPrototype(self, descriptor: Descriptor) -> Type[Message]: ...
     def GetMessages(self, files: Iterable[str]) -> Dict[str, Type[Message]]: ...
 
diff --git a/typeshed/third_party/2/google/protobuf/reflection.pyi b/typeshed/third_party/2/google/protobuf/reflection.pyi
index 3d3e76b..d32a93d 100644
--- a/typeshed/third_party/2/google/protobuf/reflection.pyi
+++ b/typeshed/third_party/2/google/protobuf/reflection.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.reflection (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 class GeneratedProtocolMessageType(type):
     def __new__(cls, name, bases, dictionary): ...
     def __init__(cls, name, bases, dictionary) -> None: ...
diff --git a/typeshed/third_party/2/google/protobuf/symbol_database.pyi b/typeshed/third_party/2/google/protobuf/symbol_database.pyi
index e29070c..df8300f 100644
--- a/typeshed/third_party/2/google/protobuf/symbol_database.pyi
+++ b/typeshed/third_party/2/google/protobuf/symbol_database.pyi
@@ -1,7 +1,3 @@
-# Stubs for google.protobuf.symbol_database
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Dict, Iterable, Type
 
 from .descriptor import EnumDescriptor, FileDescriptor
diff --git a/typeshed/third_party/2/itsdangerous.pyi b/typeshed/third_party/2/itsdangerous.pyi
index 0efb3d6..075a2e4 100644
--- a/typeshed/third_party/2/itsdangerous.pyi
+++ b/typeshed/third_party/2/itsdangerous.pyi
@@ -1,7 +1,3 @@
-# Stubs for itsdangerous (Python 2.7)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from datetime import datetime
 from itertools import izip
 from typing import Any, Callable, IO, MutableMapping, Optional, Text, Tuple, Union
diff --git a/typeshed/third_party/2/kazoo/__init__.pyi b/typeshed/third_party/2/kazoo/__init__.pyi
index 1aae9a5..e69de29 100644
--- a/typeshed/third_party/2/kazoo/__init__.pyi
+++ b/typeshed/third_party/2/kazoo/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for kazoo (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/2/kazoo/client.pyi b/typeshed/third_party/2/kazoo/client.pyi
index 8db0eda..3fd79a3 100644
--- a/typeshed/third_party/2/kazoo/client.pyi
+++ b/typeshed/third_party/2/kazoo/client.pyi
@@ -1,7 +1,3 @@
-# Stubs for kazoo.client (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 string_types = ...  # type: Any
diff --git a/typeshed/third_party/2/kazoo/exceptions.pyi b/typeshed/third_party/2/kazoo/exceptions.pyi
index ed632ba..dcec322 100644
--- a/typeshed/third_party/2/kazoo/exceptions.pyi
+++ b/typeshed/third_party/2/kazoo/exceptions.pyi
@@ -1,7 +1,3 @@
-# Stubs for kazoo.exceptions (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class KazooException(Exception): ...
diff --git a/typeshed/third_party/2/kazoo/recipe/__init__.pyi b/typeshed/third_party/2/kazoo/recipe/__init__.pyi
index 44bc4cb..e69de29 100644
--- a/typeshed/third_party/2/kazoo/recipe/__init__.pyi
+++ b/typeshed/third_party/2/kazoo/recipe/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for kazoo.recipe (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/2/kazoo/recipe/watchers.pyi b/typeshed/third_party/2/kazoo/recipe/watchers.pyi
index f942163..545f501 100644
--- a/typeshed/third_party/2/kazoo/recipe/watchers.pyi
+++ b/typeshed/third_party/2/kazoo/recipe/watchers.pyi
@@ -1,7 +1,3 @@
-# Stubs for kazoo.recipe.watchers (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 log = ...  # type: Any
diff --git a/typeshed/third_party/2/pymssql.pyi b/typeshed/third_party/2/pymssql.pyi
index 3f75b31..a35b050 100644
--- a/typeshed/third_party/2/pymssql.pyi
+++ b/typeshed/third_party/2/pymssql.pyi
@@ -26,7 +26,7 @@ class Cursor(object):
     def executemany(self, stmt: str,
                     params: Optional[Sequence[Tuple[Scalar, ...]]]) -> None: ...
     def fetchall(self) -> List[Result]: ...
-    def fetchmany(self, size: Optional[Union[int, None]]) -> List[Result]: ...
+    def fetchmany(self, size: Optional[int]) -> List[Result]: ...
     def fetchone(self) -> Result: ...
 
 def connect(server: Optional[str],
diff --git a/typeshed/third_party/2/redis/__init__.pyi b/typeshed/third_party/2/redis/__init__.pyi
index 53ec818..333de49 100644
--- a/typeshed/third_party/2/redis/__init__.pyi
+++ b/typeshed/third_party/2/redis/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for redis (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from . import client
 from . import connection
 from . import utils
diff --git a/typeshed/third_party/2/redis/client.pyi b/typeshed/third_party/2/redis/client.pyi
index 43693ec..99f2adf 100644
--- a/typeshed/third_party/2/redis/client.pyi
+++ b/typeshed/third_party/2/redis/client.pyi
@@ -1,7 +1,3 @@
-# Stubs for redis.client (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 SYM_EMPTY = ...  # type: Any
diff --git a/typeshed/third_party/2/redis/connection.pyi b/typeshed/third_party/2/redis/connection.pyi
index 214cd8d..9756477 100644
--- a/typeshed/third_party/2/redis/connection.pyi
+++ b/typeshed/third_party/2/redis/connection.pyi
@@ -1,7 +1,3 @@
-# Stubs for redis.connection (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 ssl_available = ...  # type: Any
diff --git a/typeshed/third_party/2/redis/exceptions.pyi b/typeshed/third_party/2/redis/exceptions.pyi
index 97a11f5..e0cd08a 100644
--- a/typeshed/third_party/2/redis/exceptions.pyi
+++ b/typeshed/third_party/2/redis/exceptions.pyi
@@ -1,7 +1,3 @@
-# Stubs for redis.exceptions (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 class RedisError(Exception): ...
 
 def __unicode__(self): ...
diff --git a/typeshed/third_party/2/redis/utils.pyi b/typeshed/third_party/2/redis/utils.pyi
index fe1388c..5e32010 100644
--- a/typeshed/third_party/2/redis/utils.pyi
+++ b/typeshed/third_party/2/redis/utils.pyi
@@ -1,7 +1,3 @@
-# Stubs for redis.utils (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 HIREDIS_AVAILABLE = ...  # type: Any
diff --git a/typeshed/third_party/2/routes/__init__.pyi b/typeshed/third_party/2/routes/__init__.pyi
index 5d7864d..8a1261f 100644
--- a/typeshed/third_party/2/routes/__init__.pyi
+++ b/typeshed/third_party/2/routes/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for routes (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from . import mapper
 from . import util
 
diff --git a/typeshed/third_party/2/routes/mapper.pyi b/typeshed/third_party/2/routes/mapper.pyi
index 573a2ef..074c4ff 100644
--- a/typeshed/third_party/2/routes/mapper.pyi
+++ b/typeshed/third_party/2/routes/mapper.pyi
@@ -1,7 +1,3 @@
-# Stubs for routes.mapper (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 COLLECTION_ACTIONS = ...  # type: Any
diff --git a/typeshed/third_party/2/routes/util.pyi b/typeshed/third_party/2/routes/util.pyi
index e5210e3..aeb97f3 100644
--- a/typeshed/third_party/2/routes/util.pyi
+++ b/typeshed/third_party/2/routes/util.pyi
@@ -1,7 +1,3 @@
-# Stubs for routes.util (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class RoutesException(Exception): ...
diff --git a/typeshed/third_party/2/scribe/scribe.pyi b/typeshed/third_party/2/scribe/scribe.pyi
index ec2a71f..4d9a286 100644
--- a/typeshed/third_party/2/scribe/scribe.pyi
+++ b/typeshed/third_party/2/scribe/scribe.pyi
@@ -1,7 +1,3 @@
-# Stubs for scribe.scribe (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 import fb303.FacebookService
diff --git a/typeshed/third_party/2/scribe/ttypes.pyi b/typeshed/third_party/2/scribe/ttypes.pyi
index 32f01bd..69ec920 100644
--- a/typeshed/third_party/2/scribe/ttypes.pyi
+++ b/typeshed/third_party/2/scribe/ttypes.pyi
@@ -1,7 +1,3 @@
-# Stubs for scribe.ttypes (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 fastbinary = ...  # type: Any
diff --git a/typeshed/third_party/2/selenium/webdriver/remote/webdriver.pyi b/typeshed/third_party/2/selenium/webdriver/remote/webdriver.pyi
index 9e0f24c..c8e565c 100644
--- a/typeshed/third_party/2/selenium/webdriver/remote/webdriver.pyi
+++ b/typeshed/third_party/2/selenium/webdriver/remote/webdriver.pyi
@@ -1,7 +1,3 @@
-# Stubs for selenium.webdriver.remote.webdriver (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Dict, List, Optional
 from .mobile import Mobile as Mobile
 from selenium.webdriver.remote.webelement import WebElement
diff --git a/typeshed/third_party/2/selenium/webdriver/remote/webelement.pyi b/typeshed/third_party/2/selenium/webdriver/remote/webelement.pyi
index 0577036..fd94c56 100644
--- a/typeshed/third_party/2/selenium/webdriver/remote/webelement.pyi
+++ b/typeshed/third_party/2/selenium/webdriver/remote/webelement.pyi
@@ -1,7 +1,3 @@
-# Stubs for selenium.webdriver.remote.webelement (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from selenium.webdriver.remote.webdriver import WebDriver
 from typing import Any, Optional, Dict, List
 
diff --git a/typeshed/third_party/2/thrift/Thrift.pyi b/typeshed/third_party/2/thrift/Thrift.pyi
index 4397fb6..7d5a28f 100644
--- a/typeshed/third_party/2/thrift/Thrift.pyi
+++ b/typeshed/third_party/2/thrift/Thrift.pyi
@@ -1,7 +1,3 @@
-# Stubs for thrift.Thrift (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class TType:
diff --git a/typeshed/third_party/2/thrift/protocol/TBinaryProtocol.pyi b/typeshed/third_party/2/thrift/protocol/TBinaryProtocol.pyi
index a1e5e71..21a729d 100644
--- a/typeshed/third_party/2/thrift/protocol/TBinaryProtocol.pyi
+++ b/typeshed/third_party/2/thrift/protocol/TBinaryProtocol.pyi
@@ -1,7 +1,3 @@
-# Stubs for thrift.protocol.TBinaryProtocol (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 from .TProtocol import TProtocolBase
diff --git a/typeshed/third_party/2/thrift/protocol/TProtocol.pyi b/typeshed/third_party/2/thrift/protocol/TProtocol.pyi
index e59765a..cf5d356 100644
--- a/typeshed/third_party/2/thrift/protocol/TProtocol.pyi
+++ b/typeshed/third_party/2/thrift/protocol/TProtocol.pyi
@@ -1,7 +1,3 @@
-# Stubs for thrift.protocol.TProtocol (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 from thrift.Thrift import TException
diff --git a/typeshed/third_party/2/thrift/protocol/__init__.pyi b/typeshed/third_party/2/thrift/protocol/__init__.pyi
index f98118b..4a5b650 100644
--- a/typeshed/third_party/2/thrift/protocol/__init__.pyi
+++ b/typeshed/third_party/2/thrift/protocol/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for thrift.protocol (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   TBase
 #   TBinaryProtocol
diff --git a/typeshed/third_party/2/thrift/transport/TSocket.pyi b/typeshed/third_party/2/thrift/transport/TSocket.pyi
index 6148117..9e0fef4 100644
--- a/typeshed/third_party/2/thrift/transport/TSocket.pyi
+++ b/typeshed/third_party/2/thrift/transport/TSocket.pyi
@@ -1,7 +1,3 @@
-# Stubs for thrift.transport.TSocket (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 from .TTransport import TTransportBase, TServerTransportBase
diff --git a/typeshed/third_party/2/thrift/transport/TTransport.pyi b/typeshed/third_party/2/thrift/transport/TTransport.pyi
index d46cca0..18d2eab 100644
--- a/typeshed/third_party/2/thrift/transport/TTransport.pyi
+++ b/typeshed/third_party/2/thrift/transport/TTransport.pyi
@@ -1,7 +1,3 @@
-# Stubs for thrift.transport.TTransport (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from thrift.Thrift import TException
 
diff --git a/typeshed/third_party/2/thrift/transport/__init__.pyi b/typeshed/third_party/2/thrift/transport/__init__.pyi
index ce02c61..fd3f5f5 100644
--- a/typeshed/third_party/2/thrift/transport/__init__.pyi
+++ b/typeshed/third_party/2/thrift/transport/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for thrift.transport (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   THttpClient
 #   TSocket
diff --git a/typeshed/third_party/2/tornado/concurrent.pyi b/typeshed/third_party/2/tornado/concurrent.pyi
index 46f39a3..82c29da 100644
--- a/typeshed/third_party/2/tornado/concurrent.pyi
+++ b/typeshed/third_party/2/tornado/concurrent.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.concurrent (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 futures = ...  # type: Any
diff --git a/typeshed/third_party/2/tornado/gen.pyi b/typeshed/third_party/2/tornado/gen.pyi
index fbde2da..4ec96b5 100644
--- a/typeshed/third_party/2/tornado/gen.pyi
+++ b/typeshed/third_party/2/tornado/gen.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.gen (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from collections import namedtuple
 
diff --git a/typeshed/third_party/2/tornado/httpclient.pyi b/typeshed/third_party/2/tornado/httpclient.pyi
index fa41d16..d3c7127 100644
--- a/typeshed/third_party/2/tornado/httpclient.pyi
+++ b/typeshed/third_party/2/tornado/httpclient.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.httpclient (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from tornado.util import Configurable
 
diff --git a/typeshed/third_party/2/tornado/httpserver.pyi b/typeshed/third_party/2/tornado/httpserver.pyi
index f4b2aa9..3738c85 100644
--- a/typeshed/third_party/2/tornado/httpserver.pyi
+++ b/typeshed/third_party/2/tornado/httpserver.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.httpserver (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from tornado import httputil
 from tornado.tcpserver import TCPServer
diff --git a/typeshed/third_party/2/tornado/httputil.pyi b/typeshed/third_party/2/tornado/httputil.pyi
index f8fefb5..bdcbfa5 100644
--- a/typeshed/third_party/2/tornado/httputil.pyi
+++ b/typeshed/third_party/2/tornado/httputil.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.httputil (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from tornado.util import ObjectDict
 from collections import namedtuple
diff --git a/typeshed/third_party/2/tornado/ioloop.pyi b/typeshed/third_party/2/tornado/ioloop.pyi
index 38624c5..e4f97e7 100644
--- a/typeshed/third_party/2/tornado/ioloop.pyi
+++ b/typeshed/third_party/2/tornado/ioloop.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.ioloop (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from tornado.util import Configurable
 
diff --git a/typeshed/third_party/2/tornado/locks.pyi b/typeshed/third_party/2/tornado/locks.pyi
index ea61761..eaeba24 100644
--- a/typeshed/third_party/2/tornado/locks.pyi
+++ b/typeshed/third_party/2/tornado/locks.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.locks (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class _TimeoutGarbageCollector:
diff --git a/typeshed/third_party/2/tornado/netutil.pyi b/typeshed/third_party/2/tornado/netutil.pyi
index bfbc6b1..b12154b 100644
--- a/typeshed/third_party/2/tornado/netutil.pyi
+++ b/typeshed/third_party/2/tornado/netutil.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.netutil (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from tornado.util import Configurable
 
diff --git a/typeshed/third_party/2/tornado/tcpserver.pyi b/typeshed/third_party/2/tornado/tcpserver.pyi
index 9fa7a09..489e4d4 100644
--- a/typeshed/third_party/2/tornado/tcpserver.pyi
+++ b/typeshed/third_party/2/tornado/tcpserver.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.tcpserver (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 ssl = ...  # type: Any
diff --git a/typeshed/third_party/2/tornado/testing.pyi b/typeshed/third_party/2/tornado/testing.pyi
index c6fde57..5b8c662 100644
--- a/typeshed/third_party/2/tornado/testing.pyi
+++ b/typeshed/third_party/2/tornado/testing.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.testing (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import unittest
 import logging
diff --git a/typeshed/third_party/2/tornado/util.pyi b/typeshed/third_party/2/tornado/util.pyi
index 3b07131..cf535c4 100644
--- a/typeshed/third_party/2/tornado/util.pyi
+++ b/typeshed/third_party/2/tornado/util.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.util (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 xrange = ...  # type: Any
diff --git a/typeshed/third_party/2/tornado/web.pyi b/typeshed/third_party/2/tornado/web.pyi
index ca0c7c0..69e5a37 100644
--- a/typeshed/third_party/2/tornado/web.pyi
+++ b/typeshed/third_party/2/tornado/web.pyi
@@ -1,7 +1,3 @@
-# Stubs for tornado.web (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from tornado import httputil
 
diff --git a/typeshed/third_party/2/werkzeug/__init__.pyi b/typeshed/third_party/2/werkzeug/__init__.pyi
index 5bb4845..c375f41 100644
--- a/typeshed/third_party/2/werkzeug/__init__.pyi
+++ b/typeshed/third_party/2/werkzeug/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from types import ModuleType
 
 from typing import Any
diff --git a/typeshed/third_party/2/werkzeug/_compat.pyi b/typeshed/third_party/2/werkzeug/_compat.pyi
index 801bdda..5779bc8 100644
--- a/typeshed/third_party/2/werkzeug/_compat.pyi
+++ b/typeshed/third_party/2/werkzeug/_compat.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug._compat (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import StringIO as BytesIO
 
diff --git a/typeshed/third_party/2/werkzeug/_internal.pyi b/typeshed/third_party/2/werkzeug/_internal.pyi
index 1a1bbd5..6fddbdd 100644
--- a/typeshed/third_party/2/werkzeug/_internal.pyi
+++ b/typeshed/third_party/2/werkzeug/_internal.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug._internal (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class _Missing:
diff --git a/typeshed/third_party/2/werkzeug/_reloader.pyi b/typeshed/third_party/2/werkzeug/_reloader.pyi
index 9bfea1f..55a560d 100644
--- a/typeshed/third_party/2/werkzeug/_reloader.pyi
+++ b/typeshed/third_party/2/werkzeug/_reloader.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug._reloader (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class ReloaderLoop:
diff --git a/typeshed/third_party/2/werkzeug/contrib/__init__.pyi b/typeshed/third_party/2/werkzeug/contrib/__init__.pyi
index 4b77b01..e69de29 100644
--- a/typeshed/third_party/2/werkzeug/contrib/__init__.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for werkzeug.contrib (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/2/werkzeug/contrib/atom.pyi b/typeshed/third_party/2/werkzeug/contrib/atom.pyi
index 98f994d..1e27873 100644
--- a/typeshed/third_party/2/werkzeug/contrib/atom.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/atom.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.atom (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 XHTML_NAMESPACE = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/contrib/cache.pyi b/typeshed/third_party/2/werkzeug/contrib/cache.pyi
index 1c9fcbe..23e7899 100644
--- a/typeshed/third_party/2/werkzeug/contrib/cache.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/cache.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.cache (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class BaseCache:
diff --git a/typeshed/third_party/2/werkzeug/contrib/fixers.pyi b/typeshed/third_party/2/werkzeug/contrib/fixers.pyi
index 147456e..a45c661 100644
--- a/typeshed/third_party/2/werkzeug/contrib/fixers.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/fixers.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.fixers (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class CGIRootFix:
diff --git a/typeshed/third_party/2/werkzeug/contrib/iterio.pyi b/typeshed/third_party/2/werkzeug/contrib/iterio.pyi
index fd2c2a2..33da956 100644
--- a/typeshed/third_party/2/werkzeug/contrib/iterio.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/iterio.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.iterio (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 greenlet = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/contrib/jsrouting.pyi b/typeshed/third_party/2/werkzeug/contrib/jsrouting.pyi
index 6fdd615..a9cc8c2 100644
--- a/typeshed/third_party/2/werkzeug/contrib/jsrouting.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/jsrouting.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.jsrouting (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def dumps(*args): ...
diff --git a/typeshed/third_party/2/werkzeug/contrib/limiter.pyi b/typeshed/third_party/2/werkzeug/contrib/limiter.pyi
index d51038e..52501c6 100644
--- a/typeshed/third_party/2/werkzeug/contrib/limiter.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/limiter.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.limiter (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class StreamLimitMiddleware:
diff --git a/typeshed/third_party/2/werkzeug/contrib/lint.pyi b/typeshed/third_party/2/werkzeug/contrib/lint.pyi
index a0c2295..f89c120 100644
--- a/typeshed/third_party/2/werkzeug/contrib/lint.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/lint.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.lint (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class WSGIWarning(Warning): ...
diff --git a/typeshed/third_party/2/werkzeug/contrib/profiler.pyi b/typeshed/third_party/2/werkzeug/contrib/profiler.pyi
index b41c1c8..db1eacb 100644
--- a/typeshed/third_party/2/werkzeug/contrib/profiler.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/profiler.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.profiler (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 available = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/contrib/securecookie.pyi b/typeshed/third_party/2/werkzeug/contrib/securecookie.pyi
index c262bed..219356f 100644
--- a/typeshed/third_party/2/werkzeug/contrib/securecookie.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/securecookie.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.securecookie (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from hmac import new as hmac
 from hashlib import sha1 as _default_hash
diff --git a/typeshed/third_party/2/werkzeug/contrib/sessions.pyi b/typeshed/third_party/2/werkzeug/contrib/sessions.pyi
index 5b84ede..aa3f8fc 100644
--- a/typeshed/third_party/2/werkzeug/contrib/sessions.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/sessions.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.sessions (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.datastructures import CallbackDict
 
diff --git a/typeshed/third_party/2/werkzeug/contrib/testtools.pyi b/typeshed/third_party/2/werkzeug/contrib/testtools.pyi
index c304f39..860ebb7 100644
--- a/typeshed/third_party/2/werkzeug/contrib/testtools.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/testtools.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.testtools (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.wrappers import Response
 
diff --git a/typeshed/third_party/2/werkzeug/contrib/wrappers.pyi b/typeshed/third_party/2/werkzeug/contrib/wrappers.pyi
index b538462..4ebc7e8 100644
--- a/typeshed/third_party/2/werkzeug/contrib/wrappers.pyi
+++ b/typeshed/third_party/2/werkzeug/contrib/wrappers.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.wrappers (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def is_known_charset(charset): ...
diff --git a/typeshed/third_party/2/werkzeug/datastructures.pyi b/typeshed/third_party/2/werkzeug/datastructures.pyi
index cbbddf9..72e7899 100644
--- a/typeshed/third_party/2/werkzeug/datastructures.pyi
+++ b/typeshed/third_party/2/werkzeug/datastructures.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.datastructures (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from collections import Container, Iterable, Mapping, MutableSet
 
diff --git a/typeshed/third_party/2/werkzeug/debug/__init__.pyi b/typeshed/third_party/2/werkzeug/debug/__init__.pyi
index abe6495..a806edd 100644
--- a/typeshed/third_party/2/werkzeug/debug/__init__.pyi
+++ b/typeshed/third_party/2/werkzeug/debug/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.wrappers import BaseRequest as Request, BaseResponse as Response
 
diff --git a/typeshed/third_party/2/werkzeug/debug/console.pyi b/typeshed/third_party/2/werkzeug/debug/console.pyi
index ddc1a33..5046a51 100644
--- a/typeshed/third_party/2/werkzeug/debug/console.pyi
+++ b/typeshed/third_party/2/werkzeug/debug/console.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug.console (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import code
 
diff --git a/typeshed/third_party/2/werkzeug/debug/repr.pyi b/typeshed/third_party/2/werkzeug/debug/repr.pyi
index 6889a27..fe3faef 100644
--- a/typeshed/third_party/2/werkzeug/debug/repr.pyi
+++ b/typeshed/third_party/2/werkzeug/debug/repr.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug.repr (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 deque = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/debug/tbtools.pyi b/typeshed/third_party/2/werkzeug/debug/tbtools.pyi
index 1279409..7c0cd58 100644
--- a/typeshed/third_party/2/werkzeug/debug/tbtools.pyi
+++ b/typeshed/third_party/2/werkzeug/debug/tbtools.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug.tbtools (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 UTF8_COOKIE = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/exceptions.pyi b/typeshed/third_party/2/werkzeug/exceptions.pyi
index d520518..f7017e5 100644
--- a/typeshed/third_party/2/werkzeug/exceptions.pyi
+++ b/typeshed/third_party/2/werkzeug/exceptions.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.exceptions (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class HTTPException(Exception):
diff --git a/typeshed/third_party/2/werkzeug/filesystem.pyi b/typeshed/third_party/2/werkzeug/filesystem.pyi
index 9f1b0bb..80913ca 100644
--- a/typeshed/third_party/2/werkzeug/filesystem.pyi
+++ b/typeshed/third_party/2/werkzeug/filesystem.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.filesystem (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 has_likely_buggy_unicode_filesystem = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/formparser.pyi b/typeshed/third_party/2/werkzeug/formparser.pyi
index 4b61d27..842c405 100644
--- a/typeshed/third_party/2/werkzeug/formparser.pyi
+++ b/typeshed/third_party/2/werkzeug/formparser.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.formparser (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def default_stream_factory(total_content_length, filename, content_type, content_length=None): ...
diff --git a/typeshed/third_party/2/werkzeug/http.pyi b/typeshed/third_party/2/werkzeug/http.pyi
index 1c6e3e8..8d6c15f 100644
--- a/typeshed/third_party/2/werkzeug/http.pyi
+++ b/typeshed/third_party/2/werkzeug/http.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.http (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from urllib2 import parse_http_list as _parse_list_header
 
diff --git a/typeshed/third_party/2/werkzeug/local.pyi b/typeshed/third_party/2/werkzeug/local.pyi
index 8b32367..f1d167a 100644
--- a/typeshed/third_party/2/werkzeug/local.pyi
+++ b/typeshed/third_party/2/werkzeug/local.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.local (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def release_local(local): ...
diff --git a/typeshed/third_party/2/werkzeug/posixemulation.pyi b/typeshed/third_party/2/werkzeug/posixemulation.pyi
index 5234999..b490ab4 100644
--- a/typeshed/third_party/2/werkzeug/posixemulation.pyi
+++ b/typeshed/third_party/2/werkzeug/posixemulation.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.posixemulation (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from ._compat import to_unicode as to_unicode
 from .filesystem import get_filesystem_encoding as get_filesystem_encoding
diff --git a/typeshed/third_party/2/werkzeug/routing.pyi b/typeshed/third_party/2/werkzeug/routing.pyi
index ab94060..22f493e 100644
--- a/typeshed/third_party/2/werkzeug/routing.pyi
+++ b/typeshed/third_party/2/werkzeug/routing.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.routing (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.exceptions import HTTPException
 
diff --git a/typeshed/third_party/2/werkzeug/script.pyi b/typeshed/third_party/2/werkzeug/script.pyi
index e84180e..758378d 100644
--- a/typeshed/third_party/2/werkzeug/script.pyi
+++ b/typeshed/third_party/2/werkzeug/script.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.script (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 argument_types = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/security.pyi b/typeshed/third_party/2/werkzeug/security.pyi
index c3752c1..dde9fe1 100644
--- a/typeshed/third_party/2/werkzeug/security.pyi
+++ b/typeshed/third_party/2/werkzeug/security.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.security (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 SALT_CHARS = ...  # type: Any
diff --git a/typeshed/third_party/2/werkzeug/serving.pyi b/typeshed/third_party/2/werkzeug/serving.pyi
index 752e3e7..81b288b 100644
--- a/typeshed/third_party/2/werkzeug/serving.pyi
+++ b/typeshed/third_party/2/werkzeug/serving.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.serving (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from ._compat import PY2 as PY2
 from SocketServer import ThreadingMixIn, ForkingMixIn
diff --git a/typeshed/third_party/2/werkzeug/test.pyi b/typeshed/third_party/2/werkzeug/test.pyi
index 89315ca..fd692f1 100644
--- a/typeshed/third_party/2/werkzeug/test.pyi
+++ b/typeshed/third_party/2/werkzeug/test.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.test (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from urllib2 import Request as U2Request
 from cookielib import CookieJar
diff --git a/typeshed/third_party/2/werkzeug/testapp.pyi b/typeshed/third_party/2/werkzeug/testapp.pyi
index 3a85843..4e17633 100644
--- a/typeshed/third_party/2/werkzeug/testapp.pyi
+++ b/typeshed/third_party/2/werkzeug/testapp.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.testapp (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.wrappers import BaseRequest as Request, BaseResponse as Response
 
diff --git a/typeshed/third_party/2/werkzeug/urls.pyi b/typeshed/third_party/2/werkzeug/urls.pyi
index 5f55e12..0c3cefa 100644
--- a/typeshed/third_party/2/werkzeug/urls.pyi
+++ b/typeshed/third_party/2/werkzeug/urls.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.urls (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from collections import namedtuple
 from typing import Any
 
diff --git a/typeshed/third_party/2/werkzeug/useragents.pyi b/typeshed/third_party/2/werkzeug/useragents.pyi
index 96b262a..2ca2705 100644
--- a/typeshed/third_party/2/werkzeug/useragents.pyi
+++ b/typeshed/third_party/2/werkzeug/useragents.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.useragents (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class UserAgentParser:
diff --git a/typeshed/third_party/2/werkzeug/utils.pyi b/typeshed/third_party/2/werkzeug/utils.pyi
index ff7fd39..8e2e6b9 100644
--- a/typeshed/third_party/2/werkzeug/utils.pyi
+++ b/typeshed/third_party/2/werkzeug/utils.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.utils (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug._internal import _DictAccessorProperty
 
diff --git a/typeshed/third_party/2/werkzeug/wrappers.pyi b/typeshed/third_party/2/werkzeug/wrappers.pyi
index 982650c..1fb5668 100644
--- a/typeshed/third_party/2/werkzeug/wrappers.pyi
+++ b/typeshed/third_party/2/werkzeug/wrappers.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.wrappers (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import (
     Any, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union,
 )
@@ -80,7 +76,15 @@ class BaseResponse:
     status = ...  # type: str
     direct_passthrough = ...  # type: bool
     response = ...  # type: Iterable[str]
-    def __init__(self, response: Union[Iterable[str], str]=None, status=Union[basestring, int], headers: Union[Headers, Mapping[basestring, basestring], Sequence[Tuple[basestring, basestring]]]=None, mimetype: basestring=None, content_type: basestring=None, direct_passthrough: bool=False) -> None: ...
+    def __init__(self,
+                 response: Optional[Union[Iterable[str], str]] = None,
+                 status: Optional[Union[basestring, int]] = None,
+                 headers: Optional[Union[Headers,
+                                         Mapping[basestring, basestring],
+                                         Sequence[Tuple[basestring, basestring]]]] = None,
+                 mimetype: Optional[basestring] = None,
+                 content_type: Optional[basestring] = None,
+                 direct_passthrough: Optional[bool] = False) -> None: ...
     def call_on_close(self, func): ...
     @classmethod
     def force_type(cls, response, environ=None): ...
diff --git a/typeshed/third_party/2/werkzeug/wsgi.pyi b/typeshed/third_party/2/werkzeug/wsgi.pyi
index 9c4d005..77722ed 100644
--- a/typeshed/third_party/2/werkzeug/wsgi.pyi
+++ b/typeshed/third_party/2/werkzeug/wsgi.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.wsgi (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def responder(f): ...
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/AES.pyi b/typeshed/third_party/2and3/Crypto/Cipher/AES.pyi
index 45b13ab..b23eacc 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/AES.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/AES.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.AES (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 from .blockalgo import BlockAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/ARC2.pyi b/typeshed/third_party/2and3/Crypto/Cipher/ARC2.pyi
index 08aec54..93aea85 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/ARC2.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/ARC2.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.ARC2 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 from .blockalgo import BlockAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/ARC4.pyi b/typeshed/third_party/2and3/Crypto/Cipher/ARC4.pyi
index 3a52539..c5c17ea 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/ARC4.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/ARC4.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.ARC4 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/Blowfish.pyi b/typeshed/third_party/2and3/Crypto/Cipher/Blowfish.pyi
index 546eac2..8724013 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/Blowfish.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/Blowfish.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.Blowfish (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 from .blockalgo import BlockAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/CAST.pyi b/typeshed/third_party/2and3/Crypto/Cipher/CAST.pyi
index f63a43b..0a8c115 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/CAST.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/CAST.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.CAST (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 from .blockalgo import BlockAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/DES.pyi b/typeshed/third_party/2and3/Crypto/Cipher/DES.pyi
index c2b2f5c..a3fcf2e 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/DES.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/DES.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.DES (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 from .blockalgo import BlockAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/DES3.pyi b/typeshed/third_party/2and3/Crypto/Cipher/DES3.pyi
index f8684b7..3a7f479 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/DES3.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/DES3.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.DES3 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 
 from .blockalgo import BlockAlgo
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_OAEP.pyi b/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_OAEP.pyi
index 4f57f48..50980a4 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_OAEP.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_OAEP.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.PKCS1_OAEP (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional, Union, Text
 
 from Crypto.PublicKey.RSA import _RSAobj
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_v1_5.pyi b/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_v1_5.pyi
index 5d10282..7a4eddf 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_v1_5.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/PKCS1_v1_5.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.PKCS1_v1_5 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 
 from Crypto.PublicKey.RSA import _RSAobj
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/XOR.pyi b/typeshed/third_party/2and3/Crypto/Cipher/XOR.pyi
index c131867..2d631c5 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/XOR.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/XOR.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.XOR (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/__init__.pyi b/typeshed/third_party/2and3/Crypto/Cipher/__init__.pyi
index 3d42ce3..309f274 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   AES
 #   ARC2
diff --git a/typeshed/third_party/2and3/Crypto/Cipher/blockalgo.pyi b/typeshed/third_party/2and3/Crypto/Cipher/blockalgo.pyi
index fa71377..7c20518 100644
--- a/typeshed/third_party/2and3/Crypto/Cipher/blockalgo.pyi
+++ b/typeshed/third_party/2and3/Crypto/Cipher/blockalgo.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Cipher.blockalgo (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Union, Text
 
 MODE_ECB = ...  # type: int
diff --git a/typeshed/third_party/2and3/Crypto/Hash/HMAC.pyi b/typeshed/third_party/2and3/Crypto/Hash/HMAC.pyi
index 3a71ac4..afc005b 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/HMAC.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/HMAC.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.HMAC (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 digest_size = ...  # type: Any
diff --git a/typeshed/third_party/2and3/Crypto/Hash/MD2.pyi b/typeshed/third_party/2and3/Crypto/Hash/MD2.pyi
index 4449c71..75e382d 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/MD2.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/MD2.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.MD2 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/MD4.pyi b/typeshed/third_party/2and3/Crypto/Hash/MD4.pyi
index b2e7ee0..6644f23 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/MD4.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/MD4.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.MD4 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/MD5.pyi b/typeshed/third_party/2and3/Crypto/Hash/MD5.pyi
index 15f7ce4..e8e9eb3 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/MD5.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/MD5.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.MD5 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/RIPEMD.pyi b/typeshed/third_party/2and3/Crypto/Hash/RIPEMD.pyi
index ba965de..6919ec9 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/RIPEMD.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/RIPEMD.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.RIPEMD (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/SHA.pyi b/typeshed/third_party/2and3/Crypto/Hash/SHA.pyi
index 16965f7..03c722b 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/SHA.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/SHA.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.SHA (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/SHA224.pyi b/typeshed/third_party/2and3/Crypto/Hash/SHA224.pyi
index e9b68d2..85d6cb7 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/SHA224.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/SHA224.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.SHA224 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/SHA256.pyi b/typeshed/third_party/2and3/Crypto/Hash/SHA256.pyi
index ca21b6f..252d25e 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/SHA256.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/SHA256.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.SHA256 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/SHA384.pyi b/typeshed/third_party/2and3/Crypto/Hash/SHA384.pyi
index c318eed..3a61a63 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/SHA384.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/SHA384.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.SHA384 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/SHA512.pyi b/typeshed/third_party/2and3/Crypto/Hash/SHA512.pyi
index 6239511..10cedb0 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/SHA512.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/SHA512.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.SHA512 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash.hashalgo import HashAlgo
 
diff --git a/typeshed/third_party/2and3/Crypto/Hash/__init__.pyi b/typeshed/third_party/2and3/Crypto/Hash/__init__.pyi
index 6385911..9af06f4 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   HMAC
 #   MD2
diff --git a/typeshed/third_party/2and3/Crypto/Hash/hashalgo.pyi b/typeshed/third_party/2and3/Crypto/Hash/hashalgo.pyi
index e762453..e7c84f0 100644
--- a/typeshed/third_party/2and3/Crypto/Hash/hashalgo.pyi
+++ b/typeshed/third_party/2and3/Crypto/Hash/hashalgo.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Hash.hashalgo (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class HashAlgo:
diff --git a/typeshed/third_party/2and3/Crypto/Protocol/AllOrNothing.pyi b/typeshed/third_party/2and3/Crypto/Protocol/AllOrNothing.pyi
index 300e1bf..5d3e426 100644
--- a/typeshed/third_party/2and3/Crypto/Protocol/AllOrNothing.pyi
+++ b/typeshed/third_party/2and3/Crypto/Protocol/AllOrNothing.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Protocol.AllOrNothing (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Protocol/Chaffing.pyi b/typeshed/third_party/2and3/Crypto/Protocol/Chaffing.pyi
index 73c1d56..eec11bd 100644
--- a/typeshed/third_party/2and3/Crypto/Protocol/Chaffing.pyi
+++ b/typeshed/third_party/2and3/Crypto/Protocol/Chaffing.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Protocol.Chaffing (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 __revision__ = ...  # type: str
 
 class Chaff:
diff --git a/typeshed/third_party/2and3/Crypto/Protocol/KDF.pyi b/typeshed/third_party/2and3/Crypto/Protocol/KDF.pyi
index a14b351..20cedb0 100644
--- a/typeshed/third_party/2and3/Crypto/Protocol/KDF.pyi
+++ b/typeshed/third_party/2and3/Crypto/Protocol/KDF.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Protocol.KDF (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from Crypto.Hash import SHA as SHA1
 
diff --git a/typeshed/third_party/2and3/Crypto/Protocol/__init__.pyi b/typeshed/third_party/2and3/Crypto/Protocol/__init__.pyi
index afcab98..e3744e5 100644
--- a/typeshed/third_party/2and3/Crypto/Protocol/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Protocol/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Protocol (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   AllOrNothing
 #   Chaffing
diff --git a/typeshed/third_party/2and3/Crypto/PublicKey/DSA.pyi b/typeshed/third_party/2and3/Crypto/PublicKey/DSA.pyi
index 30b7b1c..f0e6dd2 100644
--- a/typeshed/third_party/2and3/Crypto/PublicKey/DSA.pyi
+++ b/typeshed/third_party/2and3/Crypto/PublicKey/DSA.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.PublicKey.DSA (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from .pubkey import pubkey
 
diff --git a/typeshed/third_party/2and3/Crypto/PublicKey/ElGamal.pyi b/typeshed/third_party/2and3/Crypto/PublicKey/ElGamal.pyi
index 4ed2c5b..5bc238d 100644
--- a/typeshed/third_party/2and3/Crypto/PublicKey/ElGamal.pyi
+++ b/typeshed/third_party/2and3/Crypto/PublicKey/ElGamal.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.PublicKey.ElGamal (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 from Crypto.PublicKey.pubkey import pubkey
diff --git a/typeshed/third_party/2and3/Crypto/PublicKey/RSA.pyi b/typeshed/third_party/2and3/Crypto/PublicKey/RSA.pyi
index 1fbd6ff..cd10d74 100644
--- a/typeshed/third_party/2and3/Crypto/PublicKey/RSA.pyi
+++ b/typeshed/third_party/2and3/Crypto/PublicKey/RSA.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.PublicKey.RSA (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional, Union, Text
 from .pubkey import pubkey
 
diff --git a/typeshed/third_party/2and3/Crypto/PublicKey/__init__.pyi b/typeshed/third_party/2and3/Crypto/PublicKey/__init__.pyi
index 84bc3bc..36d9e94 100644
--- a/typeshed/third_party/2and3/Crypto/PublicKey/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/PublicKey/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.PublicKey (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   DSA
 #   ElGamal
diff --git a/typeshed/third_party/2and3/Crypto/PublicKey/pubkey.pyi b/typeshed/third_party/2and3/Crypto/PublicKey/pubkey.pyi
index dd34d69..cbaf5f3 100644
--- a/typeshed/third_party/2and3/Crypto/PublicKey/pubkey.pyi
+++ b/typeshed/third_party/2and3/Crypto/PublicKey/pubkey.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.PublicKey.pubkey (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from Crypto.Util.number import *  # noqa: F403
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaAccumulator.pyi b/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaAccumulator.pyi
index e843070..bb898b2 100644
--- a/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaAccumulator.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaAccumulator.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Random.Fortuna.FortunaAccumulator (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaGenerator.pyi b/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaGenerator.pyi
index 89d13ab..1d69094 100644
--- a/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaGenerator.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/Fortuna/FortunaGenerator.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Random.Fortuna.FortunaGenerator (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Random/Fortuna/SHAd256.pyi b/typeshed/third_party/2and3/Crypto/Random/Fortuna/SHAd256.pyi
index 5a83fd9..0dfb691 100644
--- a/typeshed/third_party/2and3/Crypto/Random/Fortuna/SHAd256.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/Fortuna/SHAd256.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Random.Fortuna.SHAd256 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class _SHAd256:
diff --git a/typeshed/third_party/2and3/Crypto/Random/Fortuna/__init__.pyi b/typeshed/third_party/2and3/Crypto/Random/Fortuna/__init__.pyi
index fd03fb2..e69de29 100644
--- a/typeshed/third_party/2and3/Crypto/Random/Fortuna/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/Fortuna/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for Crypto.Random.Fortuna (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/2and3/Crypto/Random/OSRNG/__init__.pyi b/typeshed/third_party/2and3/Crypto/Random/OSRNG/__init__.pyi
index e73ed2e..a9c47e6 100644
--- a/typeshed/third_party/2and3/Crypto/Random/OSRNG/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/OSRNG/__init__.pyi
@@ -1,5 +1 @@
-# Stubs for Crypto.Random.OSRNG (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Random/OSRNG/fallback.pyi b/typeshed/third_party/2and3/Crypto/Random/OSRNG/fallback.pyi
index fafc388..d25d859 100644
--- a/typeshed/third_party/2and3/Crypto/Random/OSRNG/fallback.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/OSRNG/fallback.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Random.OSRNG.fallback (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from .rng_base import BaseRNG
 
 class PythonOSURandomRNG(BaseRNG):
diff --git a/typeshed/third_party/2and3/Crypto/Random/OSRNG/posix.pyi b/typeshed/third_party/2and3/Crypto/Random/OSRNG/posix.pyi
index c7d4613..0506ffa 100644
--- a/typeshed/third_party/2and3/Crypto/Random/OSRNG/posix.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/OSRNG/posix.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Random.OSRNG.posix (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from .rng_base import BaseRNG
 
diff --git a/typeshed/third_party/2and3/Crypto/Random/OSRNG/rng_base.pyi b/typeshed/third_party/2and3/Crypto/Random/OSRNG/rng_base.pyi
index 4fa634a..46ac79c 100644
--- a/typeshed/third_party/2and3/Crypto/Random/OSRNG/rng_base.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/OSRNG/rng_base.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Random.OSRNG.rng_base (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 __revision__ = ...  # type: str
 
 class BaseRNG:
diff --git a/typeshed/third_party/2and3/Crypto/Random/__init__.pyi b/typeshed/third_party/2and3/Crypto/Random/__init__.pyi
index d9872cb..f30acfd 100644
--- a/typeshed/third_party/2and3/Crypto/Random/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/__init__.pyi
@@ -1,5 +1 @@
-# Stubs for Crypto.Random (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 def new(*args, **kwargs): ...
diff --git a/typeshed/third_party/2and3/Crypto/Random/random.pyi b/typeshed/third_party/2and3/Crypto/Random/random.pyi
index 12a2e6f..4178db7 100644
--- a/typeshed/third_party/2and3/Crypto/Random/random.pyi
+++ b/typeshed/third_party/2and3/Crypto/Random/random.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Random.random (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class StrongRandom:
diff --git a/typeshed/third_party/2and3/Crypto/Signature/PKCS1_PSS.pyi b/typeshed/third_party/2and3/Crypto/Signature/PKCS1_PSS.pyi
index 12edf26..8341c2b 100644
--- a/typeshed/third_party/2and3/Crypto/Signature/PKCS1_PSS.pyi
+++ b/typeshed/third_party/2and3/Crypto/Signature/PKCS1_PSS.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Signature.PKCS1_PSS (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class PSS_SigScheme:
diff --git a/typeshed/third_party/2and3/Crypto/Signature/PKCS1_v1_5.pyi b/typeshed/third_party/2and3/Crypto/Signature/PKCS1_v1_5.pyi
index d48d3a3..4a2b225 100644
--- a/typeshed/third_party/2and3/Crypto/Signature/PKCS1_v1_5.pyi
+++ b/typeshed/third_party/2and3/Crypto/Signature/PKCS1_v1_5.pyi
@@ -1,8 +1,3 @@
-# Stubs for Crypto.Signature.PKCS1_v1_5 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-
 class PKCS115_SigScheme:
     def __init__(self, key) -> None: ...
     def can_sign(self): ...
diff --git a/typeshed/third_party/2and3/Crypto/Signature/__init__.pyi b/typeshed/third_party/2and3/Crypto/Signature/__init__.pyi
index 710372a..560f06f 100644
--- a/typeshed/third_party/2and3/Crypto/Signature/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Signature/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Signature (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   PKCS1_PSS
 #   PKCS1_v1_5
diff --git a/typeshed/third_party/2and3/Crypto/Util/Counter.pyi b/typeshed/third_party/2and3/Crypto/Util/Counter.pyi
index 620c1be..4aae7f2 100644
--- a/typeshed/third_party/2and3/Crypto/Util/Counter.pyi
+++ b/typeshed/third_party/2and3/Crypto/Util/Counter.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Util.Counter (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def new(nbits, prefix: Any = ..., suffix: Any = ..., initial_value: int = ..., overflow: int = ..., little_endian: bool = ..., allow_wraparound: bool = ..., disable_shortcut: bool = ...): ...
diff --git a/typeshed/third_party/2and3/Crypto/Util/RFC1751.pyi b/typeshed/third_party/2and3/Crypto/Util/RFC1751.pyi
index abd7444..273204b 100644
--- a/typeshed/third_party/2and3/Crypto/Util/RFC1751.pyi
+++ b/typeshed/third_party/2and3/Crypto/Util/RFC1751.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Util.RFC1751 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Util/__init__.pyi b/typeshed/third_party/2and3/Crypto/Util/__init__.pyi
index 26f6576..1747299 100644
--- a/typeshed/third_party/2and3/Crypto/Util/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/Util/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Util (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   RFC1751
 #   asn1
diff --git a/typeshed/third_party/2and3/Crypto/Util/asn1.pyi b/typeshed/third_party/2and3/Crypto/Util/asn1.pyi
index b9227af..036a303 100644
--- a/typeshed/third_party/2and3/Crypto/Util/asn1.pyi
+++ b/typeshed/third_party/2and3/Crypto/Util/asn1.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Util.asn1 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class DerObject:
diff --git a/typeshed/third_party/2and3/Crypto/Util/number.pyi b/typeshed/third_party/2and3/Crypto/Util/number.pyi
index 265f142..796e487 100644
--- a/typeshed/third_party/2and3/Crypto/Util/number.pyi
+++ b/typeshed/third_party/2and3/Crypto/Util/number.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Util.number (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from warnings import warn as _warn
 
diff --git a/typeshed/third_party/2and3/Crypto/Util/randpool.pyi b/typeshed/third_party/2and3/Crypto/Util/randpool.pyi
index 4a5f2ac..2b05706 100644
--- a/typeshed/third_party/2and3/Crypto/Util/randpool.pyi
+++ b/typeshed/third_party/2and3/Crypto/Util/randpool.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.Util.randpool (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 __revision__ = ...  # type: str
diff --git a/typeshed/third_party/2and3/Crypto/Util/strxor.pyi b/typeshed/third_party/2and3/Crypto/Util/strxor.pyi
index 8ba57b5..cb6269b 100644
--- a/typeshed/third_party/2and3/Crypto/Util/strxor.pyi
+++ b/typeshed/third_party/2and3/Crypto/Util/strxor.pyi
@@ -1,6 +1,2 @@
-# Stubs for Crypto.Util.strxor (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 def strxor(*args, **kwargs): ...
 def strxor_c(*args, **kwargs): ...
diff --git a/typeshed/third_party/2and3/Crypto/__init__.pyi b/typeshed/third_party/2and3/Crypto/__init__.pyi
index 7b99b04..6d8e124 100644
--- a/typeshed/third_party/2and3/Crypto/__init__.pyi
+++ b/typeshed/third_party/2and3/Crypto/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 # Names in __all__ with no definition:
 #   Cipher
 #   Hash
diff --git a/typeshed/third_party/2and3/Crypto/pct_warnings.pyi b/typeshed/third_party/2and3/Crypto/pct_warnings.pyi
index 6fb4fc8..b77e975 100644
--- a/typeshed/third_party/2and3/Crypto/pct_warnings.pyi
+++ b/typeshed/third_party/2and3/Crypto/pct_warnings.pyi
@@ -1,7 +1,3 @@
-# Stubs for Crypto.pct_warnings (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 class CryptoWarning(Warning): ...
 class CryptoDeprecationWarning(DeprecationWarning, CryptoWarning): ...
 class CryptoRuntimeWarning(RuntimeWarning, CryptoWarning): ...
diff --git a/typeshed/third_party/2and3/atomicwrites/__init__.pyi b/typeshed/third_party/2and3/atomicwrites/__init__.pyi
index 34d74fb..ba6ae22 100644
--- a/typeshed/third_party/2and3/atomicwrites/__init__.pyi
+++ b/typeshed/third_party/2and3/atomicwrites/__init__.pyi
@@ -1,16 +1,16 @@
-import contextlib
 import os
 import sys
 import tempfile
-from typing import Any, AnyStr, Callable, IO, Iterator, Text
+from typing import Any, AnyStr, Callable, ContextManager, IO, Iterator, Optional, Text
+
 def replace_atomic(src: AnyStr, dst: AnyStr) -> None: ...
 def move_atomic(src: AnyStr, dst: AnyStr) -> None: ...
 class AtomicWriter(object):
     def __init__(self, path: AnyStr, mode: Text='w', overwrite: bool=False) -> None: ...
-    def open(self) -> contextlib.ContextManager[IO]: ...
-    def _open(self, get_fileobject: Callable) -> contextlib.ContextManager[IO]: ...
-    def get_fileobject(self, dir: AnyStr=None, **kwargs) -> IO: ...
+    def open(self) -> ContextManager[IO]: ...
+    def _open(self, get_fileobject: Callable) -> ContextManager[IO]: ...
+    def get_fileobject(self, dir: Optional[AnyStr] = None, **kwargs) -> IO: ...
     def sync(self, f: IO) -> None: ...
     def commit(self, f: IO) -> None: ...
     def rollback(self, f: IO) -> None: ...
-def atomic_write(path: AnyStr, writer_cls: type=AtomicWriter, **cls_kwargs) -> contextlib.ContextManager[IO]: ...
+def atomic_write(path: AnyStr, writer_cls: type=AtomicWriter, **cls_kwargs) -> ContextManager[IO]: ...
diff --git a/typeshed/third_party/2and3/backports_abc.pyi b/typeshed/third_party/2and3/backports_abc.pyi
index 1b4c3a2..8deebc0 100644
--- a/typeshed/third_party/2and3/backports_abc.pyi
+++ b/typeshed/third_party/2and3/backports_abc.pyi
@@ -1,7 +1,3 @@
-# Stubs for backports_abc (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def mk_gen(): ...
diff --git a/typeshed/third_party/2and3/boto/__init__.pyi b/typeshed/third_party/2and3/boto/__init__.pyi
index a95c1df..d7b30c8 100644
--- a/typeshed/third_party/2and3/boto/__init__.pyi
+++ b/typeshed/third_party/2and3/boto/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional, Text
 import logging
 
diff --git a/typeshed/third_party/2and3/boto/auth.pyi b/typeshed/third_party/2and3/boto/auth.pyi
index 8fdf6ae..57127ad 100644
--- a/typeshed/third_party/2and3/boto/auth.pyi
+++ b/typeshed/third_party/2and3/boto/auth.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.auth (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from boto.auth_handler import AuthHandler
 
diff --git a/typeshed/third_party/2and3/boto/auth_handler.pyi b/typeshed/third_party/2and3/boto/auth_handler.pyi
index 097f762..b9a0400 100644
--- a/typeshed/third_party/2and3/boto/auth_handler.pyi
+++ b/typeshed/third_party/2and3/boto/auth_handler.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.auth_handler (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from boto.plugin import Plugin
 
diff --git a/typeshed/third_party/2and3/boto/compat.pyi b/typeshed/third_party/2and3/boto/compat.pyi
index 85539f8..b0534a4 100644
--- a/typeshed/third_party/2and3/boto/compat.pyi
+++ b/typeshed/third_party/2and3/boto/compat.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.compat (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from base64 import encodestring as encodebytes
 
diff --git a/typeshed/third_party/2and3/boto/connection.pyi b/typeshed/third_party/2and3/boto/connection.pyi
index c8275b8..d8c40cb 100644
--- a/typeshed/third_party/2and3/boto/connection.pyi
+++ b/typeshed/third_party/2and3/boto/connection.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.connection (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Dict, Optional, Text
 from six.moves import http_client
 
diff --git a/typeshed/third_party/2and3/boto/ec2/__init__.pyi b/typeshed/third_party/2and3/boto/ec2/__init__.pyi
index 64fa781..edb9359 100644
--- a/typeshed/third_party/2and3/boto/ec2/__init__.pyi
+++ b/typeshed/third_party/2and3/boto/ec2/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.ec2 (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 RegionData = ...  # type: Any
diff --git a/typeshed/third_party/2and3/boto/elb/__init__.pyi b/typeshed/third_party/2and3/boto/elb/__init__.pyi
index 82e17fa..1d6c43f 100644
--- a/typeshed/third_party/2and3/boto/elb/__init__.pyi
+++ b/typeshed/third_party/2and3/boto/elb/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.ec2.elb (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from boto.connection import AWSQueryConnection
 
diff --git a/typeshed/third_party/2and3/boto/exception.pyi b/typeshed/third_party/2and3/boto/exception.pyi
index 83778af..bf11522 100644
--- a/typeshed/third_party/2and3/boto/exception.pyi
+++ b/typeshed/third_party/2and3/boto/exception.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.exception (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from boto.compat import StandardError
 
diff --git a/typeshed/third_party/2and3/boto/kms/__init__.pyi b/typeshed/third_party/2and3/boto/kms/__init__.pyi
index 7382eca..0640e39 100644
--- a/typeshed/third_party/2and3/boto/kms/__init__.pyi
+++ b/typeshed/third_party/2and3/boto/kms/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.kms (Python 3.6)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import List
 import boto
 
diff --git a/typeshed/third_party/2and3/boto/kms/exceptions.pyi b/typeshed/third_party/2and3/boto/kms/exceptions.pyi
index e09b895..5ac2ecd 100644
--- a/typeshed/third_party/2and3/boto/kms/exceptions.pyi
+++ b/typeshed/third_party/2and3/boto/kms/exceptions.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.kms.exceptions (Python 3.6)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from boto.exception import BotoServerError
 
 class InvalidGrantTokenException(BotoServerError): ...
diff --git a/typeshed/third_party/2and3/boto/kms/layer1.pyi b/typeshed/third_party/2and3/boto/kms/layer1.pyi
index 777f2f7..558b02a 100644
--- a/typeshed/third_party/2and3/boto/kms/layer1.pyi
+++ b/typeshed/third_party/2and3/boto/kms/layer1.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.kms.layer1 (Python 3.6)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Dict, List, Mapping, Optional, Type
 from boto.connection import AWSQueryConnection
 
diff --git a/typeshed/third_party/2and3/boto/plugin.pyi b/typeshed/third_party/2and3/boto/plugin.pyi
index 37b9721..c40c6c4 100644
--- a/typeshed/third_party/2and3/boto/plugin.pyi
+++ b/typeshed/third_party/2and3/boto/plugin.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.plugin (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class Plugin:
diff --git a/typeshed/third_party/2and3/boto/regioninfo.pyi b/typeshed/third_party/2and3/boto/regioninfo.pyi
index 9dbb46f..3772609 100644
--- a/typeshed/third_party/2and3/boto/regioninfo.pyi
+++ b/typeshed/third_party/2and3/boto/regioninfo.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.regioninfo (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 def load_endpoint_json(path): ...
diff --git a/typeshed/third_party/2and3/boto/s3/__init__.pyi b/typeshed/third_party/2and3/boto/s3/__init__.pyi
index b359694..2dcb333 100644
--- a/typeshed/third_party/2and3/boto/s3/__init__.pyi
+++ b/typeshed/third_party/2and3/boto/s3/__init__.pyi
@@ -1,6 +1,4 @@
-# Stubs for boto.s3 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Optional
 
 from .connection import S3Connection
 
@@ -10,7 +8,7 @@ from boto.regioninfo import RegionInfo
 from typing import List, Type, Text
 
 class S3RegionInfo(RegionInfo):
-    def connect(self, name: Text=None, endpoint: str=None, connection_cls: Type[AWSAuthConnection]=None, **kw_params) -> S3Connection: ...
+    def connect(self, name: Optional[Text] = None, endpoint: Optional[str] = None, connection_cls: Optional[Type[AWSAuthConnection]] = None, **kw_params) -> S3Connection: ...
 
 def regions() -> List[S3RegionInfo]: ...
 def connect_to_region(region_name: Text, **kw_params): ...
diff --git a/typeshed/third_party/2and3/boto/s3/acl.pyi b/typeshed/third_party/2and3/boto/s3/acl.pyi
index 8813009..fccf212 100644
--- a/typeshed/third_party/2and3/boto/s3/acl.pyi
+++ b/typeshed/third_party/2and3/boto/s3/acl.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.acl (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from .connection import S3Connection
 from .user import User
 from typing import Any, Dict, Optional, List, Text, Union
diff --git a/typeshed/third_party/2and3/boto/s3/bucket.pyi b/typeshed/third_party/2and3/boto/s3/bucket.pyi
index beb1d27..031c55a 100644
--- a/typeshed/third_party/2and3/boto/s3/bucket.pyi
+++ b/typeshed/third_party/2and3/boto/s3/bucket.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.bucket (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from .bucketlistresultset import BucketListResultSet
 from .connection import S3Connection
 from .key import Key
diff --git a/typeshed/third_party/2and3/boto/s3/bucketlistresultset.pyi b/typeshed/third_party/2and3/boto/s3/bucketlistresultset.pyi
index 97e79b0..e219faa 100644
--- a/typeshed/third_party/2and3/boto/s3/bucketlistresultset.pyi
+++ b/typeshed/third_party/2and3/boto/s3/bucketlistresultset.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.bucketlistresultset (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from .bucket import Bucket
 from .key import Key
 
diff --git a/typeshed/third_party/2and3/boto/s3/bucketlogging.pyi b/typeshed/third_party/2and3/boto/s3/bucketlogging.pyi
index a3f83a5..5c53f2a 100644
--- a/typeshed/third_party/2and3/boto/s3/bucketlogging.pyi
+++ b/typeshed/third_party/2and3/boto/s3/bucketlogging.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.bucketlogging (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class BucketLogging:
diff --git a/typeshed/third_party/2and3/boto/s3/connection.pyi b/typeshed/third_party/2and3/boto/s3/connection.pyi
index 73661f0..c84f20d 100644
--- a/typeshed/third_party/2and3/boto/s3/connection.pyi
+++ b/typeshed/third_party/2and3/boto/s3/connection.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.connection (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from .bucket import Bucket
 
 from typing import Any, Dict, Optional, Text, Type
diff --git a/typeshed/third_party/2and3/boto/s3/cors.pyi b/typeshed/third_party/2and3/boto/s3/cors.pyi
index 07f49b0..9ae263d 100644
--- a/typeshed/third_party/2and3/boto/s3/cors.pyi
+++ b/typeshed/third_party/2and3/boto/s3/cors.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.cors (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class CORSRule:
diff --git a/typeshed/third_party/2and3/boto/s3/deletemarker.pyi b/typeshed/third_party/2and3/boto/s3/deletemarker.pyi
index cf7bc64..b2ad36a 100644
--- a/typeshed/third_party/2and3/boto/s3/deletemarker.pyi
+++ b/typeshed/third_party/2and3/boto/s3/deletemarker.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.deletemarker (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class DeleteMarker:
diff --git a/typeshed/third_party/2and3/boto/s3/key.pyi b/typeshed/third_party/2and3/boto/s3/key.pyi
index f7232b7..ed44009 100644
--- a/typeshed/third_party/2and3/boto/s3/key.pyi
+++ b/typeshed/third_party/2and3/boto/s3/key.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.key (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Callable, Dict, Optional, Text
 
 class Key:
diff --git a/typeshed/third_party/2and3/boto/s3/keyfile.pyi b/typeshed/third_party/2and3/boto/s3/keyfile.pyi
index 2fe5faa..447ab16 100644
--- a/typeshed/third_party/2and3/boto/s3/keyfile.pyi
+++ b/typeshed/third_party/2and3/boto/s3/keyfile.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.keyfile (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class KeyFile:
diff --git a/typeshed/third_party/2and3/boto/s3/lifecycle.pyi b/typeshed/third_party/2and3/boto/s3/lifecycle.pyi
index c15048e..18a7533 100644
--- a/typeshed/third_party/2and3/boto/s3/lifecycle.pyi
+++ b/typeshed/third_party/2and3/boto/s3/lifecycle.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.lifecycle (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class Rule:
diff --git a/typeshed/third_party/2and3/boto/s3/multidelete.pyi b/typeshed/third_party/2and3/boto/s3/multidelete.pyi
index 46449c4..fa19cad 100644
--- a/typeshed/third_party/2and3/boto/s3/multidelete.pyi
+++ b/typeshed/third_party/2and3/boto/s3/multidelete.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.multidelete (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class Deleted:
diff --git a/typeshed/third_party/2and3/boto/s3/multipart.pyi b/typeshed/third_party/2and3/boto/s3/multipart.pyi
index 2bc738f..81a9452 100644
--- a/typeshed/third_party/2and3/boto/s3/multipart.pyi
+++ b/typeshed/third_party/2and3/boto/s3/multipart.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.multipart (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class CompleteMultiPartUpload:
diff --git a/typeshed/third_party/2and3/boto/s3/prefix.pyi b/typeshed/third_party/2and3/boto/s3/prefix.pyi
index 12501b2..0d7b61a 100644
--- a/typeshed/third_party/2and3/boto/s3/prefix.pyi
+++ b/typeshed/third_party/2and3/boto/s3/prefix.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.prefix (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class Prefix:
diff --git a/typeshed/third_party/2and3/boto/s3/tagging.pyi b/typeshed/third_party/2and3/boto/s3/tagging.pyi
index 07c1fca..4f4ad04 100644
--- a/typeshed/third_party/2and3/boto/s3/tagging.pyi
+++ b/typeshed/third_party/2and3/boto/s3/tagging.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.tagging (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class Tag:
diff --git a/typeshed/third_party/2and3/boto/s3/user.pyi b/typeshed/third_party/2and3/boto/s3/user.pyi
index 21832e9..73d9342 100644
--- a/typeshed/third_party/2and3/boto/s3/user.pyi
+++ b/typeshed/third_party/2and3/boto/s3/user.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.user (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class User:
diff --git a/typeshed/third_party/2and3/boto/s3/website.pyi b/typeshed/third_party/2and3/boto/s3/website.pyi
index f832077..b410b82 100644
--- a/typeshed/third_party/2and3/boto/s3/website.pyi
+++ b/typeshed/third_party/2and3/boto/s3/website.pyi
@@ -1,7 +1,3 @@
-# Stubs for boto.s3.website (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 def tag(key, value): ...
diff --git a/typeshed/third_party/3.6/click/__init__.pyi b/typeshed/third_party/2and3/click/__init__.pyi
similarity index 100%
rename from typeshed/third_party/3.6/click/__init__.pyi
rename to typeshed/third_party/2and3/click/__init__.pyi
diff --git a/typeshed/third_party/3.6/click/core.pyi b/typeshed/third_party/2and3/click/core.pyi
similarity index 77%
rename from typeshed/third_party/3.6/click/core.pyi
rename to typeshed/third_party/2and3/click/core.pyi
index abd4681..c0e054d 100644
--- a/typeshed/third_party/3.6/click/core.pyi
+++ b/typeshed/third_party/2and3/click/core.pyi
@@ -30,7 +30,7 @@ def invoke_param_callback(
 
 @contextmanager
 def augment_usage_errors(
-    ctx: 'Context', param: 'Parameter' = None
+    ctx: 'Context', param: Optional['Parameter'] = None
 ) -> Generator[None, None, None]:
     ...
 
@@ -73,20 +73,20 @@ class Context:
     def __init__(
         self,
         command: 'Command',
-        parent: 'Context' = None,
-        info_name: str = None,
-        obj: Any = None,
-        auto_envvar_prefix: str = None,
-        default_map: Mapping[str, Any] = None,
-        terminal_width: int = None,
-        max_content_width: int = None,
+        parent: Optional['Context'] = None,
+        info_name: Optional[str] = None,
+        obj: Optional[Any] = None,
+        auto_envvar_prefix: Optional[str] = None,
+        default_map: Optional[Mapping[str, Any]] = None,
+        terminal_width: Optional[int] = None,
+        max_content_width: Optional[int] = None,
         resilient_parsing: bool = False,
-        allow_extra_args: bool = None,
-        allow_interspersed_args: bool = None,
-        ignore_unknown_options: bool = None,
-        help_option_names: List[str] = None,
-        token_normalize_func: Callable[[str], str] = None,
-        color: bool = None
+        allow_extra_args: Optional[bool] = None,
+        allow_interspersed_args: Optional[bool] = None,
+        ignore_unknown_options: Optional[bool] = None,
+        help_option_names: Optional[List[str]] = None,
+        token_normalize_func: Optional[Callable[[str], str]] = None,
+        color: Optional[bool] = None
     ) -> None:
         ...
 
@@ -147,7 +147,7 @@ class BaseCommand:
     name: str
     context_settings: Dict
 
-    def __init__(self, name: str, context_settings: Dict = None) -> None:
+    def __init__(self, name: str, context_settings: Optional[Dict] = None) -> None:
         ...
 
     def get_usage(self, ctx: Context) -> str:
@@ -157,7 +157,7 @@ class BaseCommand:
         ...
 
     def make_context(
-        self, info_name: str, args: List[str], parent: Context = None, **extra
+        self, info_name: str, args: List[str], parent: Optional[Context] = None, **extra
     ) -> Context:
         ...
 
@@ -169,9 +169,9 @@ class BaseCommand:
 
     def main(
         self,
-        args: List[str] = None,
-        prog_name: str = None,
-        complete_var: str = None,
+        args: Optional[List[str]] = None,
+        prog_name: Optional[str] = None,
+        complete_var: Optional[str] = None,
         standalone_mode: bool = True,
         **extra
     ) -> Any:
@@ -193,12 +193,12 @@ class Command(BaseCommand):
     def __init__(
         self,
         name: str,
-        context_settings: Dict = None,
-        callback: Callable = None,
-        params: List['Parameter'] = None,
-        help: str = None,
-        epilog: str = None,
-        short_help: str = None,
+        context_settings: Optional[Dict] = None,
+        callback: Optional[Callable] = None,
+        params: Optional[List['Parameter']] = None,
+        help: Optional[str] = None,
+        epilog: Optional[str] = None,
+        short_help: Optional[str] = None,
         options_metavar: str = '[OPTIONS]',
         add_help_option: bool = True
     ) -> None:
@@ -252,12 +252,12 @@ class MultiCommand(Command):
 
     def __init__(
         self,
-        name: str = None,
+        name: Optional[str] = None,
         invoke_without_command: bool = False,
-        no_args_is_help: bool = None,
-        subcommand_metavar: str = None,
+        no_args_is_help: Optional[bool] = None,
+        subcommand_metavar: Optional[str] = None,
         chain: bool = False,
-        result_callback: Callable = None,
+        result_callback: Optional[Callable] = None,
         **attrs
     ) -> None:
         ...
@@ -286,11 +286,11 @@ class Group(MultiCommand):
     commands: Dict[str, Command]
 
     def __init__(
-        self, name: str = None, commands: Dict[str, Command] = None, **attrs
+        self, name: Optional[str] = None, commands: Optional[Dict[str, Command]] = None, **attrs
     ) -> None:
         ...
 
-    def add_command(self, cmd: Command, name: str = None):
+    def add_command(self, cmd: Command, name: Optional[str] = None):
         ...
 
     def command(self, *args, **kwargs) -> _Decorator:
@@ -304,7 +304,7 @@ class CommandCollection(MultiCommand):
     sources: List[MultiCommand]
 
     def __init__(
-        self, name: str = None, sources: List[MultiCommand] = None, **attrs
+        self, name: Optional[str] = None, sources: Optional[List[MultiCommand]] = None, **attrs
     ) -> None:
         ...
 
@@ -332,16 +332,16 @@ class Parameter:
 
     def __init__(
         self,
-        param_decls: List[str] = None,
-        type: Union[type, 'ParamType'] = None,
+        param_decls: Optional[List[str]] = None,
+        type: Optional[Union[type, 'ParamType']] = None,
         required: bool = False,
-        default: Any = None,
-        callback: Callable[[Context, 'Parameter', str], Any] = None,
-        nargs: int = None,
-        metavar: str = None,
+        default: Optional[Any] = None,
+        callback: Optional[Callable[[Context, 'Parameter', str], Any]] = None,
+        nargs: Optional[int] = None,
+        metavar: Optional[str] = None,
         expose_value: bool = True,
         is_eager: bool = False,
-        envvar: Union[str, List[str]] = None
+        envvar: Optional[Union[str, List[str]]] = None
     ) -> None:
         ...
 
@@ -402,18 +402,18 @@ class Option(Parameter):
 
     def __init__(
         self,
-        param_decls: List[str] = None,
+        param_decls: Optional[List[str]] = None,
         show_default: bool = False,
         prompt: Union[bool, str] = False,
         confirmation_prompt: bool = False,
         hide_input: bool = False,
-        is_flag: bool = None,
-        flag_value: Any = None,
+        is_flag: Optional[bool] = None,
+        flag_value: Optional[Any] = None,
         multiple: bool = False,
         count: bool = False,
         allow_from_autoenv: bool = True,
-        type: Union[type, 'ParamType'] = None,
-        help: str = None,
+        type: Optional[Union[type, 'ParamType']] = None,
+        help: Optional[str] = None,
         **attrs
     ) -> None:
         ...
@@ -425,8 +425,8 @@ class Option(Parameter):
 class Argument(Parameter):
     def __init__(
         self,
-        param_decls: List[str] = None,
-        required: bool = None,
+        param_decls: Optional[List[str]] = None,
+        required: Optional[bool] = None,
         **attrs
     ) -> None:
         ...
diff --git a/typeshed/third_party/3.6/click/decorators.pyi b/typeshed/third_party/2and3/click/decorators.pyi
similarity index 57%
rename from typeshed/third_party/3.6/click/decorators.pyi
rename to typeshed/third_party/2and3/click/decorators.pyi
index 8cd1616..b9d6faf 100644
--- a/typeshed/third_party/3.6/click/decorators.pyi
+++ b/typeshed/third_party/2and3/click/decorators.pyi
@@ -1,5 +1,5 @@
 from distutils.version import Version
-from typing import Any, Callable, Dict, List, TypeVar, Union
+from typing import Any, Callable, Dict, List, Optional, TypeVar, Union
 
 from click.core import Command, Group, Argument, Option, Parameter, Context
 from click.types import ParamType
@@ -7,6 +7,10 @@ from click.types import ParamType
 _T = TypeVar('_T')
 _Decorator = Callable[[_T], _T]
 
+_Callback = Callable[
+    [Context, Union[Option, Parameter], Union[bool, int, str]],
+    Any
+]
 
 def pass_context(_T) -> _T:
     ...
@@ -26,12 +30,13 @@ def make_pass_decorator(
 # arguments from core.pyi to help with type checking.
 
 def command(
-    name: str = None,
+    name: Optional[str] = None,
     cls: type = Command,
     # Command
-    help: str = None,
-    epilog: str = None,
-    short_help: str = None,
+    context_settings: Optional[Dict] = ...,
+    help: Optional[str] = None,
+    epilog: Optional[str] = None,
+    short_help: Optional[str] = None,
     options_metavar: str = '[OPTIONS]',
     add_help_option: bool = True,
 ) -> _Decorator:
@@ -41,20 +46,20 @@ def command(
 # This inherits attrs from Group, MultiCommand and Command.
 
 def group(
-    name: str = None,
+    name: Optional[str] = None,
     cls: type = Group,
     # Group
-    commands: Dict[str, Command] = None,
+    commands: Optional[Dict[str, Command]] = None,
     # MultiCommand
     invoke_without_command: bool = False,
-    no_args_is_help: bool = None,
-    subcommand_metavar: str = None,
+    no_args_is_help: Optional[bool] = None,
+    subcommand_metavar: Optional[str] = None,
     chain: bool = False,
-    result_callback: Callable = None,
+    result_callback: Optional[Callable] = None,
     # Command
-    help: str = None,
-    epilog: str = None,
-    short_help: str = None,
+    help: Optional[str] = None,
+    epilog: Optional[str] = None,
+    short_help: Optional[str] = None,
     options_metavar: str = '[OPTIONS]',
     add_help_option: bool = True,
     # User-defined
@@ -67,16 +72,16 @@ def argument(
     *param_decls: str,
     cls: type = Argument,
     # Argument
-    required: bool = None,
+    required: Optional[bool] = None,
     # Parameter
-    type: Union[type, ParamType] = None,
-    default: Any = None,
-    callback: Callable[[Context, Parameter, str], Any] = None,
-    nargs: int = None,
-    metavar: str = None,
+    type: Optional[Union[type, ParamType]] = None,
+    default: Optional[Any] = None,
+    callback: Optional[_Callback] = ...,
+    nargs: Optional[int] = None,
+    metavar: Optional[str] = None,
     expose_value: bool = True,
     is_eager: bool = False,
-    envvar: Union[str, List[str]] = None
+    envvar: Optional[Union[str, List[str]]] = None
 ) -> _Decorator:
     ...
 
@@ -89,21 +94,22 @@ def option(
     prompt: bool = False,
     confirmation_prompt: bool = False,
     hide_input: bool = False,
-    is_flag: bool = None,
-    flag_value: Any = None,
+    is_flag: Optional[bool] = None,
+    flag_value: Optional[Any] = None,
     multiple: bool = False,
     count: bool = False,
     allow_from_autoenv: bool = True,
-    type: Union[type, ParamType] = None,
-    help: str = None,
+    type: Optional[Union[type, ParamType]] = None,
+    help: Optional[str] = None,
     # Parameter
-    default: Any = None,
-    callback: Callable[[Context, Parameter, str], Any] = None,
-    nargs: int = None,
-    metavar: str = None,
+    default: Optional[Any] = None,
+    required: bool = False,
+    callback: Optional[_Callback] = ...,
+    nargs: Optional[int] = None,
+    metavar: Optional[str] = None,
     expose_value: bool = True,
     is_eager: bool = False,
-    envvar: Union[str, List[str]] = None
+    envvar: Optional[Union[str, List[str]]] = None
 ) -> _Decorator:
     ...
 
@@ -118,20 +124,20 @@ def confirmation_option(
     confirmation_prompt: bool = False,
     hide_input: bool = False,
     is_flag: bool = True,
-    flag_value: Any = None,
+    flag_value: Optional[Any] = None,
     multiple: bool = False,
     count: bool = False,
     allow_from_autoenv: bool = True,
-    type: Union[type, ParamType] = None,
+    type: Optional[Union[type, ParamType]] = None,
     help: str = 'Confirm the action without prompting.',
     # Parameter
-    default: Any = None,
-    callback: Callable[[Context, Parameter, str], Any] = None,
-    nargs: int = None,
-    metavar: str = None,
+    default: Optional[Any] = None,
+    callback: Optional[_Callback] = ...,
+    nargs: Optional[int] = None,
+    metavar: Optional[str] = None,
     expose_value: bool = False,
     is_eager: bool = False,
-    envvar: Union[str, List[str]] = None
+    envvar: Optional[Union[str, List[str]]] = None
 ) -> _Decorator:
     ...
 
@@ -145,51 +151,51 @@ def password_option(
     prompt: bool = True,
     confirmation_prompt: bool = True,
     hide_input: bool = True,
-    is_flag: bool = None,
-    flag_value: Any = None,
+    is_flag: Optional[bool] = None,
+    flag_value: Optional[Any] = None,
     multiple: bool = False,
     count: bool = False,
     allow_from_autoenv: bool = True,
-    type: Union[type, ParamType] = None,
-    help: str = None,
+    type: Optional[Union[type, ParamType]] = None,
+    help: Optional[str] = None,
     # Parameter
-    default: Any = None,
-    callback: Callable[[Context, Parameter, str], Any] = None,
-    nargs: int = None,
-    metavar: str = None,
+    default: Optional[Any] = None,
+    callback: Optional[_Callback] = ...,
+    nargs: Optional[int] = None,
+    metavar: Optional[str] = None,
     expose_value: bool = True,
     is_eager: bool = False,
-    envvar: Union[str, List[str]] = None
+    envvar: Optional[Union[str, List[str]]] = None
 ) -> _Decorator:
     ...
 
 
 # Defaults copied from the decorator body.
 def version_option(
-    version: Union[str, Version] = None,
+    version: Optional[Union[str, Version]] = None,
     *param_decls: str,
     cls: type = Option,
     # Option
-    prog_name: str = None,
+    prog_name: Optional[str] = None,
     show_default: bool = False,
     prompt: bool = False,
     confirmation_prompt: bool = False,
     hide_input: bool = False,
     is_flag: bool = True,
-    flag_value: Any = None,
+    flag_value: Optional[Any] = None,
     multiple: bool = False,
     count: bool = False,
     allow_from_autoenv: bool = True,
-    type: Union[type, ParamType] = None,
+    type: Optional[Union[type, ParamType]] = None,
     help: str = 'Show the version and exit.',
     # Parameter
-    default: Any = None,
-    callback: Callable[[Context, Parameter, str], Any] = None,
-    nargs: int = None,
-    metavar: str = None,
+    default: Optional[Any] = None,
+    callback: Optional[_Callback] = ...,
+    nargs: Optional[int] = None,
+    metavar: Optional[str] = None,
     expose_value: bool = False,
     is_eager: bool = True,
-    envvar: Union[str, List[str]] = None
+    envvar: Optional[Union[str, List[str]]] = None
 ) -> _Decorator:
     ...
 
@@ -204,19 +210,19 @@ def help_option(
     confirmation_prompt: bool = False,
     hide_input: bool = False,
     is_flag: bool = True,
-    flag_value: Any = None,
+    flag_value: Optional[Any] = None,
     multiple: bool = False,
     count: bool = False,
     allow_from_autoenv: bool = True,
-    type: Union[type, ParamType] = None,
+    type: Optional[Union[type, ParamType]] = None,
     help: str = 'Show this message and exit.',
     # Parameter
-    default: Any = None,
-    callback: Callable[[Context, Parameter, str], Any] = None,
-    nargs: int = None,
-    metavar: str = None,
+    default: Optional[Any] = None,
+    callback: Optional[_Callback] = ...,
+    nargs: Optional[int] = None,
+    metavar: Optional[str] = None,
     expose_value: bool = False,
     is_eager: bool = True,
-    envvar: Union[str, List[str]] = None
+    envvar: Optional[Union[str, List[str]]] = None
 ) -> _Decorator:
     ...
diff --git a/typeshed/third_party/3.6/click/exceptions.pyi b/typeshed/third_party/2and3/click/exceptions.pyi
similarity index 58%
rename from typeshed/third_party/3.6/click/exceptions.pyi
rename to typeshed/third_party/2and3/click/exceptions.pyi
index 7d49ae6..3517624 100644
--- a/typeshed/third_party/3.6/click/exceptions.pyi
+++ b/typeshed/third_party/2and3/click/exceptions.pyi
@@ -20,10 +20,10 @@ class ClickException(Exception):
 class UsageError(ClickException):
     ctx: Optional[Context]
 
-    def __init__(self, message: str, ctx: Context = None) -> None:
+    def __init__(self, message: str, ctx: Optional[Context] = None) -> None:
         ...
 
-    def show(self, file: IO = None) -> None:
+    def show(self, file: Optional[IO] = None) -> None:
         ...
 
 
@@ -34,9 +34,9 @@ class BadParameter(UsageError):
     def __init__(
         self,
         message: str,
-        ctx: Context = None,
-        param: Parameter = None,
-        param_hint: str = None
+        ctx: Optional[Context] = None,
+        param: Optional[Parameter] = None,
+        param_hint: Optional[str] = None
     ) -> None:
         ...
 
@@ -46,11 +46,11 @@ class MissingParameter(BadParameter):
 
     def __init__(
         self,
-        message: str = None,
-        ctx: Context = None,
-        param: Parameter = None,
-        param_hint: str = None,
-        param_type: str = None
+        message: Optional[str] = None,
+        ctx: Optional[Context] = None,
+        param: Optional[Parameter] = None,
+        param_hint: Optional[str] = None,
+        param_type: Optional[str] = None
     ) -> None:
         ...
 
@@ -62,20 +62,20 @@ class NoSuchOption(UsageError):
     def __init__(
         self,
         option_name: str,
-        message: str = None,
-        possibilities: List[str] = None,
-        ctx: Context = None
+        message: Optional[str] = None,
+        possibilities: Optional[List[str]] = None,
+        ctx: Optional[Context] = None
     ) -> None:
         ...
 
 
 class BadOptionUsage(UsageError):
-    def __init__(self, message: str, ctx: Context = None) -> None:
+    def __init__(self, message: str, ctx: Optional[Context] = None) -> None:
         ...
 
 
 class BadArgumentUsage(UsageError):
-    def __init__(self, message: str, ctx: Context = None) -> None:
+    def __init__(self, message: str, ctx: Optional[Context] = None) -> None:
         ...
 
 
@@ -83,7 +83,7 @@ class FileError(ClickException):
     ui_filename: str
     filename: str
 
-    def __init__(self, filename: str, hint: str = None) -> None:
+    def __init__(self, filename: str, hint: Optional[str] = None) -> None:
         ...
 
 
diff --git a/typeshed/third_party/3.6/click/formatting.pyi b/typeshed/third_party/2and3/click/formatting.pyi
similarity index 95%
rename from typeshed/third_party/3.6/click/formatting.pyi
rename to typeshed/third_party/2and3/click/formatting.pyi
index 5ff1349..52b81ce 100644
--- a/typeshed/third_party/3.6/click/formatting.pyi
+++ b/typeshed/third_party/2and3/click/formatting.pyi
@@ -34,8 +34,8 @@ class HelpFormatter:
     def __init__(
         self,
         indent_increment: int = 2,
-        width: int = None,
-        max_width: int = None,
+        width: Optional[int] = None,
+        max_width: Optional[int] = None,
     ) -> None:
         ...
 
diff --git a/typeshed/third_party/3.6/click/globals.pyi b/typeshed/third_party/2and3/click/globals.pyi
similarity index 73%
rename from typeshed/third_party/3.6/click/globals.pyi
rename to typeshed/third_party/2and3/click/globals.pyi
index 934ca7d..b5a113e 100644
--- a/typeshed/third_party/3.6/click/globals.pyi
+++ b/typeshed/third_party/2and3/click/globals.pyi
@@ -13,5 +13,5 @@ def pop_context() -> None:
     ...
 
 
-def resolve_color_default(color: bool = None) -> Optional[bool]:
+def resolve_color_default(color: Optional[bool] = None) -> Optional[bool]:
     ...
diff --git a/typeshed/third_party/3.6/click/parser.pyi b/typeshed/third_party/2and3/click/parser.pyi
similarity index 78%
rename from typeshed/third_party/3.6/click/parser.pyi
rename to typeshed/third_party/2and3/click/parser.pyi
index 3919966..21833d6 100644
--- a/typeshed/third_party/3.6/click/parser.pyi
+++ b/typeshed/third_party/2and3/click/parser.pyi
@@ -37,10 +37,10 @@ class Option:
         self,
         opts: Iterable[str],
         dest: str,
-        action: str = None,
+        action: Optional[str] = None,
         nargs: int = 1,
-        const: Any = None,
-        obj: Any = None
+        const: Optional[Any] = None,
+        obj: Optional[Any] = None
     ) -> None:
         ...
 
@@ -53,7 +53,7 @@ class Argument:
     nargs: int
     obj: Any
 
-    def __init__(self, dest: str, nargs: int = 1, obj: Any = None) -> None:
+    def __init__(self, dest: str, nargs: int = 1, obj: Optional[Any] = None) -> None:
         ...
 
     def process(self, value: Any, state: 'ParsingState') -> None:
@@ -79,21 +79,21 @@ class OptionParser:
     _opt_prefixes: Set[str]
     _args: List[Argument]
 
-    def __init__(self, ctx: Context = None) -> None:
+    def __init__(self, ctx: Optional[Context] = None) -> None:
         ...
 
     def add_option(
         self,
         opts: Iterable[str],
         dest: str,
-        action: str = None,
+        action: Optional[str] = None,
         nargs: int = 1,
-        const: Any = None,
-        obj: Any = None
+        const: Optional[Any] = None,
+        obj: Optional[Any] = None
     ) -> None:
         ...
 
-    def add_argument(self, dest: str, nargs: int = 1, obj: Any = None) -> None:
+    def add_argument(self, dest: str, nargs: int = 1, obj: Optional[Any] = None) -> None:
         ...
 
     def parse_args(
diff --git a/typeshed/third_party/3.6/click/termui.pyi b/typeshed/third_party/2and3/click/termui.pyi
similarity index 60%
rename from typeshed/third_party/3.6/click/termui.pyi
rename to typeshed/third_party/2and3/click/termui.pyi
index 5e0d407..bffb3fa 100644
--- a/typeshed/third_party/3.6/click/termui.pyi
+++ b/typeshed/third_party/2and3/click/termui.pyi
@@ -20,18 +20,18 @@ def _build_prompt(
     text: str,
     suffix: str,
     show_default: bool = False,
-    default: str = None,
+    default: Optional[str] = None,
 ) -> str:
     ...
 
 
 def prompt(
     text: str,
-    default: str = None,
+    default: Optional[str] = None,
     hide_input: bool = False,
     confirmation_prompt: bool = False,
-    type: Any = None,
-    value_proc: Callable[[Optional[str]], Any] = None,
+    type: Optional[Any] = None,
+    value_proc: Optional[Callable[[Optional[str]], Any]] = None,
     prompt_suffix: str = ': ',
     show_default: bool = True,
     err: bool = False,
@@ -54,7 +54,7 @@ def get_terminal_size() -> Tuple[int, int]:
     ...
 
 
-def echo_via_pager(text: str, color: bool = None) -> None:
+def echo_via_pager(text: str, color: Optional[bool] = None) -> None:
     ...
 
 
@@ -64,19 +64,19 @@ _T = TypeVar('_T')
 @contextmanager
 def progressbar(
     iterable: Optional[Iterable[_T]] = None,
-    length: int = None,
-    label: str = None,
+    length: Optional[int] = None,
+    label: Optional[str] = None,
     show_eta: bool = True,
-    show_percent: bool = None,
+    show_percent: Optional[bool] = None,
     show_pos: bool = False,
-    item_show_func: Callable[[_T], str] = None,
+    item_show_func: Optional[Callable[[_T], str]] = None,
     fill_char: str = '#',
     empty_char: str = '-',
     bar_template: str = '%(label)s  [%(bar)s]  %(info)s',
     info_sep: str = '  ',
     width: int = 36,
-    file: IO = None,
-    color: bool = None,
+    file: Optional[IO] = None,
+    color: Optional[bool] = None,
 ) -> Generator[_T, None, None]:
     ...
 
@@ -87,13 +87,13 @@ def clear() -> None:
 
 def style(
     text: str,
-    fg: str = None,
-    bg: str = None,
-    bold: bool = None,
-    dim: bool = None,
-    underline: bool = None,
-    blink: bool = None,
-    reverse: bool = None,
+    fg: Optional[str] = None,
+    bg: Optional[str] = None,
+    bold: Optional[bool] = None,
+    dim: Optional[bool] = None,
+    underline: Optional[bool] = None,
+    blink: Optional[bool] = None,
+    reverse: Optional[bool] = None,
     reset: bool = True,
 ):
     ...
@@ -106,29 +106,29 @@ def unstyle(text: str) -> str:
 # Styling options copied from style() for nicer type checking.
 def secho(
     text: str,
-    file: IO = None,
+    file: Optional[IO] = None,
     nl: bool =True,
     err: bool = False,
-    color: bool = None,
-    fg: str = None,
-    bg: str = None,
-    bold: bool = None,
-    dim: bool = None,
-    underline: bool = None,
-    blink: bool = None,
-    reverse: bool = None,
+    color: Optional[bool] = None,
+    fg: Optional[str] = None,
+    bg: Optional[str] = None,
+    bold: Optional[bool] = None,
+    dim: Optional[bool] = None,
+    underline: Optional[bool] = None,
+    blink: Optional[bool] = None,
+    reverse: Optional[bool] = None,
     reset: bool = True,
 ):
     ...
 
 
 def edit(
-    text: str = None,
-    editor: str = None,
-    env: str = None,
+    text: Optional[str] = None,
+    editor: Optional[str] = None,
+    env: Optional[str] = None,
     require_save: bool = True,
     extension: str = '.txt',
-    filename: str = None,
+    filename: Optional[str] = None,
 ) -> str:
     ...
 
diff --git a/typeshed/third_party/3.6/click/types.pyi b/typeshed/third_party/2and3/click/types.pyi
similarity index 77%
rename from typeshed/third_party/3.6/click/types.pyi
rename to typeshed/third_party/2and3/click/types.pyi
index 16eab86..7b6431e 100644
--- a/typeshed/third_party/3.6/click/types.pyi
+++ b/typeshed/third_party/2and3/click/types.pyi
@@ -12,8 +12,8 @@ class ParamType:
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> Any:
         ...
 
@@ -34,7 +34,7 @@ class ParamType:
     def split_envvar_value(self, rv: str) -> List[str]:
         ...
 
-    def fail(self, message: str, param: Parameter = None, ctx: Context = None) -> None:
+    def fail(self, message: str, param: Optional[Parameter] = None, ctx: Optional[Context] = None) -> None:
         ...
 
 
@@ -42,8 +42,8 @@ class BoolParamType(ParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> bool:
         ...
 
@@ -70,8 +70,8 @@ class FloatParamType(ParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> float:
         ...
 
@@ -92,18 +92,18 @@ class File(ParamType):
     def __init__(
         self,
         mode: str = 'r',
-        encoding: str = None,
-        errors: str = None,
-        lazy: bool = None,
-        atomic: bool = None,
+        encoding: Optional[str] = None,
+        errors: Optional[str] = None,
+        lazy: Optional[bool] = None,
+        atomic: Optional[bool] = None,
     ) -> None:
         ...
 
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> IO:
         ...
 
@@ -132,8 +132,8 @@ class FuncParamType(ParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> _F:
         ...
 
@@ -150,8 +150,8 @@ class IntParamType(ParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> int:
         ...
 
@@ -166,7 +166,7 @@ class IntParamType(ParamType):
 
 class IntRange(IntParamType):
     def __init__(
-        self, min: int = None, max: int = None, clamp: bool = False
+        self, min: Optional[int] = None, max: Optional[int] = None, clamp: bool = False
     ) -> None:
         ...
 
@@ -184,7 +184,7 @@ class Path(ParamType):
         readable: bool = True,
         resolve_path: bool = False,
         allow_dash: bool = False,
-        path_type: _PathType = None,
+        path_type: Optional[_PathType] = None,
     ) -> None:
         ...
 
@@ -194,8 +194,8 @@ class Path(ParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> _PathType:
         ...
 
@@ -211,8 +211,8 @@ class StringParamType(ParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> str:
         ...
 
@@ -234,8 +234,8 @@ class Tuple(CompositeParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> Tuple:
         ...
 
@@ -256,8 +256,8 @@ class UUIDParameterType(ParamType):
     def __call__(
         self,
         value: Optional[str],
-        param: Parameter = None,
-        ctx: Context = None,
+        param: Optional[Parameter] = None,
+        ctx: Optional[Context] = None,
     ) -> uuid.UUID:
         ...
 
@@ -270,7 +270,7 @@ class UUIDParameterType(ParamType):
         ...
 
 
-def convert_type(ty: Any, default: Any = None) -> ParamType:
+def convert_type(ty: Any, default: Optional[Any] = None) -> ParamType:
     ...
 
 # parameter type shortcuts
diff --git a/typeshed/third_party/3.6/click/utils.pyi b/typeshed/third_party/2and3/click/utils.pyi
similarity index 87%
rename from typeshed/third_party/3.6/click/utils.pyi
rename to typeshed/third_party/2and3/click/utils.pyi
index 3658295..cce7f20 100644
--- a/typeshed/third_party/3.6/click/utils.pyi
+++ b/typeshed/third_party/2and3/click/utils.pyi
@@ -32,7 +32,7 @@ class LazyFile:
         self,
         filename: str,
         mode: str = 'r',
-        encoding: str = None,
+        encoding: Optional[str] = None,
         errors: str = 'strict',
         atomic: bool = False
     ) -> None:
@@ -74,11 +74,11 @@ class KeepOpenFile:
 
 
 def echo(
-    message: str = None,
-    file: IO = None,
+    message: Optional[str] = None,
+    file: Optional[IO] = None,
     nl: bool = True,
     err: bool = False,
-    color: bool = None,
+    color: Optional[bool] = None,
 ) -> None:
     ...
 
@@ -88,7 +88,7 @@ def get_binary_stream(name: str) -> IO[bytes]:
 
 
 def get_text_stream(
-    name: str, encoding: str = None, errors: str = 'strict'
+    name: str, encoding: Optional[str] = None, errors: str = 'strict'
 ) -> IO[str]:
     ...
 
@@ -96,7 +96,7 @@ def get_text_stream(
 def open_file(
     filename: str,
     mode: str = 'r',
-    encoding: str = None,
+    encoding: Optional[str] = None,
     errors: str = 'strict',
     lazy: bool = False,
     atomic: bool = False
diff --git a/typeshed/third_party/2and3/jinja2/__init__.pyi b/typeshed/third_party/2and3/jinja2/__init__.pyi
index e77f4fd..96a5249 100644
--- a/typeshed/third_party/2and3/jinja2/__init__.pyi
+++ b/typeshed/third_party/2and3/jinja2/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2 (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from jinja2.environment import Environment as Environment, Template as Template
 from jinja2.loaders import BaseLoader as BaseLoader, FileSystemLoader as FileSystemLoader, PackageLoader as PackageLoader, DictLoader as DictLoader, FunctionLoader as FunctionLoader, PrefixLoader as PrefixLoader, ChoiceLoader as ChoiceLoader, ModuleLoader as ModuleLoader
 from jinja2.bccache import BytecodeCache as BytecodeCache, FileSystemBytecodeCache as FileSystemBytecodeCache, MemcachedBytecodeCache as MemcachedBytecodeCache
diff --git a/typeshed/third_party/2and3/jinja2/_compat.pyi b/typeshed/third_party/2and3/jinja2/_compat.pyi
index 1c83f44..8628318 100644
--- a/typeshed/third_party/2and3/jinja2/_compat.pyi
+++ b/typeshed/third_party/2and3/jinja2/_compat.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2._compat (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 import sys
 
diff --git a/typeshed/third_party/2and3/jinja2/_stringdefs.pyi b/typeshed/third_party/2and3/jinja2/_stringdefs.pyi
index d09bdbc..26f798b 100644
--- a/typeshed/third_party/2and3/jinja2/_stringdefs.pyi
+++ b/typeshed/third_party/2and3/jinja2/_stringdefs.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2._stringdefs (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 Cc = ...  # type: str
diff --git a/typeshed/third_party/2and3/jinja2/bccache.pyi b/typeshed/third_party/2and3/jinja2/bccache.pyi
index ef03701..58a6ea3 100644
--- a/typeshed/third_party/2and3/jinja2/bccache.pyi
+++ b/typeshed/third_party/2and3/jinja2/bccache.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.bccache (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 marshal_dump = ...  # type: Any
diff --git a/typeshed/third_party/2and3/jinja2/compiler.pyi b/typeshed/third_party/2and3/jinja2/compiler.pyi
index 44e001c..09883e8 100644
--- a/typeshed/third_party/2and3/jinja2/compiler.pyi
+++ b/typeshed/third_party/2and3/jinja2/compiler.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.compiler (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from keyword import iskeyword as is_python_keyword
 from jinja2.visitor import NodeVisitor
diff --git a/typeshed/third_party/2and3/jinja2/constants.pyi b/typeshed/third_party/2and3/jinja2/constants.pyi
index ca47cb0..dfb7539 100644
--- a/typeshed/third_party/2and3/jinja2/constants.pyi
+++ b/typeshed/third_party/2and3/jinja2/constants.pyi
@@ -1,5 +1 @@
-# Stubs for jinja2.constants (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 LOREM_IPSUM_WORDS = ...  # type: str
diff --git a/typeshed/third_party/2and3/jinja2/debug.pyi b/typeshed/third_party/2and3/jinja2/debug.pyi
index 270acf5..db0af46 100644
--- a/typeshed/third_party/2and3/jinja2/debug.pyi
+++ b/typeshed/third_party/2and3/jinja2/debug.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.debug (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 tproxy = ...  # type: Any
diff --git a/typeshed/third_party/2and3/jinja2/defaults.pyi b/typeshed/third_party/2and3/jinja2/defaults.pyi
index 0788c7c..3f44006 100644
--- a/typeshed/third_party/2and3/jinja2/defaults.pyi
+++ b/typeshed/third_party/2and3/jinja2/defaults.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.defaults (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from jinja2.filters import FILTERS as DEFAULT_FILTERS
 from jinja2.tests import TESTS as DEFAULT_TESTS
diff --git a/typeshed/third_party/2and3/jinja2/environment.pyi b/typeshed/third_party/2and3/jinja2/environment.pyi
index b3ea1d7..5c58651 100644
--- a/typeshed/third_party/2and3/jinja2/environment.pyi
+++ b/typeshed/third_party/2and3/jinja2/environment.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.environment (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Type, Union
 
 from .bccache import BytecodeCache
diff --git a/typeshed/third_party/2and3/jinja2/exceptions.pyi b/typeshed/third_party/2and3/jinja2/exceptions.pyi
index 1008167..861e6bc 100644
--- a/typeshed/third_party/2and3/jinja2/exceptions.pyi
+++ b/typeshed/third_party/2and3/jinja2/exceptions.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.exceptions (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional, Text
 
 class TemplateError(Exception):
diff --git a/typeshed/third_party/2and3/jinja2/ext.pyi b/typeshed/third_party/2and3/jinja2/ext.pyi
index 5159242..4fa28c7 100644
--- a/typeshed/third_party/2and3/jinja2/ext.pyi
+++ b/typeshed/third_party/2and3/jinja2/ext.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.ext (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 GETTEXT_FUNCTIONS = ...  # type: Any
diff --git a/typeshed/third_party/2and3/jinja2/filters.pyi b/typeshed/third_party/2and3/jinja2/filters.pyi
index 7da165f..d77fc22 100644
--- a/typeshed/third_party/2and3/jinja2/filters.pyi
+++ b/typeshed/third_party/2and3/jinja2/filters.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.filters (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 def contextfilter(f): ...
diff --git a/typeshed/third_party/2and3/jinja2/lexer.pyi b/typeshed/third_party/2and3/jinja2/lexer.pyi
index b571a48..89bf20d 100644
--- a/typeshed/third_party/2and3/jinja2/lexer.pyi
+++ b/typeshed/third_party/2and3/jinja2/lexer.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.lexer (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 whitespace_re = ...  # type: Any
diff --git a/typeshed/third_party/2and3/jinja2/loaders.pyi b/typeshed/third_party/2and3/jinja2/loaders.pyi
index 7de950e..9c74ec2 100644
--- a/typeshed/third_party/2and3/jinja2/loaders.pyi
+++ b/typeshed/third_party/2and3/jinja2/loaders.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.loaders (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Callable, List, Optional, Text, Tuple
 from types import ModuleType
 
diff --git a/typeshed/third_party/2and3/jinja2/meta.pyi b/typeshed/third_party/2and3/jinja2/meta.pyi
index 998cc80..0e0b849 100644
--- a/typeshed/third_party/2and3/jinja2/meta.pyi
+++ b/typeshed/third_party/2and3/jinja2/meta.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.meta (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from jinja2.compiler import CodeGenerator
 
diff --git a/typeshed/third_party/2and3/jinja2/nodes.pyi b/typeshed/third_party/2and3/jinja2/nodes.pyi
index ce43bb3..bbc315b 100644
--- a/typeshed/third_party/2and3/jinja2/nodes.pyi
+++ b/typeshed/third_party/2and3/jinja2/nodes.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.nodes (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class Impossible(Exception): ...
diff --git a/typeshed/third_party/2and3/jinja2/optimizer.pyi b/typeshed/third_party/2and3/jinja2/optimizer.pyi
index 2c30671..dc23f72 100644
--- a/typeshed/third_party/2and3/jinja2/optimizer.pyi
+++ b/typeshed/third_party/2and3/jinja2/optimizer.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.optimizer (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from jinja2.visitor import NodeTransformer
 
diff --git a/typeshed/third_party/2and3/jinja2/parser.pyi b/typeshed/third_party/2and3/jinja2/parser.pyi
index 20d19fc..f698085 100644
--- a/typeshed/third_party/2and3/jinja2/parser.pyi
+++ b/typeshed/third_party/2and3/jinja2/parser.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.parser (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 class Parser:
diff --git a/typeshed/third_party/2and3/jinja2/runtime.pyi b/typeshed/third_party/2and3/jinja2/runtime.pyi
index cfef911..34d06f4 100644
--- a/typeshed/third_party/2and3/jinja2/runtime.pyi
+++ b/typeshed/third_party/2and3/jinja2/runtime.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.runtime (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Dict, Optional, Text, Union
 from jinja2.utils import Markup as Markup, escape as escape, missing as missing, concat as concat
 from jinja2.exceptions import TemplateRuntimeError as TemplateRuntimeError, TemplateNotFound as TemplateNotFound
diff --git a/typeshed/third_party/2and3/jinja2/sandbox.pyi b/typeshed/third_party/2and3/jinja2/sandbox.pyi
index f611420..3c8a188 100644
--- a/typeshed/third_party/2and3/jinja2/sandbox.pyi
+++ b/typeshed/third_party/2and3/jinja2/sandbox.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.sandbox (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from jinja2.environment import Environment
 
diff --git a/typeshed/third_party/2and3/jinja2/tests.pyi b/typeshed/third_party/2and3/jinja2/tests.pyi
index fb31db7..db67c25 100644
--- a/typeshed/third_party/2and3/jinja2/tests.pyi
+++ b/typeshed/third_party/2and3/jinja2/tests.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.tests (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 number_re = ...  # type: Any
diff --git a/typeshed/third_party/2and3/jinja2/utils.pyi b/typeshed/third_party/2and3/jinja2/utils.pyi
index 1368299..7a0f1a9 100644
--- a/typeshed/third_party/2and3/jinja2/utils.pyi
+++ b/typeshed/third_party/2and3/jinja2/utils.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.utils (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 
 from markupsafe import Markup, escape, soft_unicode
diff --git a/typeshed/third_party/2and3/jinja2/visitor.pyi b/typeshed/third_party/2and3/jinja2/visitor.pyi
index 201750c..ef34328 100644
--- a/typeshed/third_party/2and3/jinja2/visitor.pyi
+++ b/typeshed/third_party/2and3/jinja2/visitor.pyi
@@ -1,7 +1,3 @@
-# Stubs for jinja2.visitor (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 class NodeVisitor:
     def get_visitor(self, node): ...
     def visit(self, node, *args, **kwargs): ...
diff --git a/typeshed/third_party/2and3/markupsafe/__init__.pyi b/typeshed/third_party/2and3/markupsafe/__init__.pyi
index 723d329..7961654 100644
--- a/typeshed/third_party/2and3/markupsafe/__init__.pyi
+++ b/typeshed/third_party/2and3/markupsafe/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for markupsafe (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 import sys
 
 from typing import Any, Callable, Dict, Iterable, List, Optional, Text, Tuple, Union
@@ -20,8 +16,8 @@ class Markup(text_type):
     def __rmul__(self, num: int) -> Markup: ...
     def __mod__(self, *args: Any) -> Markup: ...
     def join(self, seq: Iterable[text_type]): ...
-    def split(self, sep: text_type = None, maxsplit: int = -1) -> List[text_type]: ...
-    def rsplit(self, sep: text_type = None, maxsplit: int = -1) -> List[text_type]: ...
+    def split(self, sep: Optional[text_type] = None, maxsplit: int = -1) -> List[text_type]: ...
+    def rsplit(self, sep: Optional[text_type] = None, maxsplit: int = -1) -> List[text_type]: ...
     def splitlines(self, keepends: bool = ...) -> List[text_type]: ...
     def unescape(self) -> Text: ...
     def striptags(self) -> Text: ...
@@ -41,9 +37,9 @@ class Markup(text_type):
     def replace(self, old: text_type, new: text_type, count: int = -1) -> Markup: ...
     def ljust(self, width: int, fillchar: text_type = ...) -> Markup: ...
     def rjust(self, width: int, fillchar: text_type = ...) -> Markup: ...
-    def lstrip(self, chars: text_type = None) -> Markup: ...
-    def rstrip(self, chars: text_type = None) -> Markup: ...
-    def strip(self, chars: text_type = None) -> Markup: ...
+    def lstrip(self, chars: Optional[text_type] = None) -> Markup: ...
+    def rstrip(self, chars: Optional[text_type] = None) -> Markup: ...
+    def strip(self, chars: Optional[text_type] = None) -> Markup: ...
     def center(self, width: int, fillchar: text_type = ...) -> Markup: ...
     def zfill(self, width: int) -> Markup: ...
     def translate(self, table: Union[Dict[int, Any], text_type]) -> Markup: ...
diff --git a/typeshed/third_party/2and3/markupsafe/_compat.pyi b/typeshed/third_party/2and3/markupsafe/_compat.pyi
index 72b6f60..bb9a860 100644
--- a/typeshed/third_party/2and3/markupsafe/_compat.pyi
+++ b/typeshed/third_party/2and3/markupsafe/_compat.pyi
@@ -1,7 +1,3 @@
-# Stubs for markupsafe._compat (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 import sys
 
 from typing import Any, Iterator, Mapping, Text, Tuple, TypeVar
diff --git a/typeshed/third_party/2and3/markupsafe/_constants.pyi b/typeshed/third_party/2and3/markupsafe/_constants.pyi
index 677b46c..65ace32 100644
--- a/typeshed/third_party/2and3/markupsafe/_constants.pyi
+++ b/typeshed/third_party/2and3/markupsafe/_constants.pyi
@@ -1,7 +1,3 @@
-# Stubs for markupsafe._constants (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Dict, Text
 
 HTML_ENTITIES = ...  # type: Dict[Text, int]
diff --git a/typeshed/third_party/2and3/markupsafe/_native.pyi b/typeshed/third_party/2and3/markupsafe/_native.pyi
index 13d6fec..ecf20c6 100644
--- a/typeshed/third_party/2and3/markupsafe/_native.pyi
+++ b/typeshed/third_party/2and3/markupsafe/_native.pyi
@@ -1,7 +1,3 @@
-# Stubs for markupsafe._native (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from . import Markup
 from ._compat import text_type, string_types
 from typing import Union, Text
diff --git a/typeshed/third_party/2and3/markupsafe/_speedups.pyi b/typeshed/third_party/2and3/markupsafe/_speedups.pyi
index 379e11e..ecf20c6 100644
--- a/typeshed/third_party/2and3/markupsafe/_speedups.pyi
+++ b/typeshed/third_party/2and3/markupsafe/_speedups.pyi
@@ -1,7 +1,3 @@
-# Stubs for markupsafe._speedups (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from . import Markup
 from ._compat import text_type, string_types
 from typing import Union, Text
diff --git a/typeshed/third_party/2and3/mypy_extensions.pyi b/typeshed/third_party/2and3/mypy_extensions.pyi
index 9810914..2c4be00 100644
--- a/typeshed/third_party/2and3/mypy_extensions.pyi
+++ b/typeshed/third_party/2and3/mypy_extensions.pyi
@@ -2,7 +2,7 @@ from typing import Dict, Type, TypeVar, Optional, Union
 
 _T = TypeVar('_T')
 
-def TypedDict(typename: str, fields: Dict[str, Type[_T]]) -> Type[dict]: ...
+def TypedDict(typename: str, fields: Dict[str, Type[_T]], total: bool = ...) -> Type[dict]: ...
 
 def Arg(type: _T = ..., name: Optional[str] = ...) -> _T: ...
 def DefaultArg(type: _T = ..., name: Optional[str] = ...) -> _T: ...
diff --git a/typeshed/third_party/2and3/pymysql/__init__.pyi b/typeshed/third_party/2and3/pymysql/__init__.pyi
index d1161e8..dd58ff9 100644
--- a/typeshed/third_party/2and3/pymysql/__init__.pyi
+++ b/typeshed/third_party/2and3/pymysql/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Union, Tuple, Callable
 from .connections import Connection
 from .constants import FIELD_TYPE as FIELD_TYPE
diff --git a/typeshed/third_party/2and3/pymysql/charset.pyi b/typeshed/third_party/2and3/pymysql/charset.pyi
index 4fc0df5..916e6a3 100644
--- a/typeshed/third_party/2and3/pymysql/charset.pyi
+++ b/typeshed/third_party/2and3/pymysql/charset.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.charset (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 MBLENGTH = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/connections.pyi b/typeshed/third_party/2and3/pymysql/connections.pyi
index 2eff7be..62109ba 100644
--- a/typeshed/third_party/2and3/pymysql/connections.pyi
+++ b/typeshed/third_party/2and3/pymysql/connections.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.connections (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional, Type
 from .charset import MBLENGTH as MBLENGTH, charset_by_name as charset_by_name, charset_by_id as charset_by_id
 from .cursors import Cursor as Cursor
diff --git a/typeshed/third_party/2and3/pymysql/constants/CLIENT.pyi b/typeshed/third_party/2and3/pymysql/constants/CLIENT.pyi
index 30d9dfc..cdb11b3 100644
--- a/typeshed/third_party/2and3/pymysql/constants/CLIENT.pyi
+++ b/typeshed/third_party/2and3/pymysql/constants/CLIENT.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.constants.CLIENT (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 LONG_PASSWORD = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/constants/COMMAND.pyi b/typeshed/third_party/2and3/pymysql/constants/COMMAND.pyi
index 4ec68d5..0cfa0c2 100644
--- a/typeshed/third_party/2and3/pymysql/constants/COMMAND.pyi
+++ b/typeshed/third_party/2and3/pymysql/constants/COMMAND.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.constants.COMMAND (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 COM_SLEEP = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/constants/ER.pyi b/typeshed/third_party/2and3/pymysql/constants/ER.pyi
index 0ab17b2..811f6a2 100644
--- a/typeshed/third_party/2and3/pymysql/constants/ER.pyi
+++ b/typeshed/third_party/2and3/pymysql/constants/ER.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.constants.ER (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 ERROR_FIRST = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/constants/FIELD_TYPE.pyi b/typeshed/third_party/2and3/pymysql/constants/FIELD_TYPE.pyi
index e9987b2..e05bd6c 100644
--- a/typeshed/third_party/2and3/pymysql/constants/FIELD_TYPE.pyi
+++ b/typeshed/third_party/2and3/pymysql/constants/FIELD_TYPE.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.constants.FIELD_TYPE (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 DECIMAL = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/constants/FLAG.pyi b/typeshed/third_party/2and3/pymysql/constants/FLAG.pyi
index 792df90..869a987 100644
--- a/typeshed/third_party/2and3/pymysql/constants/FLAG.pyi
+++ b/typeshed/third_party/2and3/pymysql/constants/FLAG.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.constants.FLAG (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 NOT_NULL = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/constants/SERVER_STATUS.pyi b/typeshed/third_party/2and3/pymysql/constants/SERVER_STATUS.pyi
index 6e4db8d..ae81f04 100644
--- a/typeshed/third_party/2and3/pymysql/constants/SERVER_STATUS.pyi
+++ b/typeshed/third_party/2and3/pymysql/constants/SERVER_STATUS.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.constants.SERVER_STATUS (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 SERVER_STATUS_IN_TRANS = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/constants/__init__.pyi b/typeshed/third_party/2and3/pymysql/constants/__init__.pyi
index 19336fe..e69de29 100644
--- a/typeshed/third_party/2and3/pymysql/constants/__init__.pyi
+++ b/typeshed/third_party/2and3/pymysql/constants/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for pymysql.constants (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/2and3/pymysql/converters.pyi b/typeshed/third_party/2and3/pymysql/converters.pyi
index d9c8d29..94ba99a 100644
--- a/typeshed/third_party/2and3/pymysql/converters.pyi
+++ b/typeshed/third_party/2and3/pymysql/converters.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.converters (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from .constants import FIELD_TYPE as FIELD_TYPE, FLAG as FLAG
 from .charset import charset_by_id as charset_by_id
diff --git a/typeshed/third_party/2and3/pymysql/cursors.pyi b/typeshed/third_party/2and3/pymysql/cursors.pyi
index a06ac23..357f205 100644
--- a/typeshed/third_party/2and3/pymysql/cursors.pyi
+++ b/typeshed/third_party/2and3/pymysql/cursors.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.cursors (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Union, Tuple, Any, Dict, Optional, Text
 from .connections import Connection
 
@@ -26,7 +22,7 @@ class Cursor:
     def executemany(self, query: str, args) -> int: ...
     def callproc(self, procname, args=...): ...
     def fetchone(self) -> Optional[Gen]: ...
-    def fetchmany(self, size: int = None) -> Optional[Gen]: ...
+    def fetchmany(self, size: Optional[int] = None) -> Optional[Gen]: ...
     def fetchall(self) -> Optional[Tuple[Gen, ...]]: ...
     def scroll(self, value, mode=''): ...
     def __iter__(self): ...
diff --git a/typeshed/third_party/2and3/pymysql/err.pyi b/typeshed/third_party/2and3/pymysql/err.pyi
index 81f8803..c0320a6 100644
--- a/typeshed/third_party/2and3/pymysql/err.pyi
+++ b/typeshed/third_party/2and3/pymysql/err.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.err (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Dict
 from .constants import ER as ER
 
diff --git a/typeshed/third_party/2and3/pymysql/times.pyi b/typeshed/third_party/2and3/pymysql/times.pyi
index e96c990..4cc207a 100644
--- a/typeshed/third_party/2and3/pymysql/times.pyi
+++ b/typeshed/third_party/2and3/pymysql/times.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.times (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 Date = ...  # type: Any
diff --git a/typeshed/third_party/2and3/pymysql/util.pyi b/typeshed/third_party/2and3/pymysql/util.pyi
index 2c2f7c0..3d9a65b 100644
--- a/typeshed/third_party/2and3/pymysql/util.pyi
+++ b/typeshed/third_party/2and3/pymysql/util.pyi
@@ -1,7 +1,3 @@
-# Stubs for pymysql.util (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 def byte2int(b): ...
 def int2byte(i): ...
 def join_bytes(bs): ...
diff --git a/typeshed/third_party/2and3/pynamodb/__init__.pyi b/typeshed/third_party/2and3/pynamodb/__init__.pyi
new file mode 100644
index 0000000..83e691d
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/__init__.pyi
@@ -0,0 +1 @@
+__license__: str
diff --git a/typeshed/third_party/2and3/pynamodb/attributes.pyi b/typeshed/third_party/2and3/pynamodb/attributes.pyi
new file mode 100644
index 0000000..1b2c2d8
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/attributes.pyi
@@ -0,0 +1,84 @@
+from typing import Any, Callable, Dict, Generic, Iterable, List, Mapping, Optional, Text, Type, TypeVar, Union, Set
+
+from datetime import datetime
+
+_T = TypeVar('_T')
+_KT = TypeVar('_KT')
+_VT = TypeVar('_VT')
+_MT = TypeVar('_MT', bound='MapAttribute')
+Number = Union[int, float]
+
+class Attribute(Generic[_T]):
+    attr_name: Optional[Text]
+    attr_type: Text
+    null: bool
+    default: Any
+    is_hash_key: bool
+    is_range_key: bool
+    def __init__(self, hash_key: bool = ..., range_key: bool = ..., null: Optional[bool] = ..., default: Optional[Union[_T, Callable[..., _T]]] = ..., attr_name: Optional[Text] = ...) -> None: ...
+    def __set__(self, instance: Any, value: Optional[_T]) -> None: ...
+    def serialize(self, value: Any) -> Any: ...
+    def deserialize(self, value: Any) -> Any: ...
+    def get_value(self, value: Any) -> Any: ...
+
+class SetMixin(object):
+    def serialize(self, value): ...
+    def deserialize(self, value): ...
+
+class BinaryAttribute(Attribute[bytes]):
+    def __get__(self, instance: Any, owner: Any) -> bytes: ...
+
+class BinarySetAttribute(SetMixin, Attribute[Set[bytes]]):
+    def __get__(self, instance: Any, owner: Any) -> Set[bytes]: ...
+
+class UnicodeSetAttribute(SetMixin, Attribute[Set[Text]]):
+    def element_serialize(self, value: Any) -> Any: ...
+    def element_deserialize(self, value: Any) -> Any: ...
+    def __get__(self, instance: Any, owner: Any) -> Set[Text]: ...
+
+class UnicodeAttribute(Attribute[Text]):
+    def __get__(self, instance: Any, owner: Any) -> Text: ...
+
+class JSONAttribute(Attribute[Dict[Text, Any]]):
+    def __get__(self, instance: Any, owner: Any) -> Dict[Text, Any]: ...
+
+class LegacyBooleanAttribute(Attribute[bool]):
+    def __get__(self, instance: Any, owner: Any) -> bool: ...
+
+class BooleanAttribute(Attribute[bool]):
+    def __get__(self, instance: Any, owner: Any) -> bool: ...
+
+class NumberSetAttribute(SetMixin, Attribute[Set[Number]]):
+    def __get__(self, instance: Any, owner: Any) -> Set[Number]: ...
+
+class NumberAttribute(Attribute[Number]):
+    def __get__(self, instance: Any, owner: Any) -> Number: ...
+
+class UTCDateTimeAttribute(Attribute[datetime]):
+    def __get__(self, instance: Any, owner: Any) -> datetime: ...
+
+class NullAttribute(Attribute[None]):
+    def __get__(self, instance: Any, owner: Any) -> None: ...
+
+class MapAttributeMeta(type):
+    def __init__(cls, name, bases, attrs) -> None: ...
+
+class MapAttribute(Generic[_KT, _VT], Attribute[Mapping[_KT, _VT]], metaclass=MapAttributeMeta):
+    attribute_values: Any
+    def __init__(self, hash_key: bool = ..., range_key: bool = ..., null: Optional[bool] = ..., default: Optional[Union[Any, Callable[..., Any]]] = ..., attr_name: Optional[Text] = ..., **attrs) -> None: ...
+    def __iter__(self) -> Iterable[_VT]: ...
+    def __getattr__(self, attr: str) -> _VT: ...
+    def __getitem__(self, item: _KT) -> _VT: ...
+    def __set__(self, instance: Any, value: Union[None, MapAttribute[_KT, _VT], Mapping[_KT, _VT]]) -> None: ...
+    def __get__(self: _MT, instance: Any, owner: Any) -> _MT: ...
+    def is_type_safe(self, key: Any, value: Any) -> bool: ...
+    def validate(self) -> bool: ...
+
+class ListAttribute(Generic[_T], Attribute[List[_T]]):
+    element_type: Any
+    def __init__(self, hash_key: bool = ..., range_key: bool = ..., null: Optional[bool] = ..., default: Optional[Union[Any, Callable[..., Any]]] = ..., attr_name: Optional[Text] = ..., of: Optional[Type[_T]] = ...) -> None: ...
+    def __get__(self, instance: Any, owner: Any) -> List[_T]: ...
+
+DESERIALIZE_CLASS_MAP: Dict[Text, Attribute]
+SERIALIZE_CLASS_MAP: Dict[Type, Attribute]
+SERIALIZE_KEY_MAP: Dict[Type, Text]
diff --git a/typeshed/third_party/2and3/pynamodb/connection/__init__.pyi b/typeshed/third_party/2and3/pynamodb/connection/__init__.pyi
new file mode 100644
index 0000000..8ecfdaf
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/connection/__init__.pyi
@@ -0,0 +1,2 @@
+from pynamodb.connection.base import Connection
+from pynamodb.connection.table import TableConnection
diff --git a/typeshed/third_party/2and3/pynamodb/connection/base.pyi b/typeshed/third_party/2and3/pynamodb/connection/base.pyi
new file mode 100644
index 0000000..b0f023c
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/connection/base.pyi
@@ -0,0 +1,55 @@
+from typing import Any, Dict, Optional, Text
+
+BOTOCORE_EXCEPTIONS: Any
+log: Any
+
+class MetaTable:
+    data: Dict
+    def __init__(self, data: Dict) -> None: ...
+    @property
+    def range_keyname(self) -> Optional[Text]: ...
+    @property
+    def hash_keyname(self) -> Text: ...
+    def get_index_hash_keyname(self, index_name: Text) -> Optional[Text]: ...
+    def get_item_attribute_map(self, attributes, item_key: Any = ..., pythonic_key: bool = ...): ...
+    def get_attribute_type(self, attribute_name, value: Optional[Any] = ...): ...
+    def get_identifier_map(self, hash_key, range_key: Optional[Any] = ..., key: Any = ...): ...
+    def get_exclusive_start_key_map(self, exclusive_start_key): ...
+
+class Connection:
+    host: Any
+    region: Any
+    session_cls: Any
+    def __init__(self, region: Optional[Any] = ..., host: Optional[Any] = ..., session_cls: Optional[Any] = ..., request_timeout_seconds: Optional[Any] = ..., max_retry_attempts: Optional[Any] = ..., base_backoff_ms: Optional[Any] = ...) -> None: ...
+    def dispatch(self, operation_name, operation_kwargs): ...
+    @property
+    def session(self): ...
+    @property
+    def requests_session(self): ...
+    @property
+    def client(self): ...
+    def get_meta_table(self, table_name: Text, refresh: bool = ...): ...
+    def create_table(self, table_name: Text, attribute_definitions: Optional[Any] = ..., key_schema: Optional[Any] = ..., read_capacity_units: Optional[Any] = ..., write_capacity_units: Optional[Any] = ..., global_secondary_indexes: Optional[Any] = ..., local_secondary_indexes: Optional[Any] = ..., stream_specification: Optional[Any] = ...): ...
+    def delete_table(self, table_name: Text): ...
+    def update_table(self, table_name: Text, read_capacity_units: Optional[Any] = ..., write_capacity_units: Optional[Any] = ..., global_secondary_index_updates: Optional[Any] = ...): ...
+    def list_tables(self, exclusive_start_table_name: Optional[Any] = ..., limit: Optional[Any] = ...): ...
+    def describe_table(self, table_name: Text): ...
+    def get_conditional_operator(self, operator): ...
+    def get_item_attribute_map(self, table_name: Text, attributes, item_key: Any = ..., pythonic_key: bool = ...): ...
+    def get_expected_map(self, table_name: Text, expected): ...
+    def parse_attribute(self, attribute, return_type: bool = ...): ...
+    def get_attribute_type(self, table_name: Text, attribute_name, value: Optional[Any] = ...): ...
+    def get_identifier_map(self, table_name: Text, hash_key, range_key: Optional[Any] = ..., key: Any = ...): ...
+    def get_query_filter_map(self, table_name: Text, query_filters): ...
+    def get_consumed_capacity_map(self, return_consumed_capacity): ...
+    def get_return_values_map(self, return_values): ...
+    def get_item_collection_map(self, return_item_collection_metrics): ...
+    def get_exclusive_start_key_map(self, table_name: Text, exclusive_start_key): ...
+    def delete_item(self, table_name: Text, hash_key, range_key: Optional[Any] = ..., expected: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., return_values: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ...): ...
+    def update_item(self, table_name: Text, hash_key, range_key: Optional[Any] = ..., attribute_updates: Optional[Any] = ..., expected: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ..., return_values: Optional[Any] = ...): ...
+    def put_item(self, table_name: Text, hash_key, range_key: Optional[Any] = ..., attributes: Optional[Any] = ..., expected: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., return_values: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ...): ...
+    def batch_write_item(self, table_name: Text, put_items: Optional[Any] = ..., delete_items: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ...): ...
+    def batch_get_item(self, table_name: Text, keys, consistent_read: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., attributes_to_get: Optional[Any] = ...): ...
+    def get_item(self, table_name: Text, hash_key, range_key: Optional[Any] = ..., consistent_read: bool = ..., attributes_to_get: Optional[Any] = ...): ...
+    def scan(self, table_name: Text, attributes_to_get: Optional[Any] = ..., limit: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., scan_filter: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., exclusive_start_key: Optional[Any] = ..., segment: Optional[Any] = ..., total_segments: Optional[Any] = ...): ...
+    def query(self, table_name: Text, hash_key, attributes_to_get: Optional[Any] = ..., consistent_read: bool = ..., exclusive_start_key: Optional[Any] = ..., index_name: Optional[Any] = ..., key_conditions: Optional[Any] = ..., query_filters: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., limit: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., scan_index_forward: Optional[Any] = ..., select: Optional[Any] = ...): ...
diff --git a/typeshed/third_party/2and3/pynamodb/connection/table.pyi b/typeshed/third_party/2and3/pynamodb/connection/table.pyi
new file mode 100644
index 0000000..0f820af
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/connection/table.pyi
@@ -0,0 +1,18 @@
+from typing import Any, Optional
+
+class TableConnection:
+    table_name: Any
+    connection: Any
+    def __init__(self, table_name, region: Optional[Any] = ..., host: Optional[Any] = ..., session_cls: Optional[Any] = ..., request_timeout_seconds: Optional[Any] = ..., max_retry_attempts: Optional[Any] = ..., base_backoff_ms: Optional[Any] = ...) -> None: ...
+    def delete_item(self, hash_key, range_key: Optional[Any] = ..., expected: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., return_values: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ...): ...
+    def update_item(self, hash_key, range_key: Optional[Any] = ..., attribute_updates: Optional[Any] = ..., expected: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ..., return_values: Optional[Any] = ...): ...
+    def put_item(self, hash_key, range_key: Optional[Any] = ..., attributes: Optional[Any] = ..., expected: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., return_values: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ...): ...
+    def batch_write_item(self, put_items: Optional[Any] = ..., delete_items: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., return_item_collection_metrics: Optional[Any] = ...): ...
+    def batch_get_item(self, keys, consistent_read: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., attributes_to_get: Optional[Any] = ...): ...
+    def get_item(self, hash_key, range_key: Optional[Any] = ..., consistent_read: bool = ..., attributes_to_get: Optional[Any] = ...): ...
+    def scan(self, attributes_to_get: Optional[Any] = ..., limit: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., scan_filter: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., segment: Optional[Any] = ..., total_segments: Optional[Any] = ..., exclusive_start_key: Optional[Any] = ...): ...
+    def query(self, hash_key, attributes_to_get: Optional[Any] = ..., consistent_read: bool = ..., exclusive_start_key: Optional[Any] = ..., index_name: Optional[Any] = ..., key_conditions: Optional[Any] = ..., query_filters: Optional[Any] = ..., limit: Optional[Any] = ..., return_consumed_capacity: Optional[Any] = ..., scan_index_forward: Optional[Any] = ..., conditional_operator: Optional[Any] = ..., select: Optional[Any] = ...): ...
+    def describe_table(self): ...
+    def delete_table(self): ...
+    def update_table(self, read_capacity_units: Optional[Any] = ..., write_capacity_units: Optional[Any] = ..., global_secondary_index_updates: Optional[Any] = ...): ...
+    def create_table(self, attribute_definitions: Optional[Any] = ..., key_schema: Optional[Any] = ..., read_capacity_units: Optional[Any] = ..., write_capacity_units: Optional[Any] = ..., global_secondary_indexes: Optional[Any] = ..., local_secondary_indexes: Optional[Any] = ..., stream_specification: Optional[Any] = ...): ...
diff --git a/typeshed/third_party/2and3/pynamodb/connection/util.pyi b/typeshed/third_party/2and3/pynamodb/connection/util.pyi
new file mode 100644
index 0000000..20635c6
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/connection/util.pyi
@@ -0,0 +1,3 @@
+from typing import Text
+
+def pythonic(var_name: Text) -> Text: ...
diff --git a/typeshed/third_party/2and3/pynamodb/constants.pyi b/typeshed/third_party/2and3/pynamodb/constants.pyi
new file mode 100644
index 0000000..7c26cd6
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/constants.pyi
@@ -0,0 +1,166 @@
+from typing import Any
+
+BATCH_WRITE_ITEM: str
+DESCRIBE_TABLE: str
+BATCH_GET_ITEM: str
+CREATE_TABLE: str
+UPDATE_TABLE: str
+DELETE_TABLE: str
+LIST_TABLES: str
+UPDATE_ITEM: str
+DELETE_ITEM: str
+GET_ITEM: str
+PUT_ITEM: str
+QUERY: str
+SCAN: str
+GLOBAL_SECONDARY_INDEX_UPDATES: str
+RETURN_ITEM_COLL_METRICS: str
+EXCLUSIVE_START_TABLE_NAME: str
+RETURN_CONSUMED_CAPACITY: str
+COMPARISON_OPERATOR: str
+SCAN_INDEX_FORWARD: str
+ATTR_DEFINITIONS: str
+ATTR_VALUE_LIST: str
+TABLE_DESCRIPTION: str
+UNPROCESSED_KEYS: str
+UNPROCESSED_ITEMS: str
+CONSISTENT_READ: str
+DELETE_REQUEST: str
+RETURN_VALUES: str
+REQUEST_ITEMS: str
+ATTRS_TO_GET: str
+ATTR_UPDATES: str
+TABLE_STATUS: str
+SCAN_FILTER: str
+TABLE_NAME: str
+KEY_SCHEMA: str
+ATTR_NAME: str
+ATTR_TYPE: str
+ITEM_COUNT: str
+CAMEL_COUNT: str
+PUT_REQUEST: str
+INDEX_NAME: str
+ATTRIBUTES: str
+TABLE_KEY: str
+RESPONSES: str
+RANGE_KEY: str
+KEY_TYPE: str
+ACTION: str
+UPDATE: str
+EXISTS: str
+SELECT: str
+ACTIVE: str
+LIMIT: str
+ITEMS: str
+ITEM: str
+KEYS: str
+UTC: str
+KEY: str
+DEFAULT_ENCODING: str
+DEFAULT_REGION: str
+DATETIME_FORMAT: str
+SERVICE_NAME: str
+HTTP_OK: int
+HTTP_BAD_REQUEST: int
+PROVISIONED_THROUGHPUT: str
+READ_CAPACITY_UNITS: str
+WRITE_CAPACITY_UNITS: str
+STRING_SHORT: str
+STRING_SET_SHORT: str
+NUMBER_SHORT: str
+NUMBER_SET_SHORT: str
+BINARY_SHORT: str
+BINARY_SET_SHORT: str
+MAP_SHORT: str
+LIST_SHORT: str
+BOOLEAN: str
+BOOLEAN_SHORT: str
+STRING: str
+STRING_SET: str
+NUMBER: str
+NUMBER_SET: str
+BINARY: str
+BINARY_SET: str
+MAP: str
+LIST: str
+SHORT_ATTR_TYPES: Any
+ATTR_TYPE_MAP: Any
+LOCAL_SECONDARY_INDEX: str
+LOCAL_SECONDARY_INDEXES: str
+GLOBAL_SECONDARY_INDEX: str
+GLOBAL_SECONDARY_INDEXES: str
+PROJECTION: str
+PROJECTION_TYPE: str
+NON_KEY_ATTRIBUTES: str
+KEYS_ONLY: str
+ALL: str
+INCLUDE: str
+STREAM_VIEW_TYPE: str
+STREAM_SPECIFICATION: str
+STREAM_ENABLED: str
+STREAM_NEW_IMAGE: str
+STREAM_OLD_IMAGE: str
+STREAM_NEW_AND_OLD_IMAGE: str
+STREAM_KEYS_ONLY: str
+EXCLUSIVE_START_KEY: str
+LAST_EVALUATED_KEY: str
+QUERY_FILTER: str
+BEGINS_WITH: str
+BETWEEN: str
+EQ: str
+NE: str
+LE: str
+LT: str
+GE: str
+GT: str
+IN: str
+KEY_CONDITIONS: str
+COMPARISON_OPERATOR_VALUES: Any
+QUERY_OPERATOR_MAP: Any
+NOT_NULL: str
+NULL: str
+CONTAINS: str
+NOT_CONTAINS: str
+ALL_ATTRIBUTES: str
+ALL_PROJECTED_ATTRIBUTES: str
+SPECIFIC_ATTRIBUTES: str
+COUNT: str
+SELECT_VALUES: Any
+SCAN_OPERATOR_MAP: Any
+QUERY_FILTER_OPERATOR_MAP: Any
+DELETE_FILTER_OPERATOR_MAP: Any
+UPDATE_FILTER_OPERATOR_MAP: Any
+PUT_FILTER_OPERATOR_MAP: Any
+SEGMENT: str
+TOTAL_SEGMENTS: str
+SCAN_FILTER_VALUES: Any
+QUERY_FILTER_VALUES: Any
+DELETE_FILTER_VALUES: Any
+VALUE: str
+EXPECTED: str
+CONSUMED_CAPACITY: str
+CAPACITY_UNITS: str
+INDEXES: str
+TOTAL: str
+NONE: str
+RETURN_CONSUMED_CAPACITY_VALUES: Any
+SIZE: str
+RETURN_ITEM_COLL_METRICS_VALUES: Any
+ALL_OLD: str
+UPDATED_OLD: str
+ALL_NEW: str
+UPDATED_NEW: str
+RETURN_VALUES_VALUES: Any
+PUT: str
+DELETE: str
+ADD: str
+ATTR_UPDATE_ACTIONS: Any
+BATCH_GET_PAGE_LIMIT: int
+BATCH_WRITE_PAGE_LIMIT: int
+META_CLASS_NAME: str
+REGION: str
+HOST: str
+CONDITIONAL_OPERATOR: str
+AND: str
+OR: str
+CONDITIONAL_OPERATORS: Any
diff --git a/typeshed/third_party/2and3/pynamodb/exceptions.pyi b/typeshed/third_party/2and3/pynamodb/exceptions.pyi
new file mode 100644
index 0000000..cfd17ac
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/exceptions.pyi
@@ -0,0 +1,40 @@
+from typing import Any, Optional, Text
+
+class PynamoDBException(Exception):
+    msg: str
+    cause: Any
+    def __init__(self, msg: Optional[Text] = ..., cause: Optional[Exception] = ...) -> None: ...
+
+class PynamoDBConnectionError(PynamoDBException):
+    pass
+
+class DeleteError(PynamoDBConnectionError):
+    pass
+
+class QueryError(PynamoDBConnectionError):
+    pass
+
+class ScanError(PynamoDBConnectionError):
+    pass
+
+class PutError(PynamoDBConnectionError):
+    pass
+
+class UpdateError(PynamoDBConnectionError):
+    pass
+
+class GetError(PynamoDBConnectionError):
+    pass
+
+class TableError(PynamoDBConnectionError):
+    pass
+
+class DoesNotExist(PynamoDBException):
+    pass
+
+class TableDoesNotExist(PynamoDBException):
+    def __init__(self, table_name) -> None: ...
+
+class VerboseClientError(Exception):
+    MSG_TEMPLATE: Any
+    def __init__(self, error_response, operation_name, verbose_properties: Optional[Any] = ...) -> None: ...
diff --git a/typeshed/third_party/2and3/pynamodb/indexes.pyi b/typeshed/third_party/2and3/pynamodb/indexes.pyi
new file mode 100644
index 0000000..35506d0
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/indexes.pyi
@@ -0,0 +1,30 @@
+from typing import Any, Optional
+
+class IndexMeta(type):
+    def __init__(cls, name, bases, attrs) -> None: ...
+
+class Index(metaclass=IndexMeta):
+    Meta: Any
+    def __init__(self) -> None: ...
+    @classmethod
+    def count(cls, hash_key, consistent_read: bool = ..., **filters) -> int: ...
+    @classmethod
+    def query(self, hash_key, scan_index_forward: Optional[Any] = ..., consistent_read: bool = ..., limit: Optional[Any] = ..., last_evaluated_key: Optional[Any] = ..., attributes_to_get: Optional[Any] = ..., **filters): ...
+
+class GlobalSecondaryIndex(Index): ...
+class LocalSecondaryIndex(Index): ...
+
+class Projection(object):
+    projection_type: Any
+    non_key_attributes: Any
+
+class KeysOnlyProjection(Projection):
+    projection_type: Any
+
+class IncludeProjection(Projection):
+    projection_type: Any
+    non_key_attributes: Any
+    def __init__(self, non_attr_keys: Optional[Any] = ...) -> None: ...
+
+class AllProjection(Projection):
+    projection_type: Any
diff --git a/typeshed/third_party/2and3/pynamodb/models.pyi b/typeshed/third_party/2and3/pynamodb/models.pyi
new file mode 100644
index 0000000..56010a1
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/models.pyi
@@ -0,0 +1,85 @@
+from .exceptions import DoesNotExist
+from typing import Any, Dict, Generic, Iterable, Iterator, List, Optional, Sequence, Tuple, Type, TypeVar, Text, Union
+
+log: Any
+
+class DefaultMeta: ...
+
+class ResultSet(Iterable):
+    results: Any
+    operation: Any
+    arguments: Any
+    def __init__(self, results, operation, arguments) -> None: ...
+    def __iter__(self): ...
+
+class MetaModel(type):
+    def __init__(self, name: Text, bases: Tuple[type, ...], attrs: Dict[Any, Any]) -> None: ...
+
+_T = TypeVar('_T', bound='Model')
+KeyType = Union[Text, bytes, float, int, Tuple]
+
+class Model(metaclass=MetaModel):
+    DoesNotExist = DoesNotExist
+    attribute_values: Dict[Text, Any]
+    def __init__(self, hash_key: Optional[KeyType] = ..., range_key: Optional[Any] = ..., **attrs) -> None: ...
+    @classmethod
+    def has_map_or_list_attributes(cls: Type[_T]) -> bool: ...
+    @classmethod
+    def batch_get(cls: Type[_T], items: Iterable[Union[KeyType, Iterable[KeyType]]], consistent_read: Optional[bool] = ..., attributes_to_get: Optional[Sequence[Text]] = ...) -> Iterator[_T]: ...
+    @classmethod
+    def batch_write(cls: Type[_T], auto_commit: bool = ...) -> BatchWrite[_T]: ...
+    def delete(self, conditional_operator: Optional[Text] = ..., **expected_values) -> Any: ...
+    def update(self, attributes: Dict[Text, Dict[Text, Any]], conditional_operator: Optional[Text] = ..., **expected_values) -> Any: ...
+    def update_item(self, attribute: Text, value: Optional[Any] = ..., action: Optional[Text] = ..., conditional_operator: Optional[Text] = ..., **expected_values): ...
+    def save(self, conditional_operator: Optional[Text] = ..., **expected_values) -> Dict[str, Any]: ...
+    def refresh(self, consistent_read: bool = ...): ...
+    @classmethod
+    def get(cls: Type[_T], hash_key: KeyType, range_key: Optional[KeyType] = ..., consistent_read: bool = ...) -> _T: ...
+    @classmethod
+    def from_raw_data(cls: Type[_T], data) -> _T: ...
+    @classmethod
+    def count(cls: Type[_T], hash_key: Optional[KeyType] = ..., consistent_read: bool = ..., index_name: Optional[Text] = ..., limit: Optional[int] = ..., **filters) -> int: ...
+    @classmethod
+    def query(cls: Type[_T], hash_key: KeyType, consistent_read: bool = ..., index_name: Optional[Text] = ..., scan_index_forward: Optional[Any] = ..., conditional_operator: Optional[Text] = ..., limit: Optional[int] = ..., last_evaluated_key: Optional[Any] = ..., attributes_to_get: Optional[Iterable[Text]] = ..., page_size: Optional[int] = ..., **filters) -> Iterator[_T]: ...
+    @classmethod
+    def rate_limited_scan(cls: Type[_T], attributes_to_get: Optional[Sequence[Text]], segment: Optional[int] = ..., total_segments: Optional[int] = ..., limit: Optional[int] = ..., conditional_operator: Optional[Text] = ..., last_evaluated_key: Optional[Any] = ..., page_size: Optional[int] = ..., timeout_seconds: Optional[int] = ..., read_capacity_to_consume_per_second: int = ..., max_sleep_between_retry: int = ..., max_consecutive_exceptions: int = ..., **filters: Any): ...
+    @classmethod
+    def scan(cls: Type[_T], segment: Optional[int] = ..., total_segments: Optional[int] = ..., limit: Optional[int] = ..., conditional_operator: Optional[Text] = ..., last_evaluated_key: Optional[Any] = ..., page_size: Optional[int] = ..., **filters) -> Iterator[_T]: ...
+    @classmethod
+    def exists(cls: Type[_T]) -> bool: ...
+    @classmethod
+    def delete_table(cls): ...
+    @classmethod
+    def describe_table(cls): ...
+    @classmethod
+    def create_table(cls: Type[_T], wait: bool = ..., read_capacity_units: Optional[Any] = ..., write_capacity_units: Optional[Any] = ...): ...
+    @classmethod
+    def dumps(cls): ...
+    @classmethod
+    def dump(cls, filename): ...
+    @classmethod
+    def loads(cls, data): ...
+    @classmethod
+    def load(cls, filename): ...
+    @classmethod
+    def add_throttle_record(cls, records): ...
+    @classmethod
+    def get_throttle(cls): ...
+    @classmethod
+    def _get_attributes(cls) -> Dict[str, Any]: ...
+
+class ModelContextManager(Generic[_T]):
+    model: Type[_T]
+    auto_commit: bool
+    max_operations: int
+    pending_operations: List[Dict[Text, Any]]
+    def __init__(self, model: Type[_T], auto_commit: bool = ...) -> None: ...
+    def __enter__(self) -> ModelContextManager[_T]: ...
+
+class BatchWrite(Generic[_T], ModelContextManager[_T]):
+    def save(self, put_item: _T) -> None: ...
+    def delete(self, del_item: _T) -> None: ...
+    def __enter__(self) -> BatchWrite[_T]: ...
+    def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...
+    pending_operations: Any
+    def commit(self) -> None: ...
diff --git a/typeshed/third_party/2and3/pynamodb/settings.pyi b/typeshed/third_party/2and3/pynamodb/settings.pyi
new file mode 100644
index 0000000..76fc417
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/settings.pyi
@@ -0,0 +1,8 @@
+from typing import Any
+
+log: Any
+default_settings_dict: Any
+OVERRIDE_SETTINGS_PATH: Any
+override_settings: Any
+
+def get_settings_value(key): ...
diff --git a/typeshed/third_party/2and3/pynamodb/throttle.pyi b/typeshed/third_party/2and3/pynamodb/throttle.pyi
new file mode 100644
index 0000000..6948b68
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/throttle.pyi
@@ -0,0 +1,19 @@
+from typing import Any, Optional
+
+log: Any
+
+class ThrottleBase:
+    capacity: Any
+    window: Any
+    records: Any
+    sleep_interval: Any
+    def __init__(self, capacity, window: int = ..., initial_sleep: Optional[Any] = ...) -> None: ...
+    def add_record(self, record): ...
+    def throttle(self): ...
+
+class NoThrottle(ThrottleBase):
+    def __init__(self) -> None: ...
+    def add_record(self, record): ...
+
+class Throttle(ThrottleBase):
+    def throttle(self): ...
diff --git a/typeshed/third_party/2and3/pynamodb/types.pyi b/typeshed/third_party/2and3/pynamodb/types.pyi
new file mode 100644
index 0000000..14195f0
--- /dev/null
+++ b/typeshed/third_party/2and3/pynamodb/types.pyi
@@ -0,0 +1,5 @@
+STRING: str
+NUMBER: str
+BINARY: str
+HASH: str
+RANGE: str
diff --git a/typeshed/third_party/2and3/pytz/__init__.pyi b/typeshed/third_party/2and3/pytz/__init__.pyi
index 2c2accd..e47caea 100644
--- a/typeshed/third_party/2and3/pytz/__init__.pyi
+++ b/typeshed/third_party/2and3/pytz/__init__.pyi
@@ -14,9 +14,9 @@ country_names = ...  # type: Dict
 class _UTCclass(datetime.tzinfo):
     zone = ...  # type: str
     def fromutc(self, dt: datetime.datetime) -> datetime.datetime: ...
-    def utcoffset(self, dt: Optional[datetime.datetime]) -> datetime.timedelta: ...  # type: ignore
+    def utcoffset(self, dt: Optional[datetime.datetime]) -> datetime.timedelta: ...
     def tzname(self, dt: Optional[datetime.datetime]) -> str: ...
-    def dst(self, dt: Optional[datetime.datetime]) -> datetime.timedelta: ...  # type: ignore
+    def dst(self, dt: Optional[datetime.datetime]) -> datetime.timedelta: ...
     def localize(self, dt: datetime.datetime, is_dst: bool = ...) -> datetime.datetime: ...
     def normalize(self, dt: datetime.datetime, is_dst: bool = ...) -> datetime.datetime: ...
 
diff --git a/typeshed/third_party/2and3/requests/api.pyi b/typeshed/third_party/2and3/requests/api.pyi
index 85afdc5..865b481 100644
--- a/typeshed/third_party/2and3/requests/api.pyi
+++ b/typeshed/third_party/2and3/requests/api.pyi
@@ -20,7 +20,7 @@ def get(url: Union[Text, bytes],
         **kwargs) -> Response: ...
 def options(url: Union[str, Text], **kwargs) -> Response: ...
 def head(url: Union[str, Text], **kwargs) -> Response: ...
-def post(url: Union[str, Text], data: _Data = ..., json: Optional[MutableMapping] = ..., **kwargs) -> Response: ...
-def put(url: Union[str, Text], data: _Data = ..., **kwargs) -> Response: ...
-def patch(url: Union[str, Text], data: _Data = ..., **kwargs) -> Response: ...
+def post(url: Union[str, Text], data: _Data=..., json=..., **kwargs) -> Response: ...
+def put(url: Union[str, Text], data: _Data=..., json=..., **kwargs) -> Response: ...
+def patch(url: Union[str, Text], data: _Data=..., json=..., **kwargs) -> Response: ...
 def delete(url: Union[str, Text], **kwargs) -> Response: ...
diff --git a/typeshed/third_party/2and3/requests/packages/__init__.pyi b/typeshed/third_party/2and3/requests/packages/__init__.pyi
index 2b1bff8..b50dba3 100644
--- a/typeshed/third_party/2and3/requests/packages/__init__.pyi
+++ b/typeshed/third_party/2and3/requests/packages/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 class VendorAlias:
     def __init__(self, package_names) -> None: ...
     def find_module(self, fullname, path=...): ...
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/__init__.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/__init__.pyi
index 61a1c5f..1857527 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/__init__.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3 (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from . import connectionpool
 from . import filepost
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/_collections.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/_collections.pyi
index 58aa944..25d3f4d 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/_collections.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/_collections.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3._collections (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from collections import MutableMapping
 
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/connectionpool.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/connectionpool.pyi
index 778bb7c..c88ef2e 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/connectionpool.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/connectionpool.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.connectionpool (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from . import exceptions
 from .packages import ssl_match_hostname
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/contrib/__init__.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/contrib/__init__.pyi
index 69e47f7..e69de29 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/contrib/__init__.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/contrib/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for requests.packages.urllib3.contrib (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/exceptions.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/exceptions.pyi
index 3e7d0f6..8789e2e 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/exceptions.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/exceptions.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.exceptions (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class HTTPError(Exception): ...
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/filepost.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/filepost.pyi
index f1ce517..2fab416 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/filepost.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/filepost.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.filepost (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from . import packages
 # from .packages import six
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/packages/__init__.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/packages/__init__.pyi
index 67507f9..e69de29 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/packages/__init__.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/packages/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for requests.packages.urllib3.packages (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyi
index 9efeac0..1915c0e 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.packages.ssl_match_hostname (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 import ssl
 
 CertificateError = ssl.CertificateError
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyi
index 5abbc9d..c219980 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.packages.ssl_match_hostname._implementation (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 class CertificateError(ValueError): ...
 
 def match_hostname(cert, hostname): ...
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/poolmanager.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/poolmanager.pyi
index a65f664..21dbb4f 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/poolmanager.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/poolmanager.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.poolmanager (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from .request import RequestMethods
 
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/request.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/request.pyi
index 788c759..a644c4e 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/request.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/request.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.request (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class RequestMethods:
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/response.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/response.pyi
index b6f418a..aca9507 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/response.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/response.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.response (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, IO
 from . import _collections
 from . import exceptions
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/__init__.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/__init__.pyi
index e4a0e13..53bdac9 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/__init__.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.util (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from . import connection
 from . import request
 from . import response
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/connection.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/connection.pyi
index cd67309..5068a22 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/connection.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/connection.pyi
@@ -1,11 +1,8 @@
-# Stubs for requests.packages.urllib3.util.connection (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 poll = ...  # type: Any
 select = ...  # type: Any
+HAS_IPV6 = ...  # type: bool
 
 def is_connection_dropped(conn): ...
 def create_connection(address, timeout=..., source_address=..., socket_options=...): ...
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/request.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/request.pyi
index 0be64df..0aeb5a8 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/request.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/request.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.util.request (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 # from ..packages import six
 
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/response.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/response.pyi
index 761a006..30463da 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/response.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/response.pyi
@@ -1,5 +1 @@
-# Stubs for requests.packages.urllib3.util.response (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 def is_fp_closed(obj): ...
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/retry.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/retry.pyi
index e958d90..e0793f8 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/retry.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/retry.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.util.retry (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from .. import exceptions
 from .. import packages
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/ssl_.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/ssl_.pyi
index c7db0ac..3d75f71 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/ssl_.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/ssl_.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.util.ssl_ (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from .. import exceptions
 import ssl
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/timeout.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/timeout.pyi
index 0a7653c..760060d 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/timeout.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/timeout.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.util.timeout (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from .. import exceptions
 
diff --git a/typeshed/third_party/2and3/requests/packages/urllib3/util/url.pyi b/typeshed/third_party/2and3/requests/packages/urllib3/util/url.pyi
index 9877b4a..08f307a 100644
--- a/typeshed/third_party/2and3/requests/packages/urllib3/util/url.pyi
+++ b/typeshed/third_party/2and3/requests/packages/urllib3/util/url.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.packages.urllib3.util.url (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from .. import exceptions
 
diff --git a/typeshed/third_party/2and3/requests/status_codes.pyi b/typeshed/third_party/2and3/requests/status_codes.pyi
index e3035eb..02d5c62 100644
--- a/typeshed/third_party/2and3/requests/status_codes.pyi
+++ b/typeshed/third_party/2and3/requests/status_codes.pyi
@@ -1,7 +1,3 @@
-# Stubs for requests.status_codes (Python 3)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from .structures import LookupDict
 
diff --git a/typeshed/third_party/2and3/ujson.pyi b/typeshed/third_party/2and3/ujson.pyi
index a982c8b..4c8540d 100644
--- a/typeshed/third_party/2and3/ujson.pyi
+++ b/typeshed/third_party/2and3/ujson.pyi
@@ -7,7 +7,7 @@ __version__ = ...  # type: str
 def encode(
     obj: Any,
     ensure_ascii: bool = ...,
-    double_precision: bool = ...,
+    double_precision: int = ...,
     encode_html_chars: bool = ...,
     escape_forward_slashes: bool = ...,
     sort_keys: bool = ...,
@@ -17,7 +17,7 @@ def encode(
 def dumps(
     obj: Any,
     ensure_ascii: bool = ...,
-    double_precision: bool = ...,
+    double_precision: int = ...,
     encode_html_chars: bool = ...,
     escape_forward_slashes: bool = ...,
     sort_keys: bool = ...,
@@ -28,7 +28,7 @@ def dump(
     obj: Any,
     fp: IO[str],
     ensure_ascii: bool = ...,
-    double_precision: bool = ...,
+    double_precision: int = ...,
     encode_html_chars: bool = ...,
     escape_forward_slashes: bool = ...,
     sort_keys: bool = ...,
diff --git a/typeshed/third_party/2and3/yaml/__init__.pyi b/typeshed/third_party/2and3/yaml/__init__.pyi
index d209770..8f2edec 100644
--- a/typeshed/third_party/2and3/yaml/__init__.pyi
+++ b/typeshed/third_party/2and3/yaml/__init__.pyi
@@ -1,14 +1,10 @@
-# Stubs for yaml (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
-# from yaml.error import *
-# from yaml.tokens import *
-# from yaml.events import *
-# from yaml.nodes import *
-# from yaml.loader import *
-# from yaml.dumper import *
+from yaml.error import *  # noqa: F403
+from yaml.tokens import *  # noqa: F403
+from yaml.events import *  # noqa: F403
+from yaml.nodes import *  # noqa: F403
+from yaml.loader import *  # noqa: F403
+from yaml.dumper import *  # noqa: F403
 # TODO: stubs for cyaml?
 # from cyaml import *
 
diff --git a/typeshed/third_party/2and3/yaml/composer.pyi b/typeshed/third_party/2and3/yaml/composer.pyi
index f5f7e61..20719e0 100644
--- a/typeshed/third_party/2and3/yaml/composer.pyi
+++ b/typeshed/third_party/2and3/yaml/composer.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.composer (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import Mark, YAMLError, MarkedYAMLError
 from yaml.nodes import Node, ScalarNode, CollectionNode, SequenceNode, MappingNode
diff --git a/typeshed/third_party/2and3/yaml/constructor.pyi b/typeshed/third_party/2and3/yaml/constructor.pyi
index 36b7124..40e9ea2 100644
--- a/typeshed/third_party/2and3/yaml/constructor.pyi
+++ b/typeshed/third_party/2and3/yaml/constructor.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.constructor (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from yaml.error import Mark, YAMLError, MarkedYAMLError
 from yaml.nodes import Node, ScalarNode, CollectionNode, SequenceNode, MappingNode
 
@@ -26,7 +22,9 @@ class BaseConstructor:
     def construct_sequence(self, node, deep=...): ...
     def construct_mapping(self, node, deep=...): ...
     def construct_pairs(self, node, deep=...): ...
+    @classmethod
     def add_constructor(cls, tag, constructor): ...
+    @classmethod
     def add_multi_constructor(cls, tag_prefix, multi_constructor): ...
 
 class SafeConstructor(BaseConstructor):
diff --git a/typeshed/third_party/2and3/yaml/dumper.pyi b/typeshed/third_party/2and3/yaml/dumper.pyi
index 85b75fb..0586f13 100644
--- a/typeshed/third_party/2and3/yaml/dumper.pyi
+++ b/typeshed/third_party/2and3/yaml/dumper.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.dumper (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from yaml.emitter import Emitter
 from yaml.serializer import Serializer
 from yaml.representer import BaseRepresenter, Representer, SafeRepresenter
diff --git a/typeshed/third_party/2and3/yaml/emitter.pyi b/typeshed/third_party/2and3/yaml/emitter.pyi
index 99e72ac..a090c6d 100644
--- a/typeshed/third_party/2and3/yaml/emitter.pyi
+++ b/typeshed/third_party/2and3/yaml/emitter.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.emitter (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import YAMLError
 
diff --git a/typeshed/third_party/2and3/yaml/error.pyi b/typeshed/third_party/2and3/yaml/error.pyi
index 247e25d..4e799df 100644
--- a/typeshed/third_party/2and3/yaml/error.pyi
+++ b/typeshed/third_party/2and3/yaml/error.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.error (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class Mark:
diff --git a/typeshed/third_party/2and3/yaml/events.pyi b/typeshed/third_party/2and3/yaml/events.pyi
index ff5f12b..4c055c7 100644
--- a/typeshed/third_party/2and3/yaml/events.pyi
+++ b/typeshed/third_party/2and3/yaml/events.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.events (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class Event:
diff --git a/typeshed/third_party/2and3/yaml/loader.pyi b/typeshed/third_party/2and3/yaml/loader.pyi
index 6d3b4c1..0e9afea 100644
--- a/typeshed/third_party/2and3/yaml/loader.pyi
+++ b/typeshed/third_party/2and3/yaml/loader.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.loader (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from yaml.reader import Reader
 from yaml.scanner import Scanner
 from yaml.parser import Parser
diff --git a/typeshed/third_party/2and3/yaml/nodes.pyi b/typeshed/third_party/2and3/yaml/nodes.pyi
index a4039cd..6e3836e 100644
--- a/typeshed/third_party/2and3/yaml/nodes.pyi
+++ b/typeshed/third_party/2and3/yaml/nodes.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.nodes (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class Node:
diff --git a/typeshed/third_party/2and3/yaml/parser.pyi b/typeshed/third_party/2and3/yaml/parser.pyi
index ed47b39..094a4ea 100644
--- a/typeshed/third_party/2and3/yaml/parser.pyi
+++ b/typeshed/third_party/2and3/yaml/parser.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.parser (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import MarkedYAMLError
 
diff --git a/typeshed/third_party/2and3/yaml/reader.pyi b/typeshed/third_party/2and3/yaml/reader.pyi
index 20bbc8f..9b08631 100644
--- a/typeshed/third_party/2and3/yaml/reader.pyi
+++ b/typeshed/third_party/2and3/yaml/reader.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.reader (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import YAMLError
 
diff --git a/typeshed/third_party/2and3/yaml/representer.pyi b/typeshed/third_party/2and3/yaml/representer.pyi
index b2a3c50..b10f36d 100644
--- a/typeshed/third_party/2and3/yaml/representer.pyi
+++ b/typeshed/third_party/2and3/yaml/representer.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.representer (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import YAMLError
 
@@ -19,7 +15,9 @@ class BaseRepresenter:
     def represent(self, data): ...
     def get_classobj_bases(self, cls): ...
     def represent_data(self, data): ...
+    @classmethod
     def add_representer(cls, data_type, representer): ...
+    @classmethod
     def add_multi_representer(cls, data_type, representer): ...
     def represent_scalar(self, tag, value, style=...): ...
     def represent_sequence(self, tag, sequence, flow_style=...): ...
diff --git a/typeshed/third_party/2and3/yaml/resolver.pyi b/typeshed/third_party/2and3/yaml/resolver.pyi
index 0920e7c..0b5641e 100644
--- a/typeshed/third_party/2and3/yaml/resolver.pyi
+++ b/typeshed/third_party/2and3/yaml/resolver.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.resolver (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import YAMLError
 
@@ -16,7 +12,9 @@ class BaseResolver:
     resolver_exact_paths = ...  # type: Any
     resolver_prefix_paths = ...  # type: Any
     def __init__(self) -> None: ...
+    @classmethod
     def add_implicit_resolver(cls, tag, regexp, first): ...
+    @classmethod
     def add_path_resolver(cls, tag, path, kind=...): ...
     def descend_resolver(self, current_node, current_index): ...
     def ascend_resolver(self): ...
diff --git a/typeshed/third_party/2and3/yaml/scanner.pyi b/typeshed/third_party/2and3/yaml/scanner.pyi
index b4058ef..81acb58 100644
--- a/typeshed/third_party/2and3/yaml/scanner.pyi
+++ b/typeshed/third_party/2and3/yaml/scanner.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.scanner (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import MarkedYAMLError
 
diff --git a/typeshed/third_party/2and3/yaml/serializer.pyi b/typeshed/third_party/2and3/yaml/serializer.pyi
index c502056..c6cdb49 100644
--- a/typeshed/third_party/2and3/yaml/serializer.pyi
+++ b/typeshed/third_party/2and3/yaml/serializer.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.serializer (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from yaml.error import YAMLError
 
diff --git a/typeshed/third_party/2and3/yaml/tokens.pyi b/typeshed/third_party/2and3/yaml/tokens.pyi
index 0d659f7..a25cbe5 100644
--- a/typeshed/third_party/2and3/yaml/tokens.pyi
+++ b/typeshed/third_party/2and3/yaml/tokens.pyi
@@ -1,7 +1,3 @@
-# Stubs for yaml.tokens (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class Token:
diff --git a/typeshed/third_party/3/dateutil/tz/__init__.pyi b/typeshed/third_party/3/dateutil/tz/__init__.pyi
index 30a7ab3..4c8a6d2 100644
--- a/typeshed/third_party/3/dateutil/tz/__init__.pyi
+++ b/typeshed/third_party/3/dateutil/tz/__init__.pyi
@@ -1,5 +1 @@
-# Stubs for dateutil.tz (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from .tz import tzutc, tzoffset, tzlocal, tzfile, tzrange, tzstr, tzical, gettz, datetime_exists, datetime_ambiguous
diff --git a/typeshed/third_party/3/dateutil/tz/_common.pyi b/typeshed/third_party/3/dateutil/tz/_common.pyi
index a190c54..383218d 100644
--- a/typeshed/third_party/3/dateutil/tz/_common.pyi
+++ b/typeshed/third_party/3/dateutil/tz/_common.pyi
@@ -1,7 +1,3 @@
-# Stubs for dateutil.tz._common (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional
 from datetime import datetime, tzinfo, timedelta
 
diff --git a/typeshed/third_party/3/dateutil/tz/tz.pyi b/typeshed/third_party/3/dateutil/tz/tz.pyi
index 8564270..e693db3 100644
--- a/typeshed/third_party/3/dateutil/tz/tz.pyi
+++ b/typeshed/third_party/3/dateutil/tz/tz.pyi
@@ -1,7 +1,3 @@
-# Stubs for dateutil.tz.tz (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any, Optional, Union, IO, Tuple, List
 import datetime
 from ._common import tzname_in_python2 as tzname_in_python2, _tzinfo as _tzinfo
diff --git a/typeshed/third_party/3/enum.pyi b/typeshed/third_party/3/enum.pyi
index a7e0fd6..dbb9df3 100644
--- a/typeshed/third_party/3/enum.pyi
+++ b/typeshed/third_party/3/enum.pyi
@@ -5,7 +5,7 @@ _T = TypeVar('_T', bound=Enum)
 _S = TypeVar('_S', bound=Type[Enum])
 
 class EnumMeta(type, Iterable[Enum], Sized, Reversible[Enum], Container[Enum]):
-    def __iter__(self: Type[_T]) -> Iterator[_T]: ...  # type: ignore
+    def __iter__(self: Type[_T]) -> Iterator[_T]: ...
     def __reversed__(self: Type[_T]) -> Iterator[_T]: ...
     def __contains__(self, member: Any) -> bool: ...
     def __getitem__(self: Type[_T], name: str) -> _T: ...
@@ -32,7 +32,8 @@ def unique(enumeration: _S) -> _S: ...
 if sys.version_info >= (3, 6):
     _auto_null = ...  # type: Any
 
-    class auto:
+    # subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto()
+    class auto(IntFlag):
         value = ...  # type: Any
 
     class Flag(Enum):
@@ -45,11 +46,12 @@ if sys.version_info >= (3, 6):
         def __xor__(self: _T, other: _T) -> _T: ...
         def __invert__(self: _T) -> _T: ...
 
-    # All `type: ignore` comments below due to IntFlag making the function signatures more permissive.
+    # The `type: ignore` comment is needed because mypy considers the type
+    # signatures of several methods defined in int and Flag to be incompatible.
     class IntFlag(int, Flag):  # type: ignore
-        def __or__(self: _T, other: Union[int, _T]) -> _T: ...  # type: ignore
-        def __and__(self: _T, other: Union[int, _T]) -> _T: ...  # type: ignore
-        def __xor__(self: _T, other: Union[int, _T]) -> _T: ...  # type: ignore
+        def __or__(self: _T, other: Union[int, _T]) -> _T: ...
+        def __and__(self: _T, other: Union[int, _T]) -> _T: ...
+        def __xor__(self: _T, other: Union[int, _T]) -> _T: ...
         __ror__ = __or__
         __rand__ = __and__
         __rxor__ = __xor__
diff --git a/typeshed/third_party/3/itsdangerous.pyi b/typeshed/third_party/3/itsdangerous.pyi
index 2305bb4..4ed0402 100644
--- a/typeshed/third_party/3/itsdangerous.pyi
+++ b/typeshed/third_party/3/itsdangerous.pyi
@@ -1,7 +1,3 @@
-# Stubs for itsdangerous (Python 3)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from datetime import datetime
 from typing import Any, Callable, IO, MutableMapping, Optional, Text, Tuple, TypeVar, Union
 
diff --git a/typeshed/third_party/3/jwt/__init__.pyi b/typeshed/third_party/3/jwt/__init__.pyi
new file mode 100644
index 0000000..3161c91
--- /dev/null
+++ b/typeshed/third_party/3/jwt/__init__.pyi
@@ -0,0 +1,41 @@
+from typing import Mapping, Any, Optional, Union
+
+from . import algorithms
+
+def decode(jwt: Union[str, bytes], key: Union[str, bytes] = ...,
+           verify: bool = ..., algorithms: Optional[Any] = ...,
+           options: Optional[Mapping[Any, Any]] = ...,
+           **kwargs: Any) -> Mapping[str, Any]: ...
+
+def encode(payload: Mapping[str, Any], key: Union[str, bytes],
+           algorithm: str = ..., headers: Optional[Mapping[str, Any]] = ...,
+           json_encoder: Optional[Any] = ...) -> bytes: ...
+
+def register_algorithm(alg_id: str,
+                       alg_obj: algorithms.Algorithm) -> None: ...
+
+def unregister_algorithm(alg_id: str) -> None: ...
+
+class InvalidTokenError(Exception): pass
+class DecodeError(InvalidTokenError): pass
+class ExpiredSignatureError(InvalidTokenError): pass
+class InvalidAudienceError(InvalidTokenError): pass
+class InvalidIssuerError(InvalidTokenError): pass
+class InvalidIssuedAtError(InvalidTokenError): pass
+class ImmatureSignatureError(InvalidTokenError): pass
+class InvalidKeyError(Exception): pass
+class InvalidAlgorithmError(InvalidTokenError): pass
+class MissingRequiredClaimError(InvalidTokenError): ...
+
+# Compatibility aliases (deprecated)
+ExpiredSignature = ExpiredSignatureError
+InvalidAudience = InvalidAudienceError
+InvalidIssuer = InvalidIssuerError
+
+# These aren't actually documented, but the package
+# exports them in __init__.py, so we should at least
+# make sure that mypy doesn't raise spurious errors
+# if they're used.
+get_unverified_header = ...  # type: Any
+PyJWT = ...  # type: Any
+PyJWS = ...  # type: Any
diff --git a/typeshed/third_party/3/jwt/algorithms.pyi b/typeshed/third_party/3/jwt/algorithms.pyi
new file mode 100644
index 0000000..4576b41
--- /dev/null
+++ b/typeshed/third_party/3/jwt/algorithms.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+class Algorithm(Any): ...  # type: ignore
diff --git a/typeshed/third_party/3/jwt/contrib/__init__.pyi b/typeshed/third_party/3/jwt/contrib/__init__.pyi
new file mode 100644
index 0000000..e69de29
diff --git a/typeshed/third_party/3/jwt/contrib/algorithms/__init__.pyi b/typeshed/third_party/3/jwt/contrib/algorithms/__init__.pyi
new file mode 100644
index 0000000..b2bb1f6
--- /dev/null
+++ b/typeshed/third_party/3/jwt/contrib/algorithms/__init__.pyi
@@ -0,0 +1 @@
+from hashlib import _Hash as _HashAlg
diff --git a/typeshed/third_party/3/jwt/contrib/algorithms/py_ecdsa.pyi b/typeshed/third_party/3/jwt/contrib/algorithms/py_ecdsa.pyi
new file mode 100644
index 0000000..cd2926f
--- /dev/null
+++ b/typeshed/third_party/3/jwt/contrib/algorithms/py_ecdsa.pyi
@@ -0,0 +1,10 @@
+from typing import Any
+from jwt.algorithms import Algorithm
+
+from . import _HashAlg
+
+class ECAlgorithm(Algorithm):
+    SHA256 = ...  # type: _HashAlg
+    SHA384 = ...  # type: _HashAlg
+    SHA512 = ...  # type: _HashAlg
+    def __init__(self, hash_alg: _HashAlg) -> None: ...
diff --git a/typeshed/third_party/3/jwt/contrib/algorithms/pycrypto.pyi b/typeshed/third_party/3/jwt/contrib/algorithms/pycrypto.pyi
new file mode 100644
index 0000000..08ae8ba
--- /dev/null
+++ b/typeshed/third_party/3/jwt/contrib/algorithms/pycrypto.pyi
@@ -0,0 +1,10 @@
+from typing import Any
+from jwt.algorithms import Algorithm
+
+from . import _HashAlg
+
+class RSAAlgorithm(Algorithm):
+    SHA256 = ...  # type: _HashAlg
+    SHA384 = ...  # type: _HashAlg
+    SHA512 = ...  # type: _HashAlg
+    def __init__(self, hash_alg: _HashAlg) -> None: ...
diff --git a/typeshed/third_party/3/six/__init__.pyi b/typeshed/third_party/3/six/__init__.pyi
index 333bd27..80f6766 100644
--- a/typeshed/third_party/3/six/__init__.pyi
+++ b/typeshed/third_party/3/six/__init__.pyi
@@ -84,12 +84,12 @@ def byte2int(bs: binary_type) -> int: ...
 def indexbytes(buf: binary_type, i: int) -> int: ...
 def iterbytes(buf: binary_type) -> typing.Iterator[int]: ...
 
-def assertCountEqual(self: unittest.TestCase, first: Iterable[_T], second: Iterable[_T], msg: str = None) -> None: ...
+def assertCountEqual(self: unittest.TestCase, first: Iterable[_T], second: Iterable[_T], msg: Optional[str] = None) -> None: ...
 @overload
-def assertRaisesRegex(self: unittest.TestCase, msg: str = None) -> Any: ...
+def assertRaisesRegex(self: unittest.TestCase, msg: Optional[str] = None) -> Any: ...
 @overload
 def assertRaisesRegex(self: unittest.TestCase, callable_obj: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: ...
-def assertRegex(self: unittest.TestCase, text: AnyStr, expected_regex: Union[AnyStr, Pattern[AnyStr]], msg: str = None) -> None: ...
+def assertRegex(self: unittest.TestCase, text: AnyStr, expected_regex: Union[AnyStr, Pattern[AnyStr]], msg: Optional[str] = None) -> None: ...
 
 exec_ = exec
 
diff --git a/typeshed/third_party/3/typed_ast/ast27.pyi b/typeshed/third_party/3/typed_ast/ast27.pyi
index 28e0dfe..c4bf4f6 100644
--- a/typeshed/third_party/3/typed_ast/ast27.pyi
+++ b/typeshed/third_party/3/typed_ast/ast27.pyi
@@ -242,7 +242,7 @@ class Repr(expr):
     value = ...  # type: expr
 
 class Num(expr):
-    n = ...  # type: Union[int, float]
+    n = ...  # type: Union[int, float, complex]
 
 class Str(expr):
     s = ...  # type: bytes
diff --git a/typeshed/third_party/3/werkzeug/__init__.pyi b/typeshed/third_party/3/werkzeug/__init__.pyi
index 806f964..fc27b09 100644
--- a/typeshed/third_party/3/werkzeug/__init__.pyi
+++ b/typeshed/third_party/3/werkzeug/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from types import ModuleType
 from typing import Any
 
diff --git a/typeshed/third_party/3/werkzeug/_compat.pyi b/typeshed/third_party/3/werkzeug/_compat.pyi
index 1b0f55b..4a5fa32 100644
--- a/typeshed/third_party/3/werkzeug/_compat.pyi
+++ b/typeshed/third_party/3/werkzeug/_compat.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug._compat (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from io import StringIO as BytesIO
 
diff --git a/typeshed/third_party/3/werkzeug/_internal.pyi b/typeshed/third_party/3/werkzeug/_internal.pyi
index d16a33d..6fddbdd 100644
--- a/typeshed/third_party/3/werkzeug/_internal.pyi
+++ b/typeshed/third_party/3/werkzeug/_internal.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug._internal (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class _Missing:
diff --git a/typeshed/third_party/3/werkzeug/_reloader.pyi b/typeshed/third_party/3/werkzeug/_reloader.pyi
index 669065e..55a560d 100644
--- a/typeshed/third_party/3/werkzeug/_reloader.pyi
+++ b/typeshed/third_party/3/werkzeug/_reloader.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug._reloader (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class ReloaderLoop:
diff --git a/typeshed/third_party/3/werkzeug/contrib/__init__.pyi b/typeshed/third_party/3/werkzeug/contrib/__init__.pyi
index 3fb4116..e69de29 100644
--- a/typeshed/third_party/3/werkzeug/contrib/__init__.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/__init__.pyi
@@ -1,3 +0,0 @@
-# Stubs for werkzeug.contrib (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
diff --git a/typeshed/third_party/3/werkzeug/contrib/atom.pyi b/typeshed/third_party/3/werkzeug/contrib/atom.pyi
index cfb535d..1e27873 100644
--- a/typeshed/third_party/3/werkzeug/contrib/atom.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/atom.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.atom (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 XHTML_NAMESPACE = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/contrib/cache.pyi b/typeshed/third_party/3/werkzeug/contrib/cache.pyi
index 7b071ea..2b8abb7 100644
--- a/typeshed/third_party/3/werkzeug/contrib/cache.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/cache.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.cache (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class BaseCache:
diff --git a/typeshed/third_party/3/werkzeug/contrib/fixers.pyi b/typeshed/third_party/3/werkzeug/contrib/fixers.pyi
index d660263..a45c661 100644
--- a/typeshed/third_party/3/werkzeug/contrib/fixers.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/fixers.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.fixers (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class CGIRootFix:
diff --git a/typeshed/third_party/3/werkzeug/contrib/iterio.pyi b/typeshed/third_party/3/werkzeug/contrib/iterio.pyi
index b65323a..33da956 100644
--- a/typeshed/third_party/3/werkzeug/contrib/iterio.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/iterio.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.iterio (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 greenlet = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/contrib/jsrouting.pyi b/typeshed/third_party/3/werkzeug/contrib/jsrouting.pyi
index 9ba5cff..a9cc8c2 100644
--- a/typeshed/third_party/3/werkzeug/contrib/jsrouting.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/jsrouting.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.jsrouting (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def dumps(*args): ...
diff --git a/typeshed/third_party/3/werkzeug/contrib/limiter.pyi b/typeshed/third_party/3/werkzeug/contrib/limiter.pyi
index d27776f..52501c6 100644
--- a/typeshed/third_party/3/werkzeug/contrib/limiter.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/limiter.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.limiter (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class StreamLimitMiddleware:
diff --git a/typeshed/third_party/3/werkzeug/contrib/lint.pyi b/typeshed/third_party/3/werkzeug/contrib/lint.pyi
index ccaecf5..f89c120 100644
--- a/typeshed/third_party/3/werkzeug/contrib/lint.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/lint.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.lint (Python 3)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class WSGIWarning(Warning): ...
diff --git a/typeshed/third_party/3/werkzeug/contrib/profiler.pyi b/typeshed/third_party/3/werkzeug/contrib/profiler.pyi
index d3daf6d..db1eacb 100644
--- a/typeshed/third_party/3/werkzeug/contrib/profiler.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/profiler.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.profiler (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 available = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/contrib/securecookie.pyi b/typeshed/third_party/3/werkzeug/contrib/securecookie.pyi
index 36ed6b7..219356f 100644
--- a/typeshed/third_party/3/werkzeug/contrib/securecookie.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/securecookie.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.securecookie (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from hmac import new as hmac
 from hashlib import sha1 as _default_hash
diff --git a/typeshed/third_party/3/werkzeug/contrib/sessions.pyi b/typeshed/third_party/3/werkzeug/contrib/sessions.pyi
index 69cb4f5..aa3f8fc 100644
--- a/typeshed/third_party/3/werkzeug/contrib/sessions.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/sessions.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.sessions (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.datastructures import CallbackDict
 
diff --git a/typeshed/third_party/3/werkzeug/contrib/testtools.pyi b/typeshed/third_party/3/werkzeug/contrib/testtools.pyi
index 3c21524..860ebb7 100644
--- a/typeshed/third_party/3/werkzeug/contrib/testtools.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/testtools.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.testtools (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.wrappers import Response
 
diff --git a/typeshed/third_party/3/werkzeug/contrib/wrappers.pyi b/typeshed/third_party/3/werkzeug/contrib/wrappers.pyi
index 2e43f6a..4ebc7e8 100644
--- a/typeshed/third_party/3/werkzeug/contrib/wrappers.pyi
+++ b/typeshed/third_party/3/werkzeug/contrib/wrappers.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.contrib.wrappers (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def is_known_charset(charset): ...
diff --git a/typeshed/third_party/3/werkzeug/datastructures.pyi b/typeshed/third_party/3/werkzeug/datastructures.pyi
index 0204b34..64a9c9c 100644
--- a/typeshed/third_party/3/werkzeug/datastructures.pyi
+++ b/typeshed/third_party/3/werkzeug/datastructures.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.datastructures (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from collections import Container, Iterable, Mapping, MutableSet
 
diff --git a/typeshed/third_party/3/werkzeug/debug/__init__.pyi b/typeshed/third_party/3/werkzeug/debug/__init__.pyi
index e02bc3c..0c949f9 100644
--- a/typeshed/third_party/3/werkzeug/debug/__init__.pyi
+++ b/typeshed/third_party/3/werkzeug/debug/__init__.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.wrappers import BaseRequest as Request, BaseResponse as Response
 
diff --git a/typeshed/third_party/3/werkzeug/debug/console.pyi b/typeshed/third_party/3/werkzeug/debug/console.pyi
index 9fdf0b5..5046a51 100644
--- a/typeshed/third_party/3/werkzeug/debug/console.pyi
+++ b/typeshed/third_party/3/werkzeug/debug/console.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug.console (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 import code
 
diff --git a/typeshed/third_party/3/werkzeug/debug/repr.pyi b/typeshed/third_party/3/werkzeug/debug/repr.pyi
index 063c421..fe3faef 100644
--- a/typeshed/third_party/3/werkzeug/debug/repr.pyi
+++ b/typeshed/third_party/3/werkzeug/debug/repr.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug.repr (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 deque = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/debug/tbtools.pyi b/typeshed/third_party/3/werkzeug/debug/tbtools.pyi
index 1107c62..7c0cd58 100644
--- a/typeshed/third_party/3/werkzeug/debug/tbtools.pyi
+++ b/typeshed/third_party/3/werkzeug/debug/tbtools.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.debug.tbtools (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 UTF8_COOKIE = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/exceptions.pyi b/typeshed/third_party/3/werkzeug/exceptions.pyi
index 7e71597..a91abba 100644
--- a/typeshed/third_party/3/werkzeug/exceptions.pyi
+++ b/typeshed/third_party/3/werkzeug/exceptions.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.exceptions (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class HTTPException(Exception):
diff --git a/typeshed/third_party/3/werkzeug/filesystem.pyi b/typeshed/third_party/3/werkzeug/filesystem.pyi
index 5ebc566..80913ca 100644
--- a/typeshed/third_party/3/werkzeug/filesystem.pyi
+++ b/typeshed/third_party/3/werkzeug/filesystem.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.filesystem (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 has_likely_buggy_unicode_filesystem = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/formparser.pyi b/typeshed/third_party/3/werkzeug/formparser.pyi
index 1b63dca..96c7f22 100644
--- a/typeshed/third_party/3/werkzeug/formparser.pyi
+++ b/typeshed/third_party/3/werkzeug/formparser.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.formparser (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def default_stream_factory(total_content_length, filename, content_type, content_length=None): ...
diff --git a/typeshed/third_party/3/werkzeug/http.pyi b/typeshed/third_party/3/werkzeug/http.pyi
index 61202ea..5cc38b7 100644
--- a/typeshed/third_party/3/werkzeug/http.pyi
+++ b/typeshed/third_party/3/werkzeug/http.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.http (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from urllib.request import parse_http_list as _parse_list_header
 from urllib.parse import unquote_to_bytes as _unquote
diff --git a/typeshed/third_party/3/werkzeug/local.pyi b/typeshed/third_party/3/werkzeug/local.pyi
index 1ed3102..f1d167a 100644
--- a/typeshed/third_party/3/werkzeug/local.pyi
+++ b/typeshed/third_party/3/werkzeug/local.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.local (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def release_local(local): ...
diff --git a/typeshed/third_party/3/werkzeug/posixemulation.pyi b/typeshed/third_party/3/werkzeug/posixemulation.pyi
index a2838fc..b490ab4 100644
--- a/typeshed/third_party/3/werkzeug/posixemulation.pyi
+++ b/typeshed/third_party/3/werkzeug/posixemulation.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.posixemulation (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from ._compat import to_unicode as to_unicode
 from .filesystem import get_filesystem_encoding as get_filesystem_encoding
diff --git a/typeshed/third_party/3/werkzeug/routing.pyi b/typeshed/third_party/3/werkzeug/routing.pyi
index ff0bbda..0274542 100644
--- a/typeshed/third_party/3/werkzeug/routing.pyi
+++ b/typeshed/third_party/3/werkzeug/routing.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.routing (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.exceptions import HTTPException
 
diff --git a/typeshed/third_party/3/werkzeug/script.pyi b/typeshed/third_party/3/werkzeug/script.pyi
index a01ffde..758378d 100644
--- a/typeshed/third_party/3/werkzeug/script.pyi
+++ b/typeshed/third_party/3/werkzeug/script.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.script (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 argument_types = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/security.pyi b/typeshed/third_party/3/werkzeug/security.pyi
index b28d68a..dde9fe1 100644
--- a/typeshed/third_party/3/werkzeug/security.pyi
+++ b/typeshed/third_party/3/werkzeug/security.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.security (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 SALT_CHARS = ...  # type: Any
diff --git a/typeshed/third_party/3/werkzeug/serving.pyi b/typeshed/third_party/3/werkzeug/serving.pyi
index db347d2..241f6e2 100644
--- a/typeshed/third_party/3/werkzeug/serving.pyi
+++ b/typeshed/third_party/3/werkzeug/serving.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.serving (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from socketserver import ThreadingMixIn, ForkingMixIn
 from http.server import HTTPServer, BaseHTTPRequestHandler
diff --git a/typeshed/third_party/3/werkzeug/test.pyi b/typeshed/third_party/3/werkzeug/test.pyi
index 1def658..71dc6a6 100644
--- a/typeshed/third_party/3/werkzeug/test.pyi
+++ b/typeshed/third_party/3/werkzeug/test.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.test (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from urllib.request import Request as U2Request
 from http.cookiejar import CookieJar
diff --git a/typeshed/third_party/3/werkzeug/testapp.pyi b/typeshed/third_party/3/werkzeug/testapp.pyi
index cee939b..4e17633 100644
--- a/typeshed/third_party/3/werkzeug/testapp.pyi
+++ b/typeshed/third_party/3/werkzeug/testapp.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.testapp (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug.wrappers import BaseRequest as Request, BaseResponse as Response
 
diff --git a/typeshed/third_party/3/werkzeug/urls.pyi b/typeshed/third_party/3/werkzeug/urls.pyi
index be248d2..2976af0 100644
--- a/typeshed/third_party/3/werkzeug/urls.pyi
+++ b/typeshed/third_party/3/werkzeug/urls.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.urls (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from collections import namedtuple
 from typing import Any
 
diff --git a/typeshed/third_party/3/werkzeug/useragents.pyi b/typeshed/third_party/3/werkzeug/useragents.pyi
index 2471a24..2ca2705 100644
--- a/typeshed/third_party/3/werkzeug/useragents.pyi
+++ b/typeshed/third_party/3/werkzeug/useragents.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.useragents (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 class UserAgentParser:
diff --git a/typeshed/third_party/3/werkzeug/utils.pyi b/typeshed/third_party/3/werkzeug/utils.pyi
index b26f316..8e2e6b9 100644
--- a/typeshed/third_party/3/werkzeug/utils.pyi
+++ b/typeshed/third_party/3/werkzeug/utils.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.utils (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 from werkzeug._internal import _DictAccessorProperty
 
diff --git a/typeshed/third_party/3/werkzeug/wrappers.pyi b/typeshed/third_party/3/werkzeug/wrappers.pyi
index f6b6770..031e377 100644
--- a/typeshed/third_party/3/werkzeug/wrappers.pyi
+++ b/typeshed/third_party/3/werkzeug/wrappers.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.wrappers (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import (
     Any, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union,
 )
@@ -80,7 +76,14 @@ class BaseResponse:
     status = ...  # type: str
     direct_passthrough = ...  # type: bool
     response = ...  # type: Iterable[bytes]
-    def __init__(self, response: Union[Iterable[bytes], bytes]=None, status: Union[str, int]=None, headers: Union[Headers, Mapping[str, str], Sequence[Tuple[str, str]]]=None, mimetype: str=None, content_type: str=None, direct_passthrough: bool=False) -> None: ...
+    def __init__(self, response: Optional[Union[Iterable[bytes], bytes]]=None,
+                 status: Optional[Union[str, int]]=None,
+                 headers: Optional[Union[Headers,
+                                         Mapping[str, str],
+                                         Sequence[Tuple[str, str]]]]=None,
+                 mimetype: Optional[str] = None,
+                 content_type: Optional[str] = None,
+                 direct_passthrough: bool=False) -> None: ...
     def call_on_close(self, func): ...
     @classmethod
     def force_type(cls, response, environ=None): ...
diff --git a/typeshed/third_party/3/werkzeug/wsgi.pyi b/typeshed/third_party/3/werkzeug/wsgi.pyi
index 4a0e681..77722ed 100644
--- a/typeshed/third_party/3/werkzeug/wsgi.pyi
+++ b/typeshed/third_party/3/werkzeug/wsgi.pyi
@@ -1,7 +1,3 @@
-# Stubs for werkzeug.wsgi (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
 from typing import Any
 
 def responder(f): ...
diff --git a/xml/mypy-html.css b/xml/mypy-html.css
index 1a3302d..ec2bdf9 100644
--- a/xml/mypy-html.css
+++ b/xml/mypy-html.css
@@ -99,6 +99,6 @@ a:hover.lineno, a:active.lineno {
     background-color: #ffa;
 }
 
-.line-any {
+.line-any, .line-unanalyzed {
     background-color: #faa;
 }
diff --git a/xml/mypy.xsd b/xml/mypy.xsd
index d5f16eb..83d0832 100644
--- a/xml/mypy.xsd
+++ b/xml/mypy.xsd
@@ -5,6 +5,7 @@
   <xs:simpleType name="precision">
     <xs:restriction base="xs:string">
       <xs:enumeration value="empty"/>
+      <xs:enumeration value="unanalyzed"/>
       <xs:enumeration value="precise"/>
       <xs:enumeration value="imprecise"/>
       <xs:enumeration value="any"/>
@@ -20,6 +21,7 @@
             <xs:attribute name="module" type="xs:string" use="required"/>
             <xs:attribute name="total" type="xs:integer" use="required"/>
             <xs:attribute name="empty" type="xs:integer" use="required"/>
+            <xs:attribute name="unanalyzed" type="xs:integer" use="required"/>
             <xs:attribute name="precise" type="xs:integer" use="required"/>
             <xs:attribute name="imprecise" type="xs:integer" use="required"/>
             <xs:attribute name="any" type="xs:integer" use="required"/>

-- 
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