[med-svn] [mypy] 01/01: Imported Upstream version 0.4.4
Michael Crusoe
misterc-guest at moszumanska.debian.org
Fri Aug 26 12:33:26 UTC 2016
This is an automated email from the git hooks/post-receive script.
misterc-guest pushed a commit to annotated tag upstream/0.4.4
in repository mypy.
commit 18e65dc0f0312d7b8441c1044b18eb7b4a253e20
Author: Michael R. Crusoe <crusoe at ucdavis.edu>
Date: Fri Aug 26 00:51:36 2016 -0700
Imported Upstream version 0.4.4
---
PKG-INFO | 2 +-
mypy/build.py | 290 +++++++++---
mypy/checker.py | 414 +++++++++++++----
mypy/checkexpr.py | 375 ++++++++++-----
mypy/checkstrformat.py | 7 +-
mypy/constraints.py | 1 +
mypy/docstring.py | 204 ---------
mypy/erasetype.py | 32 +-
mypy/errors.py | 94 +++-
mypy/fastparse.py | 55 ++-
mypy/join.py | 21 +-
mypy/main.py | 62 ++-
mypy/messages.py | 50 +-
mypy/nodes.py | 49 +-
mypy/options.py | 8 +-
mypy/parse.py | 23 +-
mypy/report.py | 4 +-
mypy/semanal.py | 391 ++++++++++++++--
mypy/stats.py | 2 +-
mypy/strconv.py | 14 +-
mypy/stubutil.py | 23 +-
mypy/traverser.py | 3 +-
mypy/treetransform.py | 10 +-
mypy/typeanal.py | 15 +-
mypy/types.py | 99 +++-
mypy/version.py | 2 +-
mypy/visitor.py | 6 +
mypy/waiter.py | 15 +-
scripts/find_type.py | 87 ++++
setup.py | 28 ++
typeshed/stdlib/2.7/BaseHTTPServer.pyi | 47 ++
typeshed/stdlib/2.7/ConfigParser.pyi | 4 +-
typeshed/stdlib/2.7/Cookie.pyi | 4 +-
typeshed/stdlib/2.7/SocketServer.pyi | 13 +-
typeshed/stdlib/2.7/__builtin__.pyi | 71 ++-
typeshed/stdlib/2.7/_locale.pyi | 81 ----
typeshed/stdlib/2.7/ast.pyi | 2 +-
typeshed/stdlib/2.7/bisect.pyi | 6 -
typeshed/stdlib/2.7/builtins.pyi | 71 ++-
typeshed/stdlib/2.7/calendar.pyi | 2 +-
typeshed/stdlib/2.7/codecs.pyi | 36 +-
typeshed/stdlib/2.7/contextlib.pyi | 17 -
typeshed/stdlib/2.7/datetime.pyi | 4 +-
typeshed/stdlib/2.7/decimal.pyi | 231 ++++++++++
typeshed/stdlib/2.7/distutils/__init__.pyi | 7 -
typeshed/stdlib/2.7/distutils/emxccompiler.pyi | 5 +
typeshed/stdlib/2.7/distutils/version.pyi | 23 -
typeshed/stdlib/2.7/email/utils.pyi | 4 +-
typeshed/stdlib/2.7/functools.pyi | 2 +-
typeshed/stdlib/2.7/gettext.pyi | 16 +-
typeshed/stdlib/2.7/hmac.pyi | 13 -
typeshed/stdlib/2.7/inspect.pyi | 4 +-
typeshed/stdlib/2.7/locale.pyi | 33 --
typeshed/stdlib/2.7/mimetypes.pyi | 26 --
typeshed/stdlib/2.7/os/__init__.pyi | 11 +-
typeshed/stdlib/2.7/platform.pyi | 20 +-
typeshed/stdlib/2.7/rfc822.pyi | 4 +-
typeshed/stdlib/2.7/simplejson/__init__.pyi | 6 +-
typeshed/stdlib/2.7/socket.pyi | 2 +-
typeshed/stdlib/2.7/sqlite3/dbapi2.pyi | 2 +-
typeshed/stdlib/2.7/ssl.pyi | 350 +++++++-------
typeshed/stdlib/2.7/stat.pyi | 1 +
typeshed/stdlib/2.7/subprocess.pyi | 16 +-
typeshed/stdlib/2.7/sys.pyi | 10 +-
typeshed/stdlib/2.7/threading.pyi | 95 ----
typeshed/stdlib/2.7/traceback.pyi | 20 -
typeshed/stdlib/2.7/typing.pyi | 25 +-
typeshed/stdlib/2.7/unittest.pyi | 2 +-
typeshed/stdlib/2.7/urllib2.pyi | 17 +-
typeshed/stdlib/2.7/xml/etree/ElementInclude.pyi | 2 +-
typeshed/stdlib/2.7/xml/etree/ElementPath.pyi | 2 +-
typeshed/stdlib/2.7/xml/sax/__init__.pyi | 20 +
typeshed/stdlib/2and3/argparse.pyi | 34 +-
typeshed/stdlib/2and3/bisect.pyi | 22 +
typeshed/stdlib/2and3/cmath.pyi | 2 +-
typeshed/stdlib/2and3/code.pyi | 27 ++
typeshed/stdlib/2and3/colorsys.pyi | 15 +
typeshed/stdlib/2and3/contextlib.pyi | 53 +++
.../stdlib/{3 => 2and3}/distutils/__init__.pyi | 0
typeshed/stdlib/2and3/distutils/archive_util.pyi | 12 +
typeshed/stdlib/2and3/distutils/bcppcompiler.pyi | 6 +
typeshed/stdlib/2and3/distutils/ccompiler.pyi | 119 +++++
typeshed/stdlib/2and3/distutils/cmd.pyi | 15 +
.../sax => 2and3/distutils/command}/__init__.pyi | 0
.../2and3/distutils/command/bdist.pyi} | 0
.../distutils/command/bdist_dumb.pyi} | 0
.../stdlib/2and3/distutils/command/bdist_msi.pyi | 5 +
.../distutils/command/bdist_packager.pyi} | 0
.../distutils/command/bdist_rpm.pyi} | 0
.../distutils/command/bdist_wininst.pyi} | 0
.../distutils/command/build.pyi} | 0
.../distutils/command/build_clib.pyi} | 0
.../distutils/command/build_ext.pyi} | 0
.../stdlib/2and3/distutils/command/build_py.pyi | 8 +
.../distutils/command/build_scripts.pyi} | 0
.../distutils/command/check.pyi} | 0
.../distutils/command/clean.pyi} | 0
.../distutils/command/config.pyi} | 0
.../distutils/command/install.pyi} | 0
.../distutils/command/install_data.pyi} | 0
.../distutils/command/install_headers.pyi} | 0
.../distutils/command/install_lib.pyi} | 0
.../distutils/command/install_scripts.pyi} | 0
.../distutils/command/register.pyi} | 0
.../distutils/command/sdist.pyi} | 0
typeshed/stdlib/2and3/distutils/core.pyi | 35 ++
.../stdlib/2and3/distutils/cygwinccompiler.pyi | 7 +
typeshed/stdlib/2and3/distutils/debug.pyi | 3 +
typeshed/stdlib/2and3/distutils/dep_util.pyi | 8 +
typeshed/stdlib/2and3/distutils/dir_util.pyi | 15 +
typeshed/stdlib/2and3/distutils/dist.pyi | 7 +
typeshed/stdlib/2and3/distutils/errors.pyi | 4 +
typeshed/stdlib/2and3/distutils/extension.pyi | 39 ++
typeshed/stdlib/2and3/distutils/fancy_getopt.pyi | 27 ++
typeshed/stdlib/2and3/distutils/file_util.pyi | 12 +
typeshed/stdlib/2and3/distutils/filelist.pyi | 3 +
.../sax/__init__.pyi => 2and3/distutils/log.pyi} | 0
typeshed/stdlib/2and3/distutils/msvccompiler.pyi | 6 +
typeshed/stdlib/2and3/distutils/spawn.pyi | 8 +
typeshed/stdlib/2and3/distutils/sysconfig.pyi | 19 +
typeshed/stdlib/2and3/distutils/text_file.pyi | 18 +
typeshed/stdlib/2and3/distutils/unixccompiler.pyi | 6 +
typeshed/stdlib/2and3/distutils/util.pyi | 20 +
typeshed/stdlib/2and3/distutils/version.pyi | 35 ++
typeshed/stdlib/{2.7 => 2and3}/errno.pyi | 212 ++++-----
typeshed/stdlib/2and3/hmac.pyi | 35 ++
typeshed/stdlib/2and3/keyword.pyi | 6 +
.../stdlib/{3/_locale.pyi => 2and3/locale.pyi} | 130 +++---
typeshed/stdlib/2and3/logging/__init__.pyi | 125 +++--
typeshed/stdlib/2and3/logging/config.pyi | 22 +-
typeshed/stdlib/2and3/logging/handlers.pyi | 105 ++---
typeshed/stdlib/2and3/math.pyi | 7 +-
typeshed/stdlib/2and3/mimetypes.pyi | 38 ++
typeshed/stdlib/2and3/mmap.pyi | 80 ++++
typeshed/stdlib/2and3/operator.pyi | 300 +++++++-----
typeshed/stdlib/2and3/pkgutil.pyi | 31 ++
typeshed/stdlib/2and3/plistlib.pyi | 60 +++
typeshed/stdlib/2and3/readline.pyi | 41 ++
typeshed/stdlib/2and3/rlcompleter.pyi | 13 +
typeshed/stdlib/2and3/site.pyi | 17 +
typeshed/stdlib/2and3/termios.pyi | 246 ++++++++++
typeshed/stdlib/2and3/threading.pyi | 182 ++++++++
typeshed/stdlib/2and3/traceback.pyi | 100 ++++
typeshed/stdlib/2and3/zipfile.pyi | 94 ++++
typeshed/stdlib/{2.7 => 2and3}/zipimport.pyi | 18 +-
typeshed/stdlib/3.4/_operator.pyi | 108 -----
typeshed/stdlib/3.4/asyncio/__init__.pyi | 27 ++
typeshed/stdlib/3.4/asyncio/coroutines.pyi | 6 +-
typeshed/stdlib/3.4/asyncio/events.pyi | 32 +-
typeshed/stdlib/3.4/asyncio/futures.pyi | 5 +-
typeshed/stdlib/3.4/asyncio/locks.pyi | 59 +++
typeshed/stdlib/3.4/asyncio/protocols.pyi | 2 +-
typeshed/stdlib/3.4/asyncio/streams.pyi | 28 +-
typeshed/stdlib/3.4/asyncio/tasks.pyi | 10 +-
typeshed/stdlib/3.4/pathlib.pyi | 210 +++------
typeshed/stdlib/3.4/selectors.pyi | 90 ++++
typeshed/stdlib/3.5/pathlib.pyi | 83 ++++
typeshed/stdlib/3/bisect.pyi | 12 -
typeshed/stdlib/3/builtins.pyi | 63 ++-
typeshed/stdlib/3/cgi.pyi | 3 +
typeshed/stdlib/3/collections/__init__.pyi | 2 +-
typeshed/stdlib/3/concurrent/futures/_base.pyi | 44 +-
typeshed/stdlib/3/contextlib.pyi | 17 -
typeshed/stdlib/3/datetime.pyi | 10 +-
typeshed/stdlib/3/dis.pyi | 18 +-
typeshed/stdlib/3/distutils/errors.pyi | 4 -
typeshed/stdlib/3/distutils/spawn.pyi | 6 -
typeshed/stdlib/3/email/__init__.pyi | 12 +-
typeshed/stdlib/3/email/_header_value_parser.pyi | 397 ----------------
typeshed/stdlib/3/email/_parseaddr.pyi | 44 --
typeshed/stdlib/3/email/base64mime.pyi | 13 -
typeshed/stdlib/3/email/encoders.pyi | 12 +-
typeshed/stdlib/3/email/feedparser.pyi | 7 +-
typeshed/stdlib/3/email/generator.pyi | 9 +-
typeshed/stdlib/3/email/headerregistry.pyi | 7 +-
typeshed/stdlib/3/email/iterators.pyi | 11 +-
typeshed/stdlib/3/email/message.pyi | 50 +-
.../_vendor => stdlib/3/email/mime}/__init__.py | 0
typeshed/stdlib/3/email/mime/__init__.pyi | 4 -
typeshed/stdlib/3/email/mime/application.pyi | 9 +-
typeshed/stdlib/3/email/mime/audio.pyi | 9 +-
typeshed/stdlib/3/email/mime/base.pyi | 12 +-
typeshed/stdlib/3/email/mime/image.pyi | 9 +-
typeshed/stdlib/3/email/mime/message.pyi | 5 +-
typeshed/stdlib/3/email/mime/multipart.pyi | 10 +-
typeshed/stdlib/3/email/mime/nonmultipart.pyi | 5 +-
typeshed/stdlib/3/email/mime/text.pyi | 6 +-
typeshed/stdlib/3/email/parser.pyi | 11 +-
typeshed/stdlib/3/email/policy.pyi | 3 +-
typeshed/stdlib/3/email/quoprimime.pyi | 18 -
typeshed/stdlib/3/email/utils.pyi | 46 +-
typeshed/stdlib/3/errno.pyi | 132 ------
typeshed/stdlib/3/functools.pyi | 2 +-
typeshed/stdlib/3/glob.pyi | 15 +-
typeshed/stdlib/3/heapq.pyi | 2 +-
typeshed/stdlib/3/hmac.pyi | 27 --
typeshed/stdlib/3/html/parser.pyi | 4 +-
typeshed/stdlib/3/http/client.pyi | 115 ++---
typeshed/stdlib/3/http/cookiejar.pyi | 10 +-
typeshed/stdlib/3/importlib.pyi | 9 -
typeshed/stdlib/3/importlib/__init__.pyi | 4 +-
typeshed/stdlib/3/importlib/abc.pyi | 5 +-
typeshed/stdlib/3/importlib/machinery.pyi | 204 ++++++---
typeshed/stdlib/3/inspect.pyi | 2 +-
typeshed/stdlib/3/io.pyi | 38 +-
typeshed/stdlib/3/json.pyi | 39 +-
typeshed/stdlib/3/locale.pyi | 17 -
typeshed/stdlib/3/mimetypes.pyi | 26 --
typeshed/stdlib/3/multiprocessing/__init__.pyi | 2 +
typeshed/stdlib/3/multiprocessing/managers.pyi | 2 +
typeshed/stdlib/3/multiprocessing/process.pyi | 4 +
typeshed/stdlib/3/os/__init__.pyi | 19 +
typeshed/stdlib/3/pyclbr.pyi | 40 ++
typeshed/stdlib/3/queue.pyi | 6 +-
typeshed/stdlib/3/re.pyi | 8 +-
typeshed/stdlib/3/socketserver.pyi | 13 +-
typeshed/stdlib/3/ssl.pyi | 28 +-
typeshed/stdlib/3/stat.pyi | 6 +-
typeshed/stdlib/3/string.pyi | 19 +-
typeshed/stdlib/3/subprocess.pyi | 255 ++++++++---
typeshed/stdlib/3/sys.pyi | 4 +-
typeshed/stdlib/3/textwrap.pyi | 2 +
typeshed/stdlib/3/threading.pyi | 64 ---
typeshed/stdlib/3/traceback.pyi | 18 -
typeshed/stdlib/3/typing.pyi | 38 +-
typeshed/stdlib/3/unittest.pyi | 6 +-
typeshed/stdlib/3/urllib/error.pyi | 10 +-
typeshed/stdlib/3/urllib/request.pyi | 2 +-
typeshed/stdlib/3/xml/sax/__init__.pyi | 20 +
typeshed/stdlib/3/zipfile.pyi | 29 --
typeshed/tests/mypy_test.py | 2 +
.../third_party/2.7/dateutil/relativedelta.pyi | 86 ++++
.../third_party/2.7/google/protobuf/__init__.pyi | 1 +
typeshed/third_party/2and3/pytz/__init__.pyi | 25 +
typeshed/third_party/2and3/pytz/lazy.pyi | 13 +
typeshed/third_party/2and3/ujson.pyi | 45 ++
typeshed/third_party/3/dateutil/relativedelta.pyi | 86 ++++
typeshed/third_party/3/lxml/etree.pyi | 61 ++-
typeshed/third_party/3/lxml/objectify.pyi | 13 +
typeshed/third_party/3/pkg_resources.pyi | 310 +++++++++++++
typeshed/third_party/3/pkg_resources/__init__.pyi | 508 ---------------------
.../3/pkg_resources/_vendor/packaging/__init__.pyi | 4 -
.../pkg_resources/_vendor/packaging/specifiers.pyi | 58 ---
.../3/pkg_resources/_vendor/packaging/version.pyi | 49 --
244 files changed, 6303 insertions(+), 3917 deletions(-)
diff --git a/PKG-INFO b/PKG-INFO
index 0a75168..dd5bf99 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: mypy-lang
-Version: 0.4.3
+Version: 0.4.4
Summary: Optional static typing for Python
Home-page: http://www.mypy-lang.org/
Author: Jukka Lehtosalo
diff --git a/mypy/build.py b/mypy/build.py
index c4b9459..fe40e3d 100644
--- a/mypy/build.py
+++ b/mypy/build.py
@@ -13,6 +13,7 @@ The function build() is the main interface to this module.
import binascii
import collections
import contextlib
+import hashlib
import json
import os
import os.path
@@ -38,6 +39,7 @@ from mypy.fixup import fixup_module_pass_one, fixup_module_pass_two
from mypy.options import Options
from mypy.parse import parse
from mypy.stats import dump_type_stats
+from mypy.version import __version__
# We need to know the location of this file to load data, but
@@ -47,6 +49,9 @@ __file__ = os.path.realpath(__file__)
PYTHON_EXTENSIONS = ['.pyi', '.py']
+Graph = Dict[str, 'State']
+
+
class BuildResult:
"""The result of a successful build.
@@ -136,7 +141,7 @@ def build(sources: List[BuildSource],
# Use stub builtins (to speed up test cases and to make them easier to
# debug). This is a test-only feature, so assume our files are laid out
# as in the source tree.
- root_dir = os.path.dirname(os.path.dirname(__file__))
+ root_dir = dirname(dirname(__file__))
lib_path.insert(0, os.path.join(root_dir, 'test-data', 'unit', 'lib-stub'))
else:
for source in sources:
@@ -171,7 +176,9 @@ def build(sources: List[BuildSource],
ignore_prefix=os.getcwd(),
source_set=source_set,
reports=reports,
- options=options)
+ options=options,
+ version_id=__version__,
+ )
try:
dispatch(sources, manager)
@@ -281,8 +288,11 @@ CacheMeta = NamedTuple('CacheMeta',
('data_mtime', float), # mtime of data_json
('data_json', str), # path of <id>.data.json
('suppressed', List[str]), # dependencies that weren't imported
+ ('child_modules', List[str]), # all submodules of the given module
('options', Optional[Dict[str, bool]]), # build options
('dep_prios', List[int]),
+ ('interface_hash', str), # hash representing the public interface
+ ('version_id', str), # mypy version for cache invalidation
])
# NOTE: dependencies + suppressed == all reachable imports;
# suppressed contains those reachable imports that were prevented by
@@ -318,6 +328,7 @@ class BuildManager:
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)
"""
def __init__(self, data_dir: str,
@@ -325,21 +336,33 @@ class BuildManager:
ignore_prefix: str,
source_set: BuildSourceSet,
reports: Reports,
- options: Options) -> None:
+ options: Options,
+ version_id: str) -> None:
self.start_time = time.time()
self.data_dir = data_dir
- self.errors = Errors()
+ self.errors = Errors(options.suppress_error_context)
self.errors.set_ignore_prefix(ignore_prefix)
self.lib_path = tuple(lib_path)
self.source_set = source_set
self.reports = reports
self.options = options
+ self.version_id = version_id
self.semantic_analyzer = SemanticAnalyzer(lib_path, self.errors, options=options)
self.modules = self.semantic_analyzer.modules
self.semantic_analyzer_pass3 = ThirdPass(self.modules, self.errors)
self.type_checker = TypeChecker(self.errors, self.modules, options=options)
self.missing_modules = set() # type: Set[str]
self.stale_modules = set() # type: Set[str]
+ self.rechecked_modules = set() # type: Set[str]
+
+ def maybe_swap_for_shadow_path(self, path: str) -> str:
+ if (self.options.shadow_file and
+ os.path.samefile(self.options.shadow_file[0], path)):
+ path = self.options.shadow_file[1]
+ return path
+
+ def get_stat(self, path: str) -> os.stat_result:
+ return os.stat(self.maybe_swap_for_shadow_path(path))
def all_imported_modules_in_file(self,
file: MypyFile) -> List[Tuple[int, str, int]]:
@@ -414,25 +437,11 @@ class BuildManager:
tree = parse(source, path, self.errors, options=self.options)
tree._fullname = id
- # We don't want to warn about 'type: ignore' comments on
- # imports, but we're about to modify tree.imports, so grab
- # these first.
- import_lines = set(node.line for node in tree.imports)
-
- # Skip imports that have been ignored (so that we can ignore a C extension module without
- # stub, for example), except for 'from x import *', because we wouldn't be able to
- # determine which names should be defined unless we process the module. We can still
- # ignore errors such as redefinitions when using the latter form.
- imports = [node for node in tree.imports
- if node.line not in tree.ignored_lines or isinstance(node, ImportAll)]
- tree.imports = imports
-
if self.errors.num_messages() != num_errs:
self.log("Bailing due to parse errors")
self.errors.raise_error()
self.errors.set_file_ignored_lines(path, tree.ignored_lines)
- self.errors.mark_file_ignored_lines_used(path, import_lines)
return tree
def module_not_found(self, path: str, line: int, id: str) -> None:
@@ -709,12 +718,14 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
id, path, manager.options.cache_dir, manager.options.python_version)
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))
return None
with open(meta_json, 'r') as f:
meta_str = f.read()
manager.trace('Meta {} {}'.format(id, meta_str.rstrip()))
meta = json.loads(meta_str) # TODO: Errors
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(
@@ -726,36 +737,53 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
meta.get('data_mtime'),
data_json,
meta.get('suppressed', []),
+ meta.get('child_modules', []),
meta.get('options'),
meta.get('dep_prios', []),
+ meta.get('interface_hash', ''),
+ meta.get('version_id'),
)
if (m.id != id or m.path != path or
m.mtime is None or m.size is None or
m.dependencies is None or m.data_mtime is None):
+ manager.trace('Metadata abandoned for {}: attributes are missing'.format(id))
return None
# Ignore cache if generated by an older mypy version.
- if m.options is None or len(m.dependencies) != len(m.dep_prios):
+ if (m.version_id != manager.version_id
+ or m.options is None
+ or len(m.dependencies) != len(m.dep_prios)):
+ manager.trace('Metadata abandoned for {}: new attributes are missing'.format(id))
return None
# Ignore cache if (relevant) options aren't the same.
cached_options = m.options
current_options = select_options_affecting_cache(manager.options)
if cached_options != current_options:
+ manager.trace('Metadata abandoned for {}: options differ'.format(id))
return None
+ return m
+
+
+def is_meta_fresh(meta: CacheMeta, id: str, path: str, manager: BuildManager) -> bool:
+ if meta is None:
+ return False
+
# TODO: Share stat() outcome with find_module()
- st = os.stat(path) # TODO: Errors
- if st.st_mtime != m.mtime or st.st_size != m.size:
- manager.log('Metadata abandoned because of modified file {}'.format(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 None
+
# It's a match on (id, path, mtime, size).
# Check data_json; assume if its mtime matches it's good.
# TODO: stat() errors
- if os.path.getmtime(data_json) != m.data_mtime:
- return None
- manager.log('Found {} {}'.format(id, meta_json))
- return m
+ if os.path.getmtime(meta.data_json) != meta.data_mtime:
+ manager.log('Metadata abandoned for {}: data cache is modified'.format(id))
+ return False
+ manager.log('Found {} {} (metadata is fresh)'.format(id, meta.data_json))
+ return True
def select_options_affecting_cache(options: Options) -> Mapping[str, bool]:
@@ -775,10 +803,17 @@ def random_string() -> str:
return binascii.hexlify(os.urandom(8)).decode('ascii')
+def compute_hash(text: str) -> str:
+ # We use md5 instead of the builtin hash(...) function because the output of hash(...)
+ # can differ between runs due to hash randomization (enabled by default in Python 3.3).
+ # See the note in https://docs.python.org/3/reference/datamodel.html#object.__hash__.
+ return hashlib.md5(text.encode('utf-8')).hexdigest()
+
+
def write_cache(id: str, path: str, tree: MypyFile,
dependencies: List[str], suppressed: List[str],
- dep_prios: List[int],
- manager: BuildManager) -> None:
+ child_modules: List[str], dep_prios: List[int],
+ old_interface_hash: str, manager: BuildManager) -> str:
"""Write cache files for a module.
Args:
@@ -788,28 +823,52 @@ def write_cache(id: str, path: str, tree: MypyFile,
dependencies: module IDs on which this module depends
suppressed: module IDs which were suppressed as dependencies
dep_prios: priorities (parallel array to dependencies)
+ old_interface_hash: the hash from the previous version of the data cache file
manager: the build manager (for pyversion, log/trace)
+
+ Return:
+ The new interface hash based on the serialized tree
"""
+ # Obtain file paths
path = os.path.abspath(path)
- manager.trace('Dumping {} {}'.format(id, path))
- st = os.stat(path) # TODO: Errors
- mtime = st.st_mtime
- size = st.st_size
meta_json, data_json = get_cache_names(
id, path, manager.options.cache_dir, manager.options.python_version)
- manager.log('Writing {} {} {}'.format(id, meta_json, data_json))
- data = tree.serialize()
+ manager.log('Writing {} {} {} {}'.format(id, path, meta_json, data_json))
+
+ # Make sure directory for cache files exists
parent = os.path.dirname(data_json)
if not os.path.isdir(parent):
os.makedirs(parent)
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
- with open(data_json_tmp, 'w') as f:
- json.dump(data, f, indent=2, sort_keys=True)
- f.write('\n')
- data_mtime = os.path.getmtime(data_json_tmp)
+
+ # Serialize data and analyze interface
+ data = tree.serialize()
+ data_str = json.dumps(data, indent=2, sort_keys=True)
+ interface_hash = compute_hash(data_str)
+
+ # Write data cache file, if applicable
+ 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)
+ manager.trace("Interface for {} is unchanged".format(id))
+ else:
+ with open(data_json_tmp, 'w') as f:
+ f.write(data_str)
+ f.write('\n')
+ data_mtime = os.path.getmtime(data_json_tmp)
+ os.replace(data_json_tmp, data_json)
+ manager.trace("Interface for {} has changed".format(id))
+
+ # Obtain and set up metadata
+ st = manager.get_stat(path) # TODO: Handle errors
+ mtime = st.st_mtime
+ size = st.st_size
meta = {'id': id,
'path': path,
'mtime': mtime,
@@ -817,15 +876,21 @@ def write_cache(id: str, path: str, tree: MypyFile,
'data_mtime': data_mtime,
'dependencies': dependencies,
'suppressed': suppressed,
+ 'child_modules': child_modules,
'options': select_options_affecting_cache(manager.options),
'dep_prios': dep_prios,
+ 'interface_hash': interface_hash,
+ 'version_id': manager.version_id,
}
+
+ # Write meta cache file
with open(meta_json_tmp, 'w') as f:
json.dump(meta, f, sort_keys=True)
f.write('\n')
- os.replace(data_json_tmp, data_json)
os.replace(meta_json_tmp, meta_json)
+ return interface_hash
+
"""Dependency manager.
@@ -999,6 +1064,9 @@ class State:
# Parent package, its parent, etc.
ancestors = None # type: Optional[List[str]]
+ # A list of all direct submodules of a given module
+ child_modules = None # type: Optional[Set[str]]
+
# List of (path, line number) tuples giving context for import
import_context = None # type: List[Tuple[str, int]]
@@ -1008,6 +1076,12 @@ class State:
# If caller_state is set, the line number in the caller where the import occurred
caller_line = 0
+ # If True, indicate that the public interface of this module is unchanged
+ externally_same = True
+
+ # Contains a hash of the public interface in incremental mode
+ interface_hash = "" # type: str
+
def __init__(self,
id: Optional[str],
path: Optional[str],
@@ -1087,8 +1161,10 @@ class State:
if path and source is None and manager.options.incremental:
self.meta = find_cache_meta(self.id, self.path, manager)
# TODO: Get mtime if not cached.
+ if self.meta is not None:
+ self.interface_hash = self.meta.interface_hash
self.add_ancestors()
- if self.meta:
+ if is_meta_fresh(self.meta, self.id, self.path, manager):
# Make copies, since we may modify these and want to
# compare them to the originals later.
self.dependencies = list(self.meta.dependencies)
@@ -1096,11 +1172,14 @@ class State:
assert len(self.meta.dependencies) == len(self.meta.dep_prios)
self.priorities = {id: pri
for id, pri in zip(self.meta.dependencies, self.meta.dep_prios)}
+ self.child_modules = set(self.meta.child_modules)
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()
def skipping_ancestor(self, id: str, path: str, ancestor_for: 'State') -> None:
# TODO: Read the path (the __init__.py file) and return
@@ -1147,11 +1226,26 @@ class State:
# self.meta.dependencies when a dependency is dropped due to
# suppression by --silent-imports. However when a suppressed
# dependency is added back we find out later in the process.
- return self.meta is not None and self.dependencies == self.meta.dependencies
+ return (self.meta is not None
+ and self.is_interface_fresh()
+ and self.dependencies == self.meta.dependencies
+ and self.child_modules == set(self.meta.child_modules))
- def mark_stale(self) -> None:
- """Throw away the cache data for this file, marking it as stale."""
+ def is_interface_fresh(self) -> bool:
+ return self.externally_same
+
+ def has_new_submodules(self) -> bool:
+ """Return if this module has new submodules after being loaded from a warm cache."""
+ return self.meta is not None and self.child_modules != set(self.meta.child_modules)
+
+ def mark_as_rechecked(self) -> None:
+ """Marks this module as having been fully re-analyzed by the type-checker."""
+ self.manager.rechecked_modules.add(self.id)
+
+ def mark_interface_stale(self) -> None:
+ """Marks this module as having a stale public interface, and discards the cache data."""
self.meta = None
+ self.externally_same = False
self.manager.stale_modules.add(self.id)
def check_blockers(self) -> None:
@@ -1169,7 +1263,7 @@ class State:
except CompileError:
raise
except Exception as err:
- report_internal_error(err, self.path, 0)
+ report_internal_error(err, self.path, 0, self.manager.errors)
self.manager.errors.set_import_context(save_import_context)
self.check_blockers()
@@ -1188,6 +1282,40 @@ class State:
def calculate_mros(self) -> None:
fixup_module_pass_two(self.tree, self.manager.modules)
+ def fix_suppressed_dependencies(self, graph: Graph) -> None:
+ """Corrects whether dependencies are considered stale or not when using silent_imports.
+
+ This method is a hack to correct imports in silent_imports + incremental mode.
+ In particular, the problem is that when running mypy with a cold cache, the
+ `parse_file(...)` function is called *at the start* of the `load_graph(...)` function.
+ Note that load_graph will mark some dependencies as suppressed if they weren't specified
+ on the command line in silent_imports mode.
+
+ However, if the interface for a module is changed, parse_file will be called within
+ `process_stale_scc` -- *after* load_graph is finished, wiping out the changes load_graph
+ previously made.
+
+ This method is meant to be run after parse_file finishes in process_stale_scc and will
+ recompute what modules should be considered suppressed in silent_import mode.
+ """
+ # TODO: See if it's possible to move this check directly into parse_file in some way.
+ # TODO: Find a way to write a test case for this fix.
+ silent_mode = self.manager.options.silent_imports or self.manager.options.almost_silent
+ if not silent_mode:
+ return
+
+ new_suppressed = []
+ new_dependencies = []
+ entry_points = self.manager.source_set.source_modules
+ for dep in self.dependencies + self.suppressed:
+ ignored = dep in self.suppressed and dep not in entry_points
+ if ignored or dep not in graph:
+ new_suppressed.append(dep)
+ else:
+ new_dependencies.append(dep)
+ self.dependencies = new_dependencies
+ self.suppressed = new_suppressed
+
# Methods for processing modules from source code.
def parse_file(self) -> None:
@@ -1204,7 +1332,8 @@ class State:
self.source = None # We won't need it again.
if self.path and source is None:
try:
- source = read_with_python_encoding(self.path, manager.options.python_version)
+ path = manager.maybe_swap_for_shadow_path(self.path)
+ source = read_with_python_encoding(path, manager.options.python_version)
except IOError as ioerr:
raise CompileError([
"mypy: can't read file '{}': {}".format(self.path, ioerr.strerror)])
@@ -1307,17 +1436,21 @@ class State:
def write_cache(self) -> None:
if self.path and self.manager.options.incremental and not self.manager.errors.is_errors():
dep_prios = [self.priorities.get(dep, PRI_HIGH) for dep in self.dependencies]
- write_cache(self.id, self.path, self.tree,
- list(self.dependencies), list(self.suppressed),
- dep_prios,
- self.manager)
-
-
-Graph = Dict[str, 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,
+ self.manager)
+ if new_interface_hash == self.interface_hash:
+ self.manager.log("Cached module {} has same interface".format(self.id))
+ else:
+ self.manager.log("Cached module {} has changed interface".format(self.id))
+ self.mark_interface_stale()
+ self.interface_hash = new_interface_hash
def dispatch(sources: List[BuildSource], manager: BuildManager) -> None:
- manager.log("Using new dependency manager")
+ manager.log("Mypy version %s" % __version__)
graph = load_graph(sources, manager)
manager.log("Loaded graph with %d nodes" % len(graph))
process_graph(graph, manager)
@@ -1332,6 +1465,7 @@ def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph:
# TODO: Consider whether to go depth-first instead. This may
# affect the order in which we process files within import cycles.
new = collections.deque() # type: collections.deque[State]
+ entry_points = set() # type: Set[str]
# Seed the graph with the initial root sources.
for bs in sources:
try:
@@ -1344,11 +1478,16 @@ def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph:
manager.errors.raise_error()
graph[st.id] = st
new.append(st)
+ entry_points.add(bs.module)
# Collect dependencies. We go breadth-first.
while new:
st = new.popleft()
- for dep in st.ancestors + st.dependencies:
- if dep not in graph:
+ for dep in st.ancestors + st.dependencies + st.suppressed:
+ # We don't want to recheck imports marked with '# type: ignore'
+ # so we ignore any suppressed module not explicitly re-included
+ # from the command line.
+ ignored = dep in st.suppressed and dep not in entry_points
+ if dep not in graph and not ignored:
try:
if dep in st.ancestors:
# TODO: Why not 'if dep not in st.dependencies' ?
@@ -1366,6 +1505,17 @@ def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph:
assert newst.id not in graph, newst.id
graph[newst.id] = newst
new.append(newst)
+ if dep in st.ancestors and dep in graph:
+ graph[dep].child_modules.add(st.id)
+ if dep in graph and dep in st.suppressed:
+ # Previously suppressed file is now visible
+ if dep in st.suppressed:
+ st.suppressed.remove(dep)
+ st.dependencies.append(dep)
+ for id, g in graph.items():
+ if g.has_new_submodules():
+ g.parse_file()
+ g.mark_interface_stale()
return graph
@@ -1404,7 +1554,7 @@ def process_graph(graph: Graph, manager: BuildManager) -> None:
for id in scc:
deps.update(graph[id].dependencies)
deps -= ascc
- stale_deps = {id for id in deps if not graph[id].is_fresh()}
+ stale_deps = {id for id in deps if not graph[id].is_interface_fresh()}
fresh = fresh and not stale_deps
undeps = set()
if fresh:
@@ -1420,9 +1570,10 @@ def process_graph(graph: Graph, manager: BuildManager) -> None:
# All cache files are fresh. Check that no dependency's
# cache file is newer than any scc node's cache file.
oldest_in_scc = min(graph[id].meta.data_mtime for id in scc)
- newest_in_deps = 0 if not deps else max(graph[dep].meta.data_mtime for dep in deps)
+ viable = {id for id in deps if not graph[id].is_interface_fresh()}
+ newest_in_deps = 0 if not viable else max(graph[dep].meta.data_mtime for dep in viable)
if manager.options.verbosity >= 3: # Dump all mtimes for extreme debugging.
- all_ids = sorted(ascc | deps, key=lambda id: graph[id].meta.data_mtime)
+ all_ids = sorted(ascc | viable, key=lambda id: graph[id].meta.data_mtime)
for id in all_ids:
if id in scc:
if graph[id].meta.data_mtime < newest_in_deps:
@@ -1460,6 +1611,25 @@ def process_graph(graph: Graph, manager: BuildManager) -> None:
else:
process_stale_scc(graph, scc)
+ # TODO: This is a workaround to get around the "chaining imports" problem
+ # with the interface checks.
+ #
+ # That is, if we have a file named `module_a.py` which does:
+ #
+ # import module_b
+ # module_b.module_c.foo(3)
+ #
+ # ...and if the type signature of `module_c.foo(...)` were to change,
+ # module_a_ would not be rechecked since the interface of `module_b`
+ # would not be considered changed.
+ #
+ # As a workaround, this check will force a module's interface to be
+ # considered stale if anything it imports has a stale interface,
+ # which ensures these changes are caught and propagated.
+ if len(stale_deps) > 0:
+ for id in scc:
+ graph[id].mark_interface_stale()
+
def order_ascc(graph: Graph, ascc: AbstractSet[str], pri_max: int = PRI_ALL) -> List[str]:
"""Come up with the ideal processing order within an SCC.
@@ -1523,11 +1693,10 @@ def process_fresh_scc(graph: Graph, scc: List[str]) -> None:
def process_stale_scc(graph: Graph, scc: List[str]) -> None:
"""Process the modules in one SCC from source code."""
for id in scc:
- graph[id].mark_stale()
- for id in scc:
# We may already have parsed the module, or not.
# If the former, parse_file() is a no-op.
graph[id].parse_file()
+ graph[id].fix_suppressed_dependencies(graph)
for id in scc:
graph[id].patch_parent()
for id in scc:
@@ -1537,6 +1706,7 @@ def process_stale_scc(graph: Graph, scc: List[str]) -> None:
for id in scc:
graph[id].type_check()
graph[id].write_cache()
+ graph[id].mark_as_rechecked()
def sorted_components(graph: Graph,
diff --git a/mypy/checker.py b/mypy/checker.py
index 5bacc9d..6a5b0d9 100644
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -11,7 +11,7 @@ from typing import (
from mypy.errors import Errors, report_internal_error
from mypy.nodes import (
- SymbolTable, Node, MypyFile, Var,
+ SymbolTable, Node, MypyFile, Var, Expression,
OverloadedFuncDef, FuncDef, FuncItem, FuncBase, TypeInfo,
ClassDef, GDEF, Block, AssignmentStmt, NameExpr, MemberExpr, IndexExpr,
TupleExpr, ListExpr, ExpressionStmt, ReturnStmt, IfStmt,
@@ -20,11 +20,12 @@ from mypy.nodes import (
BytesExpr, UnicodeExpr, FloatExpr, OpExpr, UnaryExpr, CastExpr, RevealTypeExpr, SuperExpr,
TypeApplication, DictExpr, SliceExpr, FuncExpr, TempNode, SymbolTableNode,
Context, ListComprehension, ConditionalExpr, GeneratorExpr,
- Decorator, SetExpr, TypeVarExpr, PrintStmt,
+ Decorator, SetExpr, TypeVarExpr, NewTypeExpr, PrintStmt,
LITERAL_TYPE, BreakStmt, ContinueStmt, ComparisonExpr, StarExpr,
YieldFromExpr, NamedTupleExpr, SetComprehension,
DictionaryComprehension, ComplexExpr, EllipsisExpr, TypeAliasExpr,
RefExpr, YieldExpr, BackquoteExpr, ImportFrom, ImportAll, ImportBase,
+ AwaitExpr,
CONTRAVARIANT, COVARIANT
)
from mypy.nodes import function_type, method_type, method_type_with_fallback
@@ -32,7 +33,8 @@ from mypy import nodes
from mypy.types import (
Type, AnyType, CallableType, Void, FunctionLike, Overloaded, TupleType,
Instance, NoneTyp, ErrorType, strip_type,
- UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType
+ UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType,
+ true_only, false_only
)
from mypy.sametypes import is_same_type
from mypy.messages import MessageBuilder
@@ -145,8 +147,7 @@ class TypeChecker(NodeVisitor[Type]):
self.globals = file_node.names
self.weak_opts = file_node.weak_opts
self.enter_partial_types()
- # gross, but no other clear way to tell
- self.is_typeshed_stub = self.is_stub and 'typeshed' in os.path.normpath(path).split(os.sep)
+ self.is_typeshed_stub = self.errors.is_typeshed_file(path)
for d in file_node.defs:
self.accept(d)
@@ -200,7 +201,7 @@ class TypeChecker(NodeVisitor[Type]):
try:
typ = node.accept(self)
except Exception as err:
- report_internal_error(err, self.errors.file, node.line)
+ report_internal_error(err, self.errors.file, node.line, self.errors)
self.type_context.pop()
self.store_type(node, typ)
if self.typing_mode_none():
@@ -257,65 +258,151 @@ class TypeChecker(NodeVisitor[Type]):
self.msg.overloaded_signatures_overlap(i + 1, i + j + 2,
item.func)
- def is_generator_return_type(self, typ: Type) -> bool:
- return is_subtype(self.named_generic_type('typing.Generator',
- [AnyType(), AnyType(), AnyType()]),
- typ)
+ # Here's the scoop about generators and coroutines.
+ #
+ # There are two kinds of generators: classic generators (functions
+ # with `yield` or `yield from` in the body) and coroutines
+ # (functions declared with `async def`). The latter are specified
+ # in PEP 492 and only available in Python >= 3.5.
+ #
+ # Classic generators can be parameterized with three types:
+ # - ty is the Yield type (the type of y in `yield y`)
+ # - tc is the type reCeived by yield (the type of c in `c = yield`).
+ # - tr is the Return type (the type of r in `return r`)
+ #
+ # A classic generator must define a return type that's either
+ # `Generator[ty, tc, tr]`, Iterator[ty], or Iterable[ty] (or
+ # object or Any). If tc/tr are not given, both are Void.
+ #
+ # A coroutine must define a return type corresponding to tr; the
+ # other two are unconstrained. The "external" return type (seen
+ # by the caller) is Awaitable[tr].
+ #
+ # In addition, there's the synthetic type AwaitableGenerator: it
+ # inherits from both Awaitable and Generator and can be used both
+ # in `yield from` and in `await`. This type is set automatically
+ # for functions decorated with `@types.coroutine` or
+ # `@asyncio.coroutine`. Its single parameter corresponds to tr.
+ #
+ # There are several useful methods, each taking a type t and a
+ # flag c indicating whether it's for a generator or coroutine:
+ #
+ # - is_generator_return_type(t, c) returns whether t is a Generator,
+ # Iterator, Iterable (if not c), or Awaitable (if c), or
+ # AwaitableGenerator (regardless of c).
+ # - get_generator_yield_type(t, c) returns ty.
+ # - get_generator_receive_type(t, c) returns tc.
+ # - get_generator_return_type(t, c) returns tr.
+
+ def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool:
+ """Is `typ` a valid type for a generator/coroutine?
+
+ True if `typ` is a *supertype* of Generator or Awaitable.
+ Also true it it's *exactly* AwaitableGenerator (modulo type parameters).
+ """
+ if is_coroutine:
+ # This means we're in Python 3.5 or later.
+ at = self.named_generic_type('typing.Awaitable', [AnyType()])
+ if is_subtype(at, typ):
+ return True
+ else:
+ gt = self.named_generic_type('typing.Generator', [AnyType(), AnyType(), AnyType()])
+ if is_subtype(gt, typ):
+ return True
+ return isinstance(typ, Instance) and typ.type.fullname() == 'typing.AwaitableGenerator'
- def get_generator_yield_type(self, return_type: Type) -> Type:
+ def get_generator_yield_type(self, return_type: Type, is_coroutine: bool) -> Type:
+ """Given the declared return type of a generator (t), return the type it yields (ty)."""
if isinstance(return_type, AnyType):
return AnyType()
- elif not self.is_generator_return_type(return_type):
- # If the function doesn't have a proper Generator (or superclass) return type, anything
- # is permissible.
+ elif not self.is_generator_return_type(return_type, is_coroutine):
+ # If the function doesn't have a proper Generator (or
+ # Awaitable) return type, anything is permissible.
return AnyType()
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType()
+ elif return_type.type.fullname() == 'typing.Awaitable':
+ # Awaitable: ty is Any.
+ return AnyType()
elif return_type.args:
- return return_type.args[0]
+ # AwaitableGenerator, Generator, Iterator, or Iterable; ty is args[0].
+ ret_type = return_type.args[0]
+ # TODO not best fix, better have dedicated yield token
+ if isinstance(ret_type, NoneTyp):
+ if experiments.STRICT_OPTIONAL:
+ return NoneTyp(is_ret_type=True)
+ else:
+ return Void()
+ return ret_type
else:
# If the function's declared supertype of Generator has no type
# parameters (i.e. is `object`), then the yielded values can't
- # be accessed so any type is acceptable.
+ # be accessed so any type is acceptable. IOW, ty is Any.
+ # (However, see https://github.com/python/mypy/issues/1933)
return AnyType()
- def get_generator_receive_type(self, return_type: Type) -> Type:
+ def get_generator_receive_type(self, return_type: Type, is_coroutine: bool) -> Type:
+ """Given a declared generator return type (t), return the type its yield receives (tc)."""
if isinstance(return_type, AnyType):
return AnyType()
- elif not self.is_generator_return_type(return_type):
- # If the function doesn't have a proper Generator (or superclass) return type, anything
- # is permissible.
+ elif not self.is_generator_return_type(return_type, is_coroutine):
+ # If the function doesn't have a proper Generator (or
+ # Awaitable) return type, anything is permissible.
return AnyType()
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType()
- elif return_type.type.fullname() == 'typing.Generator':
- # Generator is the only type which specifies the type of values it can receive.
+ elif return_type.type.fullname() == 'typing.Awaitable':
+ # Awaitable, AwaitableGenerator: tc is Any.
+ return AnyType()
+ elif (return_type.type.fullname() in ('typing.Generator', 'typing.AwaitableGenerator')
+ and len(return_type.args) >= 3):
+ # Generator: tc is args[1].
return return_type.args[1]
else:
# `return_type` is a supertype of Generator, so callers won't be able to send it
- # values.
- return Void()
+ # values. IOW, tc is None.
+ if experiments.STRICT_OPTIONAL:
+ return NoneTyp(is_ret_type=True)
+ else:
+ return Void()
- def get_generator_return_type(self, return_type: Type) -> Type:
+ def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Type:
+ """Given the declared return type of a generator (t), return the type it returns (tr)."""
if isinstance(return_type, AnyType):
return AnyType()
- elif not self.is_generator_return_type(return_type):
- # If the function doesn't have a proper Generator (or superclass) return type, anything
- # is permissible.
+ elif not self.is_generator_return_type(return_type, is_coroutine):
+ # If the function doesn't have a proper Generator (or
+ # Awaitable) return type, anything is permissible.
return AnyType()
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType()
- elif return_type.type.fullname() == 'typing.Generator':
- # Generator is the only type which specifies the type of values it returns into
- # `yield from` expressions.
+ elif return_type.type.fullname() == 'typing.Awaitable' and len(return_type.args) == 1:
+ # Awaitable: tr is args[0].
+ return return_type.args[0]
+ elif (return_type.type.fullname() in ('typing.Generator', 'typing.AwaitableGenerator')
+ and len(return_type.args) >= 3):
+ # AwaitableGenerator, Generator: tr is args[2].
return return_type.args[2]
else:
- # `return_type` is supertype of Generator, so callers won't be able to see the return
- # type when used in a `yield from` expression.
+ # Supertype of Generator (Iterator, Iterable, object): tr is any.
+ return AnyType()
+
+ def check_awaitable_expr(self, t: Type, ctx: Context, msg: str) -> Type:
+ """Check the argument to `await` and extract the type of value.
+
+ Also used by `async for` and `async with`.
+ """
+ if not self.check_subtype(t, self.named_type('typing.Awaitable'), ctx,
+ msg, 'actual type', 'expected type'):
return AnyType()
+ else:
+ echk = self.expr_checker
+ method = echk.analyze_external_member_access('__await__', t, ctx)
+ generator = echk.check_call(method, [], [], ctx)[0]
+ return self.get_generator_return_type(generator, False)
def visit_func_def(self, defn: FuncDef) -> Type:
"""Type check a function definition."""
@@ -415,7 +502,7 @@ class TypeChecker(NodeVisitor[Type]):
if fdef:
# Check if __init__ has an invalid, non-None return type.
if (fdef.info and fdef.name() == '__init__' and
- not isinstance(typ.ret_type, Void) and
+ not isinstance(typ.ret_type, (Void, NoneTyp)) and
not self.dynamic_funcs[-1]):
self.fail(messages.INIT_MUST_HAVE_NONE_RETURN_TYPE,
item.type)
@@ -447,17 +534,30 @@ class TypeChecker(NodeVisitor[Type]):
# Check that Generator functions have the appropriate return type.
if defn.is_generator:
- if not self.is_generator_return_type(typ.ret_type):
+ if not self.is_generator_return_type(typ.ret_type, defn.is_coroutine):
self.fail(messages.INVALID_RETURN_TYPE_FOR_GENERATOR, typ)
# Python 2 generators aren't allowed to return values.
if (self.options.python_version[0] == 2 and
isinstance(typ.ret_type, Instance) and
typ.ret_type.type.fullname() == 'typing.Generator'):
- if not (isinstance(typ.ret_type.args[2], Void)
- or isinstance(typ.ret_type.args[2], AnyType)):
+ if not isinstance(typ.ret_type.args[2], (Void, NoneTyp, AnyType)):
self.fail(messages.INVALID_GENERATOR_RETURN_ITEM_TYPE, typ)
+ # Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`.
+ if defn.is_awaitable_coroutine:
+ # Update the return type to AwaitableGenerator.
+ # (This doesn't exist in typing.py, only in typing.pyi.)
+ t = typ.ret_type
+ c = defn.is_coroutine
+ ty = self.get_generator_yield_type(t, c)
+ tc = self.get_generator_receive_type(t, c)
+ tr = self.get_generator_return_type(t, c)
+ ret_type = self.named_generic_type('typing.AwaitableGenerator',
+ [ty, tc, tr, t])
+ typ = typ.copy_modified(ret_type=ret_type)
+ defn.type = typ
+
# Push return type.
self.return_types.append(typ.ret_type)
@@ -709,9 +809,13 @@ class TypeChecker(NodeVisitor[Type]):
# Map the overridden method type to subtype context so that
# it can be checked for compatibility.
original_type = base_attr.type
- if original_type is None and isinstance(base_attr.node,
- FuncDef):
- original_type = self.function_type(base_attr.node)
+ if original_type is None:
+ if isinstance(base_attr.node, FuncDef):
+ original_type = self.function_type(base_attr.node)
+ elif isinstance(base_attr.node, Decorator):
+ original_type = self.function_type(base_attr.node.func)
+ else:
+ assert False, str(base_attr.node)
if isinstance(original_type, FunctionLike):
original = map_type_from_supertype(
method_type(original_type),
@@ -725,7 +829,6 @@ class TypeChecker(NodeVisitor[Type]):
base.name(),
defn)
else:
- assert original_type is not None
self.msg.signature_incompatible_with_supertype(
defn.name(), name, base.name(), defn)
@@ -929,6 +1032,7 @@ class TypeChecker(NodeVisitor[Type]):
# This doesn't actually provide any additional information -- multiple
# None initializers preserve the partial None type.
return
+
if is_valid_inferred_type(rvalue_type):
var = lvalue_type.var
partial_types = self.find_partial_types(var)
@@ -942,11 +1046,12 @@ class TypeChecker(NodeVisitor[Type]):
else:
var.type = None
del partial_types[var]
- # Try to infer a partial type. No need to check the return value, as
- # an error will be reported elsewhere.
- self.infer_partial_type(lvalue_type.var, lvalue, rvalue_type)
- return
- if (is_literal_none(rvalue) and
+ lvalue_type = var.type
+ else:
+ # Try to infer a partial type. No need to check the return value, as
+ # an error will be reported elsewhere.
+ self.infer_partial_type(lvalue_type.var, lvalue, rvalue_type)
+ elif (is_literal_none(rvalue) and
isinstance(lvalue, NameExpr) and
isinstance(lvalue.node, Var) and
lvalue.node.is_initialized_in_class):
@@ -1191,8 +1296,8 @@ class TypeChecker(NodeVisitor[Type]):
if self.typing_mode_weak():
self.set_inferred_type(name, lvalue, AnyType())
self.binder.assign_type(lvalue, init_type, self.binder.get_declaration(lvalue), True)
- elif isinstance(init_type, Void):
- self.check_not_void(init_type, context)
+ elif self.is_unusable_type(init_type):
+ self.check_usable_type(init_type, context)
self.set_inference_error_fallback_type(name, lvalue, init_type, context)
elif isinstance(init_type, DeletedType):
self.msg.deleted_as_rvalue(init_type, context)
@@ -1336,8 +1441,10 @@ class TypeChecker(NodeVisitor[Type]):
"""Type check a return statement."""
self.binder.breaking_out = True
if self.is_within_function():
- if self.function_stack[-1].is_generator:
- return_type = self.get_generator_return_type(self.return_types[-1])
+ defn = self.function_stack[-1]
+ if defn.is_generator:
+ return_type = self.get_generator_return_type(self.return_types[-1],
+ defn.is_coroutine)
else:
return_type = self.return_types[-1]
@@ -1348,8 +1455,8 @@ class TypeChecker(NodeVisitor[Type]):
if isinstance(typ, AnyType):
return None
- if isinstance(return_type, Void):
- # Lambdas are allowed to have a Void return.
+ if self.is_unusable_type(return_type):
+ # Lambdas are allowed to have a unusable returns.
# Functions returning a value of type None are allowed to have a Void return.
if isinstance(self.function_stack[-1], FuncExpr) or isinstance(typ, NoneTyp):
return None
@@ -1367,10 +1474,7 @@ class TypeChecker(NodeVisitor[Type]):
if (self.function_stack[-1].is_generator and isinstance(return_type, AnyType)):
return None
- if isinstance(return_type, Void):
- return None
-
- if isinstance(return_type, AnyType):
+ if isinstance(return_type, (Void, NoneTyp, AnyType)):
return None
if self.typing_mode_full():
@@ -1407,7 +1511,7 @@ class TypeChecker(NodeVisitor[Type]):
with self.binder.frame_context():
for e, b in zip(s.expr, s.body):
t = self.accept(e)
- self.check_not_void(t, e)
+ self.check_usable_type(t, e)
if_map, else_map = find_isinstance_check(
e, self.type_map,
self.typing_mode_weak()
@@ -1453,11 +1557,11 @@ class TypeChecker(NodeVisitor[Type]):
s: OperatorAssignmentStmt) -> Type:
"""Type check an operator assignment statement, e.g. x += 1."""
lvalue_type = self.accept(s.lvalue)
- method = infer_operator_assignment_method(lvalue_type, s.op)
+ 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):
+ if isinstance(s.lvalue, IndexExpr) and not inplace:
self.check_indexed_assignment(s.lvalue, s.rvalue, s.rvalue)
else:
if not is_subtype(rvalue_type, lvalue_type):
@@ -1604,15 +1708,37 @@ class TypeChecker(NodeVisitor[Type]):
def visit_for_stmt(self, s: ForStmt) -> Type:
"""Type check a for statement."""
- item_type = self.analyze_iterable_item_type(s.expr)
+ if s.is_async:
+ item_type = self.analyze_async_iterable_item_type(s.expr)
+ else:
+ item_type = self.analyze_iterable_item_type(s.expr)
self.analyze_index_variables(s.index, item_type, s)
self.accept_loop(s.body, s.else_body)
+ def analyze_async_iterable_item_type(self, expr: Node) -> Type:
+ """Analyse async iterable expression and return iterator item type."""
+ iterable = self.accept(expr)
+
+ self.check_usable_type(iterable, expr)
+
+ self.check_subtype(iterable,
+ self.named_generic_type('typing.AsyncIterable',
+ [AnyType()]),
+ expr, messages.ASYNC_ITERABLE_EXPECTED)
+
+ echk = self.expr_checker
+ method = echk.analyze_external_member_access('__aiter__', iterable, expr)
+ iterator = echk.check_call(method, [], [], expr)[0]
+ method = echk.analyze_external_member_access('__anext__', iterator, expr)
+ awaitable = echk.check_call(method, [], [], expr)[0]
+ return self.check_awaitable_expr(awaitable, expr,
+ messages.INCOMPATIBLE_TYPES_IN_ASYNC_FOR)
+
def analyze_iterable_item_type(self, expr: Node) -> Type:
"""Analyse iterable expression and return iterator item type."""
iterable = self.accept(expr)
- self.check_not_void(iterable, expr)
+ self.check_usable_type(iterable, expr)
if isinstance(iterable, TupleType):
if experiments.STRICT_OPTIONAL:
joined = UninhabitedType() # type: Type
@@ -1714,18 +1840,39 @@ class TypeChecker(NodeVisitor[Type]):
self.fail(messages.READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE, e)
def visit_with_stmt(self, s: WithStmt) -> Type:
- echk = self.expr_checker
for expr, target in zip(s.expr, s.target):
- ctx = self.accept(expr)
- enter = echk.analyze_external_member_access('__enter__', ctx, expr)
- obj = echk.check_call(enter, [], [], expr)[0]
- if target:
- self.check_assignment(target, self.temp_node(obj, expr))
- exit = echk.analyze_external_member_access('__exit__', ctx, expr)
- arg = self.temp_node(AnyType(), expr)
- echk.check_call(exit, [arg] * 3, [nodes.ARG_POS] * 3, expr)
+ if s.is_async:
+ self.check_async_with_item(expr, target)
+ else:
+ self.check_with_item(expr, target)
self.accept(s.body)
+ def check_async_with_item(self, expr: Expression, target: Expression) -> None:
+ echk = self.expr_checker
+ ctx = self.accept(expr)
+ enter = echk.analyze_external_member_access('__aenter__', ctx, expr)
+ obj = echk.check_call(enter, [], [], expr)[0]
+ obj = self.check_awaitable_expr(
+ obj, expr, messages.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER)
+ if target:
+ self.check_assignment(target, self.temp_node(obj, expr))
+ exit = echk.analyze_external_member_access('__aexit__', ctx, expr)
+ arg = self.temp_node(AnyType(), expr)
+ res = echk.check_call(exit, [arg] * 3, [nodes.ARG_POS] * 3, expr)[0]
+ self.check_awaitable_expr(
+ res, expr, messages.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT)
+
+ def check_with_item(self, expr: Expression, target: Expression) -> None:
+ echk = self.expr_checker
+ ctx = self.accept(expr)
+ enter = echk.analyze_external_member_access('__enter__', ctx, expr)
+ obj = echk.check_call(enter, [], [], expr)[0]
+ if target:
+ self.check_assignment(target, self.temp_node(obj, expr))
+ exit = echk.analyze_external_member_access('__exit__', ctx, expr)
+ arg = self.temp_node(AnyType(), expr)
+ echk.check_call(exit, [arg] * 3, [nodes.ARG_POS] * 3, expr)
+
def visit_print_stmt(self, s: PrintStmt) -> Type:
for arg in s.args:
self.accept(arg)
@@ -1746,6 +1893,11 @@ class TypeChecker(NodeVisitor[Type]):
return self.expr_checker.visit_call_expr(e)
def visit_yield_from_expr(self, e: YieldFromExpr) -> Type:
+ # NOTE: Whether `yield from` accepts an `async def` decorated
+ # with `@types.coroutine` (or `@asyncio.coroutine`) depends on
+ # whether the generator containing the `yield from` is itself
+ # thus decorated. But it accepts a generator regardless of
+ # how it's decorated.
return_type = self.return_types[-1]
subexpr_type = self.accept(e.expr, return_type)
iter_type = None # type: Type
@@ -1756,6 +1908,8 @@ class TypeChecker(NodeVisitor[Type]):
iter_type = AnyType()
elif (isinstance(subexpr_type, Instance) and
is_subtype(subexpr_type, self.named_type('typing.Iterable'))):
+ if self.is_async_def(subexpr_type) and not self.has_coroutine_decorator(return_type):
+ self.msg.yield_from_invalid_operand_type(subexpr_type, e)
iter_method_type = self.expr_checker.analyze_external_member_access(
'__iter__',
subexpr_type,
@@ -1766,13 +1920,17 @@ class TypeChecker(NodeVisitor[Type]):
iter_type, _ = self.expr_checker.check_call(iter_method_type, [], [],
context=generic_generator_type)
else:
- self.msg.yield_from_invalid_operand_type(subexpr_type, e)
- iter_type = AnyType()
+ if not (self.is_async_def(subexpr_type) and self.has_coroutine_decorator(return_type)):
+ self.msg.yield_from_invalid_operand_type(subexpr_type, e)
+ iter_type = AnyType()
+ else:
+ iter_type = self.check_awaitable_expr(subexpr_type, e,
+ messages.INCOMPATIBLE_TYPES_IN_YIELD_FROM)
# Check that the iterator's item type matches the type yielded by the Generator function
# containing this `yield from` expression.
- expected_item_type = self.get_generator_yield_type(return_type)
- actual_item_type = self.get_generator_yield_type(iter_type)
+ expected_item_type = self.get_generator_yield_type(return_type, False)
+ actual_item_type = self.get_generator_yield_type(iter_type, False)
self.check_subtype(actual_item_type, expected_item_type, e,
messages.INCOMPATIBLE_TYPES_IN_YIELD_FROM,
@@ -1781,10 +1939,41 @@ class TypeChecker(NodeVisitor[Type]):
# Determine the type of the entire yield from expression.
if (isinstance(iter_type, Instance) and
iter_type.type.fullname() == 'typing.Generator'):
- return self.get_generator_return_type(iter_type)
+ return self.get_generator_return_type(iter_type, False)
else:
# Non-Generators don't return anything from `yield from` expressions.
- return Void()
+ # However special-case Any (which might be produced by an error).
+ if isinstance(actual_item_type, AnyType):
+ return AnyType()
+ else:
+ if experiments.STRICT_OPTIONAL:
+ return NoneTyp(is_ret_type=True)
+ else:
+ return Void()
+
+ def has_coroutine_decorator(self, t: Type) -> bool:
+ """Whether t came from a function decorated with `@coroutine`."""
+ return isinstance(t, Instance) and t.type.fullname() == 'typing.AwaitableGenerator'
+
+ def is_async_def(self, t: Type) -> bool:
+ """Whether t came from a function defined using `async def`."""
+ # In check_func_def(), when we see a function decorated with
+ # `@typing.coroutine` or `@async.coroutine`, we change the
+ # return type to typing.AwaitableGenerator[...], so that its
+ # type is compatible with either Generator or Awaitable.
+ # But for the check here we need to know whether the original
+ # function (before decoration) was an `async def`. The
+ # AwaitableGenerator type conveniently preserves the original
+ # type as its 4th parameter (3rd when using 0-origin indexing
+ # :-), so that we can recover that information here.
+ # (We really need to see whether the original, undecorated
+ # function was an `async def`, which is orthogonal to its
+ # decorations.)
+ if (isinstance(t, Instance)
+ and t.type.fullname() == 'typing.AwaitableGenerator'
+ and len(t.args) >= 4):
+ t = t.args[3]
+ return isinstance(t, Instance) and t.type.fullname() == 'typing.Awaitable'
def visit_member_expr(self, e: MemberExpr) -> Type:
return self.expr_checker.visit_member_expr(e)
@@ -1851,6 +2040,9 @@ class TypeChecker(NodeVisitor[Type]):
# TODO: Perhaps return a special type used for type variables only?
return AnyType()
+ def visit_newtype_expr(self, e: NewTypeExpr) -> Type:
+ return AnyType()
+
def visit_namedtuple_expr(self, e: NamedTupleExpr) -> Type:
# TODO: Perhaps return a type object type?
return AnyType()
@@ -1896,10 +2088,9 @@ class TypeChecker(NodeVisitor[Type]):
def visit_yield_expr(self, e: YieldExpr) -> Type:
return_type = self.return_types[-1]
- expected_item_type = self.get_generator_yield_type(return_type)
+ expected_item_type = self.get_generator_yield_type(return_type, False)
if e.expr is None:
- if (not (isinstance(expected_item_type, Void) or
- isinstance(expected_item_type, AnyType))
+ if (not isinstance(expected_item_type, (Void, NoneTyp, AnyType))
and self.typing_mode_full()):
self.fail(messages.YIELD_VALUE_EXPECTED, e)
else:
@@ -1907,7 +2098,16 @@ class TypeChecker(NodeVisitor[Type]):
self.check_subtype(actual_item_type, expected_item_type, e,
messages.INCOMPATIBLE_TYPES_IN_YIELD,
'actual type', 'expected type')
- return self.get_generator_receive_type(return_type)
+ return self.get_generator_receive_type(return_type, False)
+
+ def visit_await_expr(self, e: AwaitExpr) -> Type:
+ expected_type = self.type_context[-1]
+ if expected_type is not None:
+ expected_type = self.named_generic_type('typing.Awaitable', [expected_type])
+ actual_type = self.accept(e.expr, expected_type)
+ if isinstance(actual_type, AnyType):
+ return AnyType()
+ return self.check_awaitable_expr(actual_type, e, messages.INCOMPATIBLE_TYPES_IN_AWAIT)
#
# Helpers
@@ -1916,11 +2116,13 @@ class TypeChecker(NodeVisitor[Type]):
def check_subtype(self, subtype: Type, supertype: Type, context: Context,
msg: str = messages.INCOMPATIBLE_TYPES,
subtype_label: str = None,
- supertype_label: str = None) -> None:
+ supertype_label: str = None) -> bool:
"""Generate an error if the subtype is not compatible with
supertype."""
- if not is_subtype(subtype, supertype):
- if isinstance(subtype, Void):
+ if is_subtype(subtype, supertype):
+ return True
+ else:
+ if self.is_unusable_type(subtype):
self.msg.does_not_return_value(subtype, context)
else:
extra_info = [] # type: List[str]
@@ -1933,6 +2135,7 @@ class TypeChecker(NodeVisitor[Type]):
if extra_info:
msg += ' (' + ', '.join(extra_info) + ')'
self.fail(msg, context)
+ return False
def named_type(self, name: str) -> Instance:
"""Return an instance type with type given by the name and no
@@ -2048,7 +2251,8 @@ class TypeChecker(NodeVisitor[Type]):
partial_types = self.partial_types.pop()
if not self.current_node_deferred:
for var, context in partial_types.items():
- if experiments.STRICT_OPTIONAL and cast(PartialType, var.type).type is None:
+ if (experiments.STRICT_OPTIONAL and
+ isinstance(var.type, PartialType) and var.type.type is None):
# None partial type: assume variable is intended to have type None
var.type = NoneTyp()
else:
@@ -2068,9 +2272,16 @@ class TypeChecker(NodeVisitor[Type]):
"""
return self.return_types != []
- def check_not_void(self, typ: Type, context: Context) -> None:
- """Generate an error if the type is Void."""
- if isinstance(typ, Void):
+ def is_unusable_type(self, typ: Type):
+ """Is this type an unusable type?
+
+ The two unusable types are Void and NoneTyp(is_ret_type=True).
+ """
+ return isinstance(typ, Void) or (isinstance(typ, NoneTyp) and typ.is_ret_type)
+
+ def check_usable_type(self, typ: Type, context: Context) -> None:
+ """Generate an error if the type is not a usable type."""
+ if self.is_unusable_type(typ):
self.msg.does_not_return_value(typ, context)
def temp_node(self, t: Type, context: Context = None) -> Node:
@@ -2237,11 +2448,16 @@ def find_isinstance_check(node: Node,
if is_not:
if_vars, else_vars = else_vars, if_vars
return if_vars, else_vars
- elif isinstance(node, RefExpr) and experiments.STRICT_OPTIONAL:
- # The type could be falsy, so we can't deduce anything new about the else branch
+ elif isinstance(node, RefExpr):
+ # Restrict the type of the variable to True-ish/False-ish in the if and else branches
+ # respectively
vartype = type_map[node]
- _, if_vars = conditional_type_map(node, vartype, NoneTyp(), weak=weak)
- return if_vars, {}
+ if_type = true_only(vartype)
+ else_type = false_only(vartype)
+ ref = node # type: Node
+ if_map = {ref: if_type} if not isinstance(if_type, UninhabitedType) else None
+ else_map = {ref: else_type} if not isinstance(else_type, UninhabitedType) else None
+ return if_map, else_map
elif isinstance(node, OpExpr) and node.op == 'and':
left_if_vars, left_else_vars = find_isinstance_check(
node.left,
@@ -2414,19 +2630,19 @@ def is_more_precise_signature(t: CallableType, s: CallableType) -> bool:
return is_more_precise(t.ret_type, s.ret_type)
-def infer_operator_assignment_method(type: Type, operator: str) -> str:
- """Return the method used for operator assignment for given value type.
+def infer_operator_assignment_method(type: Type, operator: str) -> Tuple[bool, str]:
+ """Determine if operator assignment on given value type is in-place, and the method name.
- For example, if operator is '+', return '__iadd__' or '__add__' depending
- on which method is supported by the type.
+ For example, if operator is '+', return (True, '__iadd__') or (False, '__add__')
+ depending on which method is supported by the type.
"""
method = nodes.op_methods[operator]
if isinstance(type, Instance):
if operator in nodes.ops_with_inplace_method:
- inplace = '__i' + method[2:]
- if type.type.has_readable_member(inplace):
- method = inplace
- return method
+ inplace_method = '__i' + method[2:]
+ if type.type.has_readable_member(inplace_method):
+ return True, inplace_method
+ return False, method
def is_valid_inferred_type(typ: Type) -> bool:
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
index 599d67a..f5b2013 100644
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -5,7 +5,8 @@ from typing import cast, Dict, List, Tuple, Callable, Union, Optional
from mypy.types import (
Type, AnyType, CallableType, Overloaded, NoneTyp, Void, TypeVarDef,
TupleType, Instance, TypeVarId, TypeVarType, ErasedType, UnionType,
- PartialType, DeletedType, UnboundType, UninhabitedType, TypeType
+ PartialType, DeletedType, UnboundType, UninhabitedType, TypeType,
+ true_only, false_only
)
from mypy.nodes import (
NameExpr, RefExpr, Var, FuncDef, OverloadedFuncDef, TypeInfo, CallExpr,
@@ -14,7 +15,7 @@ from mypy.nodes import (
TupleExpr, DictExpr, FuncExpr, SuperExpr, SliceExpr, Context,
ListComprehension, GeneratorExpr, SetExpr, MypyFile, Decorator,
ConditionalExpr, ComparisonExpr, TempNode, SetComprehension,
- DictionaryComprehension, ComplexExpr, EllipsisExpr,
+ DictionaryComprehension, ComplexExpr, EllipsisExpr, StarExpr,
TypeAliasExpr, BackquoteExpr, ARG_POS, ARG_NAMED, ARG_STAR2
)
from mypy.nodes import function_type
@@ -157,8 +158,10 @@ class ExpressionChecker:
var = cast(Var, e.callee.expr.node)
partial_types = self.chk.find_partial_types(var)
if partial_types is not None and not self.chk.current_node_deferred:
- partial_type = cast(PartialType, var.type)
- if partial_type is None or partial_type.type is None:
+ partial_type = var.type
+ if (partial_type is None or
+ not isinstance(partial_type, PartialType) or
+ partial_type.type is None):
# A partial None type -> can't infer anything.
return
typename = partial_type.type.fullname()
@@ -661,6 +664,8 @@ class ExpressionChecker:
for i, actuals in enumerate(formal_to_actual):
for actual in actuals:
arg_type = arg_types[actual]
+ if arg_type is None:
+ continue # Some kind of error was already reported.
# Check that a *arg is valid as varargs.
if (arg_kinds[actual] == nodes.ARG_STAR and
not self.is_valid_var_arg(arg_type)):
@@ -670,6 +675,11 @@ class ExpressionChecker:
messages.invalid_keyword_var_arg(arg_type, 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)
+ and tuple_counter[0] >= len(arg_type.items)
+ and arg_kinds[actual] == nodes.ARG_STAR):
+ # The tuple is exhausted. Continue with further arguments.
+ continue
actual_type = get_actual_type(arg_type, arg_kinds[actual],
tuple_counter)
check_arg(actual_type, arg_type, arg_kinds[actual],
@@ -695,7 +705,7 @@ class ExpressionChecker:
callee_type: Type, n: int, m: int, callee: CallableType,
context: Context, messages: MessageBuilder) -> None:
"""Check the type of a single argument in a call."""
- if isinstance(caller_type, Void):
+ if self.chk.is_unusable_type(caller_type):
messages.does_not_return_value(caller_type, context)
elif isinstance(caller_type, DeletedType):
messages.deleted_as_rvalue(caller_type, context)
@@ -990,7 +1000,7 @@ class ExpressionChecker:
result = sub_result
else:
# TODO: check on void needed?
- self.check_not_void(sub_result, e)
+ self.check_usable_type(sub_result, e)
result = join.join_types(result, sub_result)
return result
@@ -1002,6 +1012,20 @@ class ExpressionChecker:
else:
return nodes.op_methods[op]
+ def _check_op_for_errors(self, method: str, base_type: Type, arg: Node,
+ context: Context
+ ) -> Tuple[Tuple[Type, Type], MessageBuilder]:
+ """Type check a binary operation which maps to a method call.
+
+ Return ((result type, inferred operator method type), error message).
+ """
+ local_errors = self.msg.copy()
+ local_errors.disable_count = 0
+ result = self.check_op_local(method, base_type,
+ arg, context,
+ local_errors)
+ return result, local_errors
+
def check_op_local(self, method: str, base_type: Type, arg: Node,
context: Context, local_errors: MessageBuilder) -> Tuple[Type, Type]:
"""Type check a binary operation which maps to a method call.
@@ -1054,15 +1078,46 @@ class ExpressionChecker:
# method of the other operand instead.
rmethod = self.get_reverse_op_method(method)
arg_type = self.accept(arg)
+ base_arg_node = TempNode(base_type)
+ # In order to be consistent with showing an error about the lhs not matching if neither
+ # the lhs nor the rhs have a compatible signature, we keep track of the first error
+ # message generated when considering __rX methods and __cmp__ methods for Python 2.
+ first_error = None # type: Optional[Tuple[Tuple[Type, Type], MessageBuilder]]
if self.has_member(arg_type, rmethod):
- method_type = self.analyze_external_member_access(
- rmethod, arg_type, context)
- temp = TempNode(base_type)
- return self.check_call(method_type, [temp], [nodes.ARG_POS],
- context)
+ result, local_errors = self._check_op_for_errors(rmethod, arg_type,
+ base_arg_node, context)
+ if not local_errors.is_errors():
+ return result
+ first_error = first_error or (result, local_errors)
+ # If we've failed to find an __rX method and we're checking Python 2, check to see if
+ # there is a __cmp__ method on the lhs or on the rhs.
+ if (self.chk.options.python_version[0] == 2 and
+ method in nodes.ops_falling_back_to_cmp):
+ cmp_method = nodes.comparison_fallback_method
+ if self.has_member(base_type, cmp_method):
+ # First check the if the lhs has a __cmp__ method that works
+ result, local_errors = self._check_op_for_errors(cmp_method, base_type,
+ arg, context)
+ if not local_errors.is_errors():
+ return result
+ first_error = first_error or (result, local_errors)
+ if self.has_member(arg_type, cmp_method):
+ # Failed to find a __cmp__ method on the lhs, check if
+ # the rhs as a __cmp__ method that can operate on lhs
+ result, local_errors = self._check_op_for_errors(cmp_method, arg_type,
+ base_arg_node, context)
+ if not local_errors.is_errors():
+ return result
+ first_error = first_error or (result, local_errors)
+ if first_error:
+ # We found either a __rX method, a __cmp__ method on the base_type, or a __cmp__
+ # method on the rhs and failed match. Return the error for the first of these to
+ # fail.
+ self.msg.add_errors(first_error[1])
+ return first_error[0]
else:
- # No __rX method either. Do deferred type checking to produce
- # error message that we may have missed previously.
+ # No __rX method or __cmp__. Do deferred type checking to
+ # produce error message that we may have missed previously.
# TODO Fix type checking an expression more than once.
return self.check_op_local(method, base_type, arg, context,
self.msg)
@@ -1085,22 +1140,20 @@ class ExpressionChecker:
ctx = self.chk.type_context[-1]
left_type = self.accept(e.left, ctx)
+ assert e.op in ('and', 'or') # Checked by visit_op_expr
+
if e.op == 'and':
right_map, left_map = \
mypy.checker.find_isinstance_check(e.left, self.chk.type_map,
self.chk.typing_mode_weak())
+ restricted_left_type = false_only(left_type)
+ result_is_left = not left_type.can_be_true
elif e.op == 'or':
left_map, right_map = \
mypy.checker.find_isinstance_check(e.left, self.chk.type_map,
self.chk.typing_mode_weak())
- else:
- left_map = None
- right_map = None
-
- if left_map and e.left in left_map:
- # The type of expressions in left_map is the type they'll have if
- # the left operand is the result of the operator.
- left_type = left_map[e.left]
+ restricted_left_type = true_only(left_type)
+ result_is_left = not left_type.can_be_false
with self.chk.binder.frame_context():
if right_map:
@@ -1109,16 +1162,26 @@ class ExpressionChecker:
right_type = self.accept(e.right, left_type)
- self.check_not_void(left_type, context)
- self.check_not_void(right_type, context)
+ self.check_usable_type(left_type, context)
+ self.check_usable_type(right_type, context)
- # If either of the type maps is None that means that result cannot happen.
- # If both of the type maps are None we just have no information.
- if left_map is not None and right_map is None:
+ if right_map is None:
+ # The boolean expression is statically known to be the left value
+ assert left_map is not None # find_isinstance_check guarantees this
return left_type
- elif left_map is None and right_map is not None:
+ if left_map is None:
+ # The boolean expression is statically known to be the right value
+ assert right_map is not None # find_isinstance_check guarantees this
return right_type
- return UnionType.make_simplified_union([left_type, right_type])
+
+ if isinstance(restricted_left_type, UninhabitedType):
+ # The left operand can never be the result
+ return right_type
+ elif result_is_left:
+ # The left operand is always the result
+ return left_type
+ else:
+ return UnionType.make_simplified_union([restricted_left_type, right_type])
def check_list_multiply(self, e: OpExpr) -> Type:
"""Type check an expression of form '[...] * e'.
@@ -1141,7 +1204,7 @@ class ExpressionChecker:
operand_type = self.accept(e.expr)
op = e.op
if op == 'not':
- self.check_not_void(operand_type, e)
+ self.check_usable_type(operand_type, e)
result = self.chk.bool_type() # type: Type
elif op == '-':
method_type = self.analyze_external_member_access('__neg__',
@@ -1279,15 +1342,17 @@ class ExpressionChecker:
def visit_list_expr(self, e: ListExpr) -> Type:
"""Type check a list expression [...]."""
- return self.check_list_or_set_expr(e.items, 'builtins.list', '<list>',
- e)
+ return self.check_lst_expr(e.items, 'builtins.list', '<list>', e)
def visit_set_expr(self, e: SetExpr) -> Type:
- return self.check_list_or_set_expr(e.items, 'builtins.set', '<set>', e)
+ return self.check_lst_expr(e.items, 'builtins.set', '<set>', e)
- def check_list_or_set_expr(self, items: List[Node], fullname: str,
- tag: str, context: Context) -> Type:
+ def check_lst_expr(self, items: List[Node], fullname: str,
+ tag: str, context: Context) -> Type:
# Translate into type checking a generic function call.
+ # Used for list and set expressions, as well as for tuples
+ # containing star expressions that don't refer to a
+ # Tuple. (Note: "lst" stands for list-set-tuple. :-)
tvdef = TypeVarDef('T', -1, [], self.chk.object_type())
tv = TypeVarType(tvdef)
constructor = CallableType(
@@ -1299,8 +1364,11 @@ class ExpressionChecker:
name=tag,
variables=[tvdef])
return self.check_call(constructor,
- items,
- [nodes.ARG_POS] * len(items), context)[0]
+ [(i.expr if isinstance(i, StarExpr) else i)
+ for i in items],
+ [(nodes.ARG_STAR if isinstance(i, StarExpr) else nodes.ARG_POS)
+ for i in items],
+ context)[0]
def visit_tuple_expr(self, e: TupleExpr) -> Type:
"""Type check a tuple expression."""
@@ -1308,46 +1376,98 @@ class ExpressionChecker:
# Try to determine type context for type inference.
if isinstance(self.chk.type_context[-1], TupleType):
t = self.chk.type_context[-1]
- if len(t.items) == len(e.items):
- ctx = t
- # Infer item types.
+ ctx = t
+ # NOTE: it's possible for the context to have a different
+ # number of items than e. In that case we use those context
+ # items that match a position in e, and we'll worry about type
+ # mismatches later.
+
+ # Infer item types. Give up if there's a star expression
+ # that's not a Tuple.
items = [] # type: List[Type]
+ j = 0 # Index into ctx.items; irrelevant if ctx is None.
for i in range(len(e.items)):
item = e.items[i]
tt = None # type: Type
- if not ctx:
- tt = self.accept(item)
+ if isinstance(item, StarExpr):
+ # Special handling for star expressions.
+ # TODO: If there's a context, and item.expr is a
+ # TupleExpr, flatten it, so we can benefit from the
+ # context? Counterargument: Why would anyone write
+ # (1, *(2, 3)) instead of (1, 2, 3) except in a test?
+ tt = self.accept(item.expr)
+ self.check_usable_type(tt, e)
+ if isinstance(tt, TupleType):
+ items.extend(tt.items)
+ j += len(tt.items)
+ else:
+ # A star expression that's not a Tuple.
+ # Treat the whole thing as a variable-length tuple.
+ return self.check_lst_expr(e.items, 'builtins.tuple', '<tuple>', e)
else:
- tt = self.accept(item, ctx.items[i])
- self.check_not_void(tt, e)
- items.append(tt)
+ if not ctx or j >= len(ctx.items):
+ tt = self.accept(item)
+ else:
+ tt = self.accept(item, ctx.items[j])
+ j += 1
+ self.check_usable_type(tt, e)
+ items.append(tt)
fallback_item = join.join_type_list(items)
return TupleType(items, self.chk.named_generic_type('builtins.tuple', [fallback_item]))
def visit_dict_expr(self, e: DictExpr) -> Type:
- # Translate into type checking a generic function call.
+ """Type check a dict expression.
+
+ Translate it into a call to dict(), with provisions for **expr.
+ """
+ # Collect function arguments, watching out for **expr.
+ args = [] # type: List[Node] # Regular "key: value"
+ stargs = [] # type: List[Node] # For "**expr"
+ for key, value in e.items:
+ if key is None:
+ stargs.append(value)
+ else:
+ args.append(TupleExpr([key, value]))
+ # Define type variables (used in constructors below).
ktdef = TypeVarDef('KT', -1, [], self.chk.object_type())
vtdef = TypeVarDef('VT', -2, [], self.chk.object_type())
kt = TypeVarType(ktdef)
vt = TypeVarType(vtdef)
- # The callable type represents a function like this:
- #
- # def <unnamed>(*v: Tuple[kt, vt]) -> Dict[kt, vt]: ...
- constructor = CallableType(
- [TupleType([kt, vt], self.named_type('builtins.tuple'))],
- [nodes.ARG_STAR],
- [None],
- self.chk.named_generic_type('builtins.dict', [kt, vt]),
- self.named_type('builtins.function'),
- name='<list>',
- variables=[ktdef, vtdef])
- # Synthesize function arguments.
- args = [] # type: List[Node]
- for key, value in e.items:
- args.append(TupleExpr([key, value]))
- return self.check_call(constructor,
- args,
- [nodes.ARG_POS] * len(args), e)[0]
+ # Call dict(*args), unless it's empty and stargs is not.
+ if args or not stargs:
+ # The callable type represents a function like this:
+ #
+ # def <unnamed>(*v: Tuple[kt, vt]) -> Dict[kt, vt]: ...
+ constructor = CallableType(
+ [TupleType([kt, vt], self.named_type('builtins.tuple'))],
+ [nodes.ARG_STAR],
+ [None],
+ self.chk.named_generic_type('builtins.dict', [kt, vt]),
+ self.named_type('builtins.function'),
+ name='<list>',
+ variables=[ktdef, vtdef])
+ rv = self.check_call(constructor, args, [nodes.ARG_POS] * len(args), e)[0]
+ else:
+ # dict(...) will be called below.
+ rv = None
+ # Call rv.update(arg) for each arg in **stargs,
+ # except if rv isn't set yet, then set rv = dict(arg).
+ if stargs:
+ for arg in stargs:
+ if rv is None:
+ constructor = CallableType(
+ [self.chk.named_generic_type('typing.Mapping', [kt, vt])],
+ [nodes.ARG_POS],
+ [None],
+ self.chk.named_generic_type('builtins.dict', [kt, vt]),
+ self.named_type('builtins.function'),
+ name='<list>',
+ variables=[ktdef, vtdef])
+ rv = self.check_call(constructor, [arg], [nodes.ARG_POS], arg)[0]
+ else:
+ method = self.analyze_external_member_access('update', rv, arg)
+ self.check_call(method, [arg], [nodes.ARG_POS], arg)
+ return rv
def visit_func_expr(self, e: FuncExpr) -> Type:
"""Type check lambda expression."""
@@ -1465,59 +1585,72 @@ class ExpressionChecker:
type_name: str,
id_for_messages: str) -> Type:
"""Type check a generator expression or a list comprehension."""
- self.check_for_comp(gen)
-
- # Infer the type of the list comprehension by using a synthetic generic
- # callable type.
- tvdef = TypeVarDef('T', -1, [], self.chk.object_type())
- tv = TypeVarType(tvdef)
- constructor = CallableType(
- [tv],
- [nodes.ARG_POS],
- [None],
- self.chk.named_generic_type(type_name, [tv]),
- self.chk.named_type('builtins.function'),
- name=id_for_messages,
- variables=[tvdef])
- return self.check_call(constructor,
- [gen.left_expr], [nodes.ARG_POS], gen)[0]
+ with self.chk.binder.frame_context():
+ self.check_for_comp(gen)
+
+ # Infer the type of the list comprehension by using a synthetic generic
+ # callable type.
+ tvdef = TypeVarDef('T', -1, [], self.chk.object_type())
+ tv = TypeVarType(tvdef)
+ constructor = CallableType(
+ [tv],
+ [nodes.ARG_POS],
+ [None],
+ self.chk.named_generic_type(type_name, [tv]),
+ self.chk.named_type('builtins.function'),
+ name=id_for_messages,
+ variables=[tvdef])
+ return self.check_call(constructor,
+ [gen.left_expr], [nodes.ARG_POS], gen)[0]
def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type:
"""Type check a dictionary comprehension."""
- self.check_for_comp(e)
-
- # Infer the type of the list comprehension by using a synthetic generic
- # callable type.
- ktdef = TypeVarDef('KT', -1, [], self.chk.object_type())
- vtdef = TypeVarDef('VT', -2, [], self.chk.object_type())
- kt = TypeVarType(ktdef)
- vt = TypeVarType(vtdef)
- constructor = CallableType(
- [kt, vt],
- [nodes.ARG_POS, nodes.ARG_POS],
- [None, None],
- self.chk.named_generic_type('builtins.dict', [kt, vt]),
- self.chk.named_type('builtins.function'),
- name='<dictionary-comprehension>',
- variables=[ktdef, vtdef])
- return self.check_call(constructor,
- [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e)[0]
+ with self.chk.binder.frame_context():
+ self.check_for_comp(e)
+
+ # Infer the type of the list comprehension by using a synthetic generic
+ # callable type.
+ ktdef = TypeVarDef('KT', -1, [], self.chk.object_type())
+ vtdef = TypeVarDef('VT', -2, [], self.chk.object_type())
+ kt = TypeVarType(ktdef)
+ vt = TypeVarType(vtdef)
+ constructor = CallableType(
+ [kt, vt],
+ [nodes.ARG_POS, nodes.ARG_POS],
+ [None, None],
+ self.chk.named_generic_type('builtins.dict', [kt, vt]),
+ self.chk.named_type('builtins.function'),
+ name='<dictionary-comprehension>',
+ variables=[ktdef, vtdef])
+ return self.check_call(constructor,
+ [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e)[0]
def check_for_comp(self, e: Union[GeneratorExpr, DictionaryComprehension]) -> None:
"""Check the for_comp part of comprehensions. That is the part from 'for':
... for x in y if z
+
+ Note: This adds the type information derived from the condlists to the current binder.
"""
- with self.chk.binder.frame_context():
- for index, sequence, conditions in zip(e.indices, e.sequences,
- e.condlists):
- sequence_type = self.chk.analyze_iterable_item_type(sequence)
- self.chk.analyze_index_variables(index, sequence_type, e)
- for condition in conditions:
- self.accept(condition)
+ for index, sequence, conditions in zip(e.indices, e.sequences,
+ e.condlists):
+ sequence_type = self.chk.analyze_iterable_item_type(sequence)
+ self.chk.analyze_index_variables(index, sequence_type, e)
+ for condition in conditions:
+ self.accept(condition)
+
+ # values are only part of the comprehension when all conditions are true
+ true_map, _ = mypy.checker.find_isinstance_check(
+ condition, self.chk.type_map,
+ self.chk.typing_mode_weak()
+ )
+
+ if true_map:
+ for var, type in true_map.items():
+ self.chk.binder.push(var, type)
def visit_conditional_expr(self, e: ConditionalExpr) -> Type:
cond_type = self.accept(e.cond)
- self.check_not_void(cond_type, e)
+ self.check_usable_type(cond_type, e)
ctx = self.chk.type_context[-1]
# Gain type information from isinstance if it is there
@@ -1570,9 +1703,9 @@ class ExpressionChecker:
"""Type check a node. Alias for TypeChecker.accept."""
return self.chk.accept(node, context)
- def check_not_void(self, typ: Type, context: Context) -> None:
+ def check_usable_type(self, typ: Type, context: Context) -> None:
"""Generate an error if type is Void."""
- self.chk.check_not_void(typ, context)
+ self.chk.check_usable_type(typ, context)
def is_boolean(self, typ: Type) -> bool:
"""Is type compatible with bool?"""
@@ -1593,8 +1726,21 @@ class ExpressionChecker:
def is_valid_keyword_var_arg(self, typ: Type) -> bool:
"""Is a type valid as a **kwargs argument?"""
- return is_subtype(typ, self.chk.named_generic_type(
- 'builtins.dict', [self.named_type('builtins.str'), AnyType()]))
+ 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()]))
+ else:
+ return (
+ is_subtype(typ, self.chk.named_generic_type(
+ 'builtins.dict',
+ [self.named_type('builtins.str'),
+ AnyType()]))
+ or
+ is_subtype(typ, self.chk.named_generic_type(
+ 'builtins.dict',
+ [self.named_type('builtins.unicode'),
+ AnyType()])))
def has_non_method(self, typ: Type, member: str) -> bool:
"""Does type have a member variable / property with the given name?"""
@@ -1643,9 +1789,7 @@ def map_actuals_to_formals(caller_kinds: List[int],
argument type with the given index.
"""
ncallee = len(callee_kinds)
- map = [None] * ncallee # type: List[List[int]]
- for i in range(ncallee):
- map[i] = []
+ map = [[] for i in range(ncallee)] # type: List[List[int]]
j = 0
for i, kind in enumerate(caller_kinds):
if kind == nodes.ARG_POS:
@@ -1666,8 +1810,9 @@ def map_actuals_to_formals(caller_kinds: List[int],
if callee_kinds[j] != nodes.ARG_STAR2:
map[j].append(i)
else:
- raise NotImplementedError()
- j += 1
+ break
+ if callee_kinds[j] != nodes.ARG_STAR:
+ j += 1
else:
# Assume that it is an iterable (if it isn't, there will be
# an error later).
@@ -1676,6 +1821,8 @@ def map_actuals_to_formals(caller_kinds: List[int],
break
else:
map[j].append(i)
+ if callee_kinds[j] == nodes.ARG_STAR:
+ break
j += 1
elif kind == nodes.ARG_NAMED:
name = caller_names[i]
diff --git a/mypy/checkstrformat.py b/mypy/checkstrformat.py
index 0ff81fb..952256c 100644
--- a/mypy/checkstrformat.py
+++ b/mypy/checkstrformat.py
@@ -88,7 +88,9 @@ class StringFormatterChecker:
context: Context) -> bool:
has_star = any(specifier.has_star() for specifier in specifiers)
has_key = any(specifier.has_key() for specifier in specifiers)
- all_have_keys = all(specifier.has_key() for specifier in specifiers)
+ all_have_keys = all(
+ specifier.has_key() or specifier.type == '%' for specifier in specifiers
+ )
if has_key and has_star:
self.msg.string_interpolation_with_star_and_key(context)
@@ -145,6 +147,9 @@ class StringFormatterChecker:
mapping[key_str] = self.accept(v)
for specifier in specifiers:
+ if specifier.type == '%':
+ # %% is allowed in mappings, no checking is required
+ continue
if specifier.key not in mapping:
self.msg.key_not_in_mapping(specifier.key, replacements)
return
diff --git a/mypy/constraints.py b/mypy/constraints.py
index e9f0402..f204c02 100644
--- a/mypy/constraints.py
+++ b/mypy/constraints.py
@@ -278,6 +278,7 @@ class ConstraintBuilderVisitor(TypeVisitor[List[Constraint]]):
return self.infer_against_any(template.args)
if (isinstance(actual, TupleType) and
(is_named_instance(template, 'typing.Iterable') or
+ is_named_instance(template, 'typing.Container') or
is_named_instance(template, 'typing.Sequence') or
is_named_instance(template, 'typing.Reversible'))
and self.direction == SUPERTYPE_OF):
diff --git a/mypy/docstring.py b/mypy/docstring.py
deleted file mode 100644
index d78a81d..0000000
--- a/mypy/docstring.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""Find type annotations from a docstring.
-
-Do not actually try to parse the annotations, just return them as strings.
-
-Also recognize some common non-PEP-484 aliases such as 'a string' for 'str'
-and 'list of int' for 'List[int]'.
-
-Based on original implementation by Kyle Consalus.
-
-TODO: Decide whether it makes sense to do the heuristic analysis of aliases and natural
- language type descriptions as it's all kind of ad hoc.
-"""
-
-import re
-from typing import Optional, List, Tuple, Dict, Sequence
-from collections import OrderedDict
-
-
-_example1 = """Fetches rows from a Bigtable.
-
- Retrieves rows pertaining to the given keys from the Table instance
- represented by big_table. Silly things may happen if
- other_silly_variable is not None.
-
- Args:
- big_table: An open Bigtable Table instance.
- keys (Sequence[str]): A sequence of strings representing the key of each table row
- to fetch.
- but: if the keys are broken, we die.
- other_silly_variable (int): Another optional variable, that has a much
- longer name than the other args, and which does nothing.
- abc0 (Tuple[int, bool]): Hi.
- abc (Tuple[int, bool], optional): Hi.
-
- Returns:
- Dict[str, int]: Things.
-
- Raises:
- IOError: An error occurred accessing the bigtable.Table object.
- """
-
-
-# Regular expression that finds the argument name and type in a line such
-# as ' name (type): description'.
-PARAM_RE = re.compile(r'^\s*(?P<name>[A-Za-z_][A-Za-z_0-9]*)(\s+\((?P<type>[^)]+)\))?:')
-
-# Type strings with these brackets are rejected.
-BRACKET_RE = re.compile(r'\(|\)|\{|\}')
-
-# Support some commonly used type aliases that aren't normally valid in annotations.
-# TODO: Optionally reject these (or give a warning if these are used).
-translations = {
- 'obj': 'Any',
- 'boolean': 'bool',
- 'string': 'str',
- 'integer': 'int',
- 'number': 'float',
- 'list': 'List[Any]',
- 'set': 'Set[Any]',
- 'sequence': 'Sequence[Any]',
- 'iterable': 'Iterable[Any]',
- 'dict': 'Dict[Any, Any]',
- 'dictionary': 'Dict[Any, Any]',
- 'mapping': 'Mapping[Any, Any]',
-}
-
-# Some common types that we should recognize.
-known_types = [
- 'int', 'str', 'unicode', 'bool', 'float', 'None', 'tuple',
-]
-
-known_generic_types = [
- 'List', 'Set', 'Dict', 'Iterable', 'Sequence', 'Mapping',
-]
-
-# Some natural language patterns that we want to support in docstrings.
-known_patterns = [
- ('list of ?', 'List[?]'),
- ('set of ?', 'List[?]'),
- ('sequence of ?', 'Sequence[?]'),
- ('optional ?', 'Optional[?]'),
-]
-
-
-class DocstringTypes(object):
- def __init__(self) -> None:
- self.args = OrderedDict() # type: Dict[str, Optional[str]]
- self.rettype = None # type: Optional[str]
-
- def as_type_str(self) -> str:
- return ('(' + ','.join([v or 'Any' for v in self.args.values()]) +
- ') -> ' + (self.rettype or 'Any'))
-
- def __str__(self) -> str:
- return repr({'args': self.args, 'return': self.rettype})
-
-
-def wsprefix(s: str) -> str:
- return s[:len(s) - len(s.lstrip())]
-
-
-def scrubtype(typestr: Optional[str], only_known: bool =False) -> Optional[str]:
- if typestr is None:
- return typestr
-
- # Reject typestrs with parentheses or curly braces.
- if BRACKET_RE.search(typestr):
- return None
-
- # Reject typestrs whose square brackets don't match & those with commas outside square
- # brackets.
- bracket_level = 0
- for c in typestr:
- if c == '[':
- bracket_level += 1
- elif c == ']':
- bracket_level -= 1
- if bracket_level < 0: # Square brackets don't match
- return None
- elif c == ',' and bracket_level == 0: # A comma appears outside brackets
- return None
- if bracket_level > 0:
- return None
-
- recognized = False
- typestr = typestr.strip()
- for prefix in ('a', 'A', 'an', 'An', 'the', 'The'):
- if typestr.startswith(prefix + ' '):
- typestr = typestr[len(prefix) + 1:]
- if typestr in translations:
- typestr = translations[typestr]
- recognized = True
- if typestr in known_types:
- recognized = True
- if any(typestr.startswith(t + '[') for t in known_generic_types):
- recognized = True
- for pattern, repl in known_patterns:
- pattern = pattern.replace('?', '([a-zA-Z]+)') + '$'
- m = re.match(pattern, typestr)
- if m:
- arg = scrubtype(m.group(1), only_known=only_known)
- if arg:
- typestr = repl.replace('?', arg)
- recognized = True
- if not recognized and only_known:
- # This is potentially a type but not one of the known types.
- return None
- return typestr
-
-
-def parse_args(lines: List[str]) -> Tuple[Dict[str, str], List[str]]:
- res = OrderedDict() # type: Dict[str, str]
- indent = wsprefix(lines[0])
- while lines:
- l = lines[0]
- if l.strip() in ('Returns:', 'Raises:'):
- break
- lines = lines[1:]
- if not l or l.isspace():
- break
- if not wsprefix(l) == indent:
- continue
- m = PARAM_RE.match(l)
- if m:
- gd = m.groupdict()
- res[gd['name']] = scrubtype(gd['type'])
- return res, lines
-
-
-def parse_return(lines: List[str]) -> Tuple[Optional[str], List[str]]:
- res = None # type: Optional[str]
- while lines and lines[0].strip == '':
- lines = lines[1:]
- if lines:
- l = lines[0]
- lines = lines[1:]
- segs = l.strip().split(':', 1)
- if len(segs) >= 1:
- res = scrubtype(segs[0], only_known=(len(segs) == 1))
- return res, lines
-
-
-def parse_docstring(pds: str) -> DocstringTypes:
- ds = DocstringTypes()
- lines = pds.splitlines()
- while lines:
- first = lines[0]
- if first.strip() in ('Args:', 'Params:', 'Arguments:'):
- ds.args, lines = parse_args(lines[1:])
- break
- lines = lines[1:]
- while lines:
- first = lines[0]
- if first.strip() == 'Returns:':
- ds.rettype, lines = parse_return(lines[1:])
- break
- lines = lines[1:]
- if not ds.args:
- return None
- return ds
-
-
-if __name__ == '__main__':
- print(parse_docstring(_example1))
diff --git a/mypy/erasetype.py b/mypy/erasetype.py
index b2c1f76..3f53f75 100644
--- a/mypy/erasetype.py
+++ b/mypy/erasetype.py
@@ -5,6 +5,7 @@ from mypy.types import (
Instance, TypeVarType, CallableType, TupleType, UnionType, Overloaded, ErasedType,
PartialType, DeletedType, TypeTranslator, TypeList, UninhabitedType, TypeType
)
+from mypy import experiments
def erase_type(typ: Type) -> Type:
@@ -65,7 +66,11 @@ class EraseTypeVisitor(TypeVisitor[Type]):
def visit_callable_type(self, t: CallableType) -> Type:
# We must preserve the fallback type for overload resolution to work.
- return CallableType([], [], [], Void(), t.fallback)
+ if experiments.STRICT_OPTIONAL:
+ ret_type = NoneTyp(is_ret_type=True) # type: Type
+ else:
+ ret_type = Void()
+ return CallableType([], [], [], ret_type, t.fallback)
def visit_overloaded(self, t: Overloaded) -> Type:
return t.items()[0].accept(self)
@@ -80,31 +85,6 @@ class EraseTypeVisitor(TypeVisitor[Type]):
return TypeType(t.item.accept(self), line=t.line)
-def erase_generic_types(t: Type) -> Type:
- """Remove generic type arguments and type variables from a type.
-
- Replace all types A[...] with simply A, and all type variables
- with 'Any'.
- """
-
- if t:
- return t.accept(GenericTypeEraser())
- else:
- return None
-
-
-class GenericTypeEraser(TypeTranslator):
- """Implementation of type erasure"""
-
- # FIX: What about generic function types?
-
- def visit_type_var(self, t: TypeVarType) -> Type:
- return AnyType()
-
- def visit_instance(self, t: Instance) -> Type:
- return Instance(t.type, [], t.line)
-
-
def erase_typevars(t: Type, ids_to_erase: Optional[Container[TypeVarId]] = None) -> Type:
"""Replace all type variables in a type with any,
or just the ones in the provided collection.
diff --git a/mypy/errors.py b/mypy/errors.py
index 25f7ed0..f9da1db 100644
--- a/mypy/errors.py
+++ b/mypy/errors.py
@@ -89,7 +89,10 @@ class Errors:
# Collection of reported only_once messages.
only_once_messages = None # type: Set[str]
- def __init__(self) -> None:
+ # Set to True to suppress "In function "foo":" messages.
+ suppress_error_context = False # type: bool
+
+ def __init__(self, suppress_error_context: bool = False) -> None:
self.error_info = []
self.import_ctx = []
self.type_name = [None]
@@ -97,9 +100,10 @@ class Errors:
self.ignored_lines = OrderedDict()
self.used_ignored_lines = defaultdict(set)
self.only_once_messages = set()
+ self.suppress_error_context = suppress_error_context
def copy(self) -> 'Errors':
- new = Errors()
+ new = Errors(self.suppress_error_context)
new.file = self.file
new.import_ctx = self.import_ctx[:]
new.type_name = self.type_name[:]
@@ -202,12 +206,17 @@ class Errors:
def generate_unused_ignore_notes(self) -> None:
for file, ignored_lines in self.ignored_lines.items():
- for line in ignored_lines - self.used_ignored_lines[file]:
- # Don't use report since add_error_info will ignore the error!
- info = ErrorInfo(self.import_context(), file, None, None,
- line, 'note', "unused 'type: ignore' comment",
- False, False)
- self.error_info.append(info)
+ if not self.is_typeshed_file(file):
+ for line in ignored_lines - self.used_ignored_lines[file]:
+ # Don't use report since add_error_info will ignore the error!
+ info = ErrorInfo(self.import_context(), file, None, None,
+ line, 'note', "unused 'type: ignore' comment",
+ False, False)
+ self.error_info.append(info)
+
+ def is_typeshed_file(self, file: str) -> bool:
+ # gross, but no other clear way to tell
+ return 'typeshed' in os.path.normpath(file).split(os.sep)
def num_messages(self) -> int:
"""Return the number of generated messages."""
@@ -287,7 +296,9 @@ class Errors:
file = self.simplify_path(e.file)
# Report context within a source file.
- if (e.function_or_member != prev_function_or_member or
+ if self.suppress_error_context:
+ pass
+ elif (e.function_or_member != prev_function_or_member or
e.type != prev_type):
if e.function_or_member is None:
if e.type is None:
@@ -398,31 +409,64 @@ def remove_path_prefix(path: str, prefix: str) -> str:
# Corresponds to command-line flag --pdb.
drop_into_pdb = False
+# Corresponds to command-line flag --show-traceback.
+show_tb = False
+
def set_drop_into_pdb(flag: bool) -> None:
global drop_into_pdb
drop_into_pdb = flag
-def report_internal_error(err: Exception, file: str, line: int) -> None:
- """Display stack trace and file location for an internal error + exit."""
- if drop_into_pdb:
- import pdb # type: ignore
- pdb.post_mortem(sys.exc_info()[2])
- tb = traceback.extract_stack()[:-2]
- tb2 = traceback.extract_tb(sys.exc_info()[2])
- print('Traceback (most recent call last):')
- for s in traceback.format_list(tb + tb2):
- print(s.rstrip('\n'))
- print('{}: {}'.format(type(err).__name__, err))
- print('\n*** INTERNAL ERROR ***', file=sys.stderr)
+def set_show_tb(flag: bool) -> None:
+ global show_tb
+ show_tb = flag
+
+
+def report_internal_error(err: Exception, file: str, line: int, errors: Errors) -> None:
+ """Report internal error and exit.
+
+ This optionally starts pdb or shows a traceback.
+ """
+ # Dump out errors so far, they often provide a clue.
+ # But catch unexpected errors rendering them.
+ try:
+ for msg in errors.messages():
+ print(msg)
+ except Exception as e:
+ print("Failed to dump errors:", repr(e), file=sys.stderr)
+
+ # Compute file:line prefix for official-looking error messages.
if line:
prefix = '{}:{}'.format(file, line)
else:
prefix = file
- print('\n{}: error: Internal error --'.format(prefix),
+
+ # Print "INTERNAL ERROR" message.
+ print('{}: error: INTERNAL ERROR --'.format(prefix),
'please report a bug at https://github.com/python/mypy/issues',
file=sys.stderr)
- print('\nNOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.',
- file=sys.stderr)
- sys.exit(1)
+
+ # If requested, drop into pdb. This overrides show_tb.
+ if drop_into_pdb:
+ print('Dropping into pdb', file=sys.stderr)
+ import pdb
+ pdb.post_mortem(sys.exc_info()[2])
+
+ # If requested, print traceback, else print note explaining how to get one.
+ if not show_tb:
+ if not drop_into_pdb:
+ print('{}: note: please use --show-traceback to print a traceback '
+ 'when reporting a bug'.format(prefix),
+ file=sys.stderr)
+ else:
+ tb = traceback.extract_stack()[:-2]
+ tb2 = traceback.extract_tb(sys.exc_info()[2])
+ print('Traceback (most recent call last):')
+ for s in traceback.format_list(tb + tb2):
+ print(s.rstrip('\n'))
+ print('{}: {}'.format(type(err).__name__, err))
+ print('{}: note: use --pdb to drop into pdb'.format(prefix), file=sys.stderr)
+
+ # Exit. The caller has nothing more to say.
+ raise SystemExit(1)
diff --git a/mypy/fastparse.py b/mypy/fastparse.py
index c76e8b9..2432317 100644
--- a/mypy/fastparse.py
+++ b/mypy/fastparse.py
@@ -14,9 +14,12 @@ from mypy.nodes import (
UnaryExpr, FuncExpr, ComparisonExpr,
StarExpr, YieldFromExpr, NonlocalDecl, DictionaryComprehension,
SetComprehension, ComplexExpr, EllipsisExpr, YieldExpr, Argument,
+ AwaitExpr,
ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_STAR2
)
-from mypy.types import Type, CallableType, AnyType, UnboundType, TupleType, TypeList, EllipsisType
+from mypy.types import (
+ Type, CallableType, FunctionLike, AnyType, UnboundType, TupleType, TypeList, EllipsisType,
+)
from mypy import defaults
from mypy import experiments
from mypy.errors import Errors
@@ -242,6 +245,17 @@ class ASTConverter(ast35.NodeTransformer):
# arg? kwarg, expr* defaults)
@with_line
def visit_FunctionDef(self, n: ast35.FunctionDef) -> Node:
+ return self.do_func_def(n)
+
+ # AsyncFunctionDef(identifier name, arguments args,
+ # stmt* body, expr* decorator_list, expr? returns, string? type_comment)
+ @with_line
+ def visit_AsyncFunctionDef(self, n: ast35.AsyncFunctionDef) -> Node:
+ return self.do_func_def(n, is_coroutine=True)
+
+ def do_func_def(self, n: Union[ast35.FunctionDef, ast35.AsyncFunctionDef],
+ is_coroutine: bool = False) -> Node:
+ """Helper shared between visit_FunctionDef and visit_AsyncFunctionDef."""
args = self.transform_args(n.args, n.lineno)
arg_kinds = [arg.kind for arg in args]
@@ -270,6 +284,9 @@ class ASTConverter(ast35.NodeTransformer):
arg_types = [a.type_annotation for a in args]
return_type = TypeConverter(line=n.lineno).visit(n.returns)
+ for arg, arg_type in zip(args, arg_types):
+ self.set_type_optional(arg_type, arg.initializer)
+
if isinstance(return_type, UnboundType):
return_type.is_ret_type = True
@@ -285,6 +302,9 @@ class ASTConverter(ast35.NodeTransformer):
args,
self.as_block(n.body, n.lineno),
func_type)
+ if is_coroutine:
+ # A coroutine is also a generator, mostly for internal reasons.
+ func_def.is_generator = func_def.is_coroutine = True
if func_type is not None:
func_type.definition = func_def
func_type.line = n.lineno
@@ -312,9 +332,7 @@ class ASTConverter(ast35.NodeTransformer):
def transform_args(self, args: ast35.arguments, line: int) -> List[Argument]:
def make_argument(arg: ast35.arg, default: Optional[ast35.expr], kind: int) -> Argument:
arg_type = TypeConverter(line=line).visit(arg.annotation)
- converted_default = self.visit(default)
- self.set_type_optional(arg_type, converted_default)
- return Argument(Var(arg.arg), arg_type, converted_default, kind)
+ return Argument(Var(arg.arg), arg_type, self.visit(default), kind)
new_args = []
num_no_defaults = len(args.args) - len(args.defaults)
@@ -345,9 +363,6 @@ class ASTConverter(ast35.NodeTransformer):
return new_args
- # TODO: AsyncFunctionDef(identifier name, arguments args,
- # stmt* body, expr* decorator_list, expr? returns, string? type_comment)
-
def stringify_name(self, n: ast35.AST) -> str:
if isinstance(n, ast35.Name):
return n.id
@@ -419,7 +434,16 @@ class ASTConverter(ast35.NodeTransformer):
self.as_block(n.body, n.lineno),
self.as_block(n.orelse, n.lineno))
- # TODO: AsyncFor(expr target, expr iter, stmt* body, stmt* orelse)
+ # AsyncFor(expr target, expr iter, stmt* body, stmt* orelse)
+ @with_line
+ def visit_AsyncFor(self, n: ast35.AsyncFor) -> Node:
+ r = ForStmt(self.visit(n.target),
+ self.visit(n.iter),
+ self.as_block(n.body, n.lineno),
+ self.as_block(n.orelse, n.lineno))
+ r.is_async = True
+ return r
+
# While(expr test, stmt* body, stmt* orelse)
@with_line
def visit_While(self, n: ast35.While) -> Node:
@@ -441,7 +465,14 @@ class ASTConverter(ast35.NodeTransformer):
[self.visit(i.optional_vars) for i in n.items],
self.as_block(n.body, n.lineno))
- # TODO: AsyncWith(withitem* items, stmt* body)
+ # AsyncWith(withitem* items, stmt* body)
+ @with_line
+ def visit_AsyncWith(self, n: ast35.AsyncWith) -> Node:
+ r = WithStmt([self.visit(i.context_expr) for i in n.items],
+ [self.visit(i.optional_vars) for i in n.items],
+ self.as_block(n.body, n.lineno))
+ r.is_async = True
+ return r
# Raise(expr? exc, expr? cause)
@with_line
@@ -628,7 +659,11 @@ class ASTConverter(ast35.NodeTransformer):
iters,
ifs_list)
- # TODO: Await(expr value)
+ # Await(expr value)
+ @with_line
+ def visit_Await(self, n: ast35.Await) -> Node:
+ v = self.visit(n.value)
+ return AwaitExpr(v)
# Yield(expr? value)
@with_line
diff --git a/mypy/join.py b/mypy/join.py
index d63388d..b5de3fd 100644
--- a/mypy/join.py
+++ b/mypy/join.py
@@ -6,7 +6,7 @@ from mypy.types import (
Type, AnyType, NoneTyp, Void, TypeVisitor, Instance, UnboundType,
ErrorType, TypeVarType, CallableType, TupleType, ErasedType, TypeList,
UnionType, FunctionLike, Overloaded, PartialType, DeletedType,
- UninhabitedType, TypeType
+ UninhabitedType, TypeType, true_or_false
)
from mypy.maptype import map_instance_to_supertype
from mypy.subtypes import is_subtype, is_equivalent, is_subtype_ignoring_tvars
@@ -17,6 +17,11 @@ from mypy import experiments
def join_simple(declaration: 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):
+ # if types are restricted in different ways, use the more general versions
+ s = true_or_false(s)
+ t = true_or_false(t)
+
if isinstance(s, AnyType):
return s
@@ -60,12 +65,20 @@ def join_types(s: Type, t: Type) -> Type:
If the join does not exist, return an ErrorType instance.
"""
+ if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):
+ # if types are restricted in different ways, use the more general versions
+ s = true_or_false(s)
+ t = true_or_false(t)
+
if isinstance(s, AnyType):
return s
if isinstance(s, ErasedType):
return t
+ if isinstance(s, UnionType) and not isinstance(t, UnionType):
+ s, t = t, s
+
if isinstance(s, NoneTyp) and not isinstance(t, NoneTyp):
s, t = t, s
@@ -114,8 +127,12 @@ class TypeJoinVisitor(TypeVisitor[Type]):
if experiments.STRICT_OPTIONAL:
if isinstance(self.s, (NoneTyp, UninhabitedType)):
return t
+ elif isinstance(self.s, UnboundType):
+ return AnyType()
+ elif isinstance(self.s, Void) or isinstance(self.s, ErrorType):
+ return ErrorType()
else:
- return self.default(self.s)
+ return UnionType.make_simplified_union([self.s, t])
else:
if not isinstance(self.s, Void):
return self.s
diff --git a/mypy/main.py b/mypy/main.py
index 80ae44d..de1f628 100644
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -12,7 +12,7 @@ from mypy import defaults
from mypy import git
from mypy import experiments
from mypy.build import BuildSource, BuildResult, PYTHON_EXTENSIONS
-from mypy.errors import CompileError, set_drop_into_pdb
+from mypy.errors import CompileError, set_drop_into_pdb, set_show_tb
from mypy.options import Options, BuildType
from mypy.version import __version__
@@ -33,8 +33,8 @@ def main(script_path: str) -> None:
sources, options = process_options(sys.argv[1:])
if options.pdb:
set_drop_into_pdb(True)
- if not options.dirty_stubs:
- git.verify_git_integrity_or_abort(build.default_data_dir(bin_dir))
+ if options.show_traceback:
+ set_show_tb(True)
f = sys.stdout
try:
res = type_check_only(sources, bin_dir, options)
@@ -107,6 +107,15 @@ class SplitNamespace(argparse.Namespace):
return getattr(self._standard_namespace, name)
+def parse_version(v: str) -> Tuple[int, int]:
+ m = re.match(r'\A(\d)\.(\d+)\Z', v)
+ if m:
+ return int(m.group(1)), int(m.group(2))
+ else:
+ raise argparse.ArgumentTypeError(
+ "Invalid python version '{}' (expected format: 'x.y')".format(v))
+
+
def process_options(args: List[str]) -> Tuple[List[BuildSource], Options]:
"""Process command line arguments.
@@ -121,14 +130,6 @@ def process_options(args: List[str]) -> Tuple[List[BuildSource], Options]:
parser = argparse.ArgumentParser(prog='mypy', epilog=FOOTER,
formatter_class=help_factory)
- def parse_version(v: str) -> Tuple[int, int]:
- m = re.match(r'\A(\d)\.(\d+)\Z', v)
- if m:
- return int(m.group(1)), int(m.group(2))
- else:
- raise argparse.ArgumentTypeError(
- "Invalid python version '{}' (expected format: 'x.y')".format(v))
-
# Unless otherwise specified, arguments will be parsed directly onto an
# Options object. Options that require further processing should have
# their `dest` prefixed with `special-opts:`, which will cause them to be
@@ -139,12 +140,13 @@ def process_options(args: List[str]) -> Tuple[List[BuildSource], Options]:
version='%(prog)s ' + __version__)
parser.add_argument('--python-version', type=parse_version, metavar='x.y',
help='use Python x.y')
- parser.add_argument('--py2', dest='python_version', action='store_const',
+ parser.add_argument('--platform', action='store', metavar='PLATFORM',
+ help="typecheck special-cased code for the given OS platform "
+ "(defaults to sys.platform).")
+ parser.add_argument('-2', '--py2', dest='python_version', action='store_const',
const=defaults.PYTHON2_VERSION, help="use Python 2 mode")
parser.add_argument('-s', '--silent-imports', action='store_true',
help="don't follow imports to .py files")
- parser.add_argument('--silent', action='store_true', dest='special-opts:silent',
- help="deprecated name for --silent-imports")
parser.add_argument('--almost-silent', action='store_true',
help="like --silent-imports but reports the imports as errors")
parser.add_argument('--disallow-untyped-calls', action='store_true',
@@ -162,6 +164,9 @@ def process_options(args: List[str]) -> Tuple[List[BuildSource], Options]:
help="warn about casting an expression to its inferred type")
parser.add_argument('--warn-unused-ignores', action='store_true',
help="warn about unneeded '# type: ignore' comments")
+ parser.add_argument('--suppress-error-context', action='store_true',
+ dest='suppress_error_context',
+ help="Suppress context notes before errors")
parser.add_argument('--fast-parser', action='store_true',
help="enable experimental fast parser")
parser.add_argument('-i', '--incremental', action='store_true',
@@ -172,17 +177,30 @@ def process_options(args: List[str]) -> Tuple[List[BuildSource], Options]:
parser.add_argument('--strict-optional', action='store_true',
dest='special-opts:strict_optional',
help="enable experimental strict Optional checks")
- parser.add_argument('-f', '--dirty-stubs', action='store_true',
- help="don't warn if typeshed is out of sync")
parser.add_argument('--pdb', action='store_true', help="invoke pdb on fatal error")
- parser.add_argument('--use-python-path', action='store_true',
- dest='special-opts:use_python_path',
- help="an anti-pattern")
+ parser.add_argument('--show-traceback', '--tb', action='store_true',
+ help="show traceback on fatal error")
parser.add_argument('--stats', action='store_true', dest='dump_type_stats', help="dump stats")
parser.add_argument('--inferstats', action='store_true', dest='dump_inference_stats',
help="dump type inference stats")
parser.add_argument('--custom-typing', metavar='MODULE', dest='custom_typing_module',
help="use a custom typing module")
+ # 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)
+ # deprecated options
+ parser.add_argument('--silent', action='store_true', dest='special-opts:silent',
+ help=argparse.SUPPRESS)
+ parser.add_argument('-f', '--dirty-stubs', action='store_true',
+ dest='special-opts:dirty_stubs',
+ help=argparse.SUPPRESS)
+ parser.add_argument('--use-python-path', action='store_true',
+ dest='special-opts:use_python_path',
+ help=argparse.SUPPRESS)
report_group = parser.add_argument_group(
title='report generation',
@@ -228,11 +246,15 @@ def process_options(args: List[str]) -> Tuple[List[BuildSource], Options]:
"See https://github.com/python/mypy/issues/1411 for more discussion."
)
- # --silent is deprecated; warn about this.
+ # warn about deprecated options
if special_opts.silent:
print("Warning: --silent is deprecated; use --silent-imports",
file=sys.stderr)
options.silent_imports = True
+ if special_opts.dirty_stubs:
+ print("Warning: -f/--dirty-stubs is deprecated and no longer necessary. Mypy no longer "
+ "checks the git status of stubs.",
+ file=sys.stderr)
# Check for invalid argument combinations.
code_methods = sum(bool(c) for c in [special_opts.modules,
diff --git a/mypy/messages.py b/mypy/messages.py
index 2090107..d04050f 100644
--- a/mypy/messages.py
+++ b/mypy/messages.py
@@ -40,6 +40,11 @@ YIELD_VALUE_EXPECTED = 'Yield value expected'
INCOMPATIBLE_TYPES = 'Incompatible types'
INCOMPATIBLE_TYPES_IN_ASSIGNMENT = 'Incompatible types in assignment'
INCOMPATIBLE_REDEFINITION = 'Incompatible redefinition'
+INCOMPATIBLE_TYPES_IN_AWAIT = 'Incompatible types in await'
+INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER = 'Incompatible types in "async with" for __aenter__'
+INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT = 'Incompatible types in "async with" for __aexit__'
+INCOMPATIBLE_TYPES_IN_ASYNC_FOR = 'Incompatible types in "async for"'
+
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'
@@ -57,6 +62,7 @@ INCOMPATIBLE_KEY_TYPE = 'Incompatible dictionary key type'
INCOMPATIBLE_VALUE_TYPE = 'Incompatible dictionary value type'
NEED_ANNOTATION_FOR_VAR = 'Need type annotation for variable'
ITERABLE_EXPECTED = 'Iterable expected'
+ASYNC_ITERABLE_EXPECTED = 'AsyncIterable expected'
INCOMPATIBLE_TYPES_IN_FOR = 'Incompatible types in for statement'
INCOMPATIBLE_ARRAY_VAR_ARGS = 'Incompatible variable arguments in call'
INVALID_SLICE_INDEX = 'Slice index must be an integer or None'
@@ -314,8 +320,8 @@ class MessageBuilder:
if (isinstance(typ, Instance) and
typ.type.has_readable_member(member)):
self.fail('Member "{}" is not assignable'.format(member), context)
- elif isinstance(typ, Void):
- self.check_void(typ, context)
+ elif self.check_unusable_type(typ, context):
+ pass
elif member == '__contains__':
self.fail('Unsupported right operand type for in ({})'.format(
self.format(typ)), context)
@@ -370,9 +376,8 @@ class MessageBuilder:
Types can be Type objects or strings.
"""
- if isinstance(left_type, Void) or isinstance(right_type, Void):
- self.check_void(left_type, context)
- self.check_void(right_type, context)
+ if (self.check_unusable_type(left_type, context) or
+ self.check_unusable_type(right_type, context)):
return
left_str = ''
if isinstance(left_type, str):
@@ -395,7 +400,7 @@ class MessageBuilder:
def unsupported_left_operand(self, op: str, typ: Type,
context: Context) -> None:
- if not self.check_void(typ, context):
+ if not self.check_unusable_type(typ, context):
if self.disable_type_names:
msg = 'Unsupported left operand type for {} (some union)'.format(op)
else:
@@ -548,18 +553,17 @@ class MessageBuilder:
format(capitalize(callable_name(callee)),
callee.arg_names[index]), context)
- def does_not_return_value(self, void_type: Type, context: Context) -> None:
- """Report an error about a void type in a non-void context.
+ def does_not_return_value(self, unusable_type: Type, context: Context) -> None:
+ """Report an error about use of an unusable type.
- The first argument must be a void type. If the void type has a
- source in it, report it in the error message. This allows
- giving messages such as 'Foo does not return a value'.
+ If the type is a Void type and has a source in it, report it in the error message.
+ This allows giving messages such as 'Foo does not return a value'.
"""
- if (cast(Void, void_type)).source is None:
- self.fail('Function does not return a value', context)
- else:
+ if isinstance(unusable_type, Void) and unusable_type.source is not None:
self.fail('{} does not return a value'.format(
- capitalize((cast(Void, void_type)).source)), context)
+ capitalize((cast(Void, unusable_type)).source)), context)
+ else:
+ self.fail('Function does not return a value', context)
def deleted_as_rvalue(self, typ: DeletedType, context: Context) -> None:
"""Report an error about using an deleted type as an rvalue."""
@@ -596,7 +600,7 @@ class MessageBuilder:
def invalid_cast(self, target_type: Type, source_type: Type,
context: Context) -> None:
- if not self.check_void(source_type, context):
+ if not self.check_unusable_type(source_type, context):
self.fail('Cannot cast from {} to {}'.format(
self.format(source_type), self.format(target_type)), context)
@@ -714,11 +718,13 @@ class MessageBuilder:
def undefined_in_superclass(self, member: str, context: Context) -> None:
self.fail('"{}" undefined in superclass'.format(member), context)
- def check_void(self, typ: Type, context: Context) -> bool:
- """If type is void, report an error such as '.. does not
+ def check_unusable_type(self, typ: Type, context: Context) -> bool:
+ """If type is a type which is not meant to be used (like Void or
+ NoneTyp(is_ret_type=True)), report an error such as '.. does not
return a value' and return True. Otherwise, return False.
"""
- if isinstance(typ, Void):
+ if (isinstance(typ, Void) or
+ (isinstance(typ, NoneTyp) and typ.is_ret_type)):
self.does_not_return_value(typ, context)
return True
else:
@@ -767,7 +773,7 @@ class MessageBuilder:
def cannot_instantiate_abstract_class(self, class_name: str,
abstract_attributes: List[str],
context: Context) -> None:
- attrs = format_string_list("'%s'" % a for a in abstract_attributes[:5])
+ attrs = format_string_list("'%s'" % a for a in abstract_attributes)
self.fail("Cannot instantiate abstract class '%s' with abstract "
"attribute%s %s" % (class_name, plural_s(abstract_attributes),
attrs),
@@ -881,8 +887,10 @@ def format_string_list(s: Iterable[str]) -> str:
assert len(l) > 0
if len(l) == 1:
return l[0]
- else:
+ elif len(l) <= 5:
return '%s and %s' % (', '.join(l[:-1]), l[-1])
+ else:
+ return '%s, ... and %s (%i methods suppressed)' % (', '.join(l[:2]), l[-1], len(l) - 3)
def callable_name(type: CallableType) -> str:
diff --git a/mypy/nodes.py b/mypy/nodes.py
index fe4da0d..31dc552 100644
--- a/mypy/nodes.py
+++ b/mypy/nodes.py
@@ -416,6 +416,8 @@ class FuncItem(FuncBase):
# Is this an overload variant of function with more than one overload variant?
is_overload = False
is_generator = False # Contains a yield statement?
+ is_coroutine = False # Defined using 'async def' syntax?
+ is_awaitable_coroutine = False # Decorated with '@{typing,asyncio}.coroutine'?
is_static = False # Uses @staticmethod?
is_class = False # Uses @classmethod?
# Variants of function with type variables with values expanded
@@ -486,6 +488,7 @@ class FuncDef(FuncItem, Statement):
'is_property': self.is_property,
'is_overload': self.is_overload,
'is_generator': self.is_generator,
+ 'is_coroutine': self.is_coroutine,
'is_static': self.is_static,
'is_class': self.is_class,
'is_decorated': self.is_decorated,
@@ -507,6 +510,7 @@ class FuncDef(FuncItem, Statement):
ret.is_property = data['is_property']
ret.is_overload = data['is_overload']
ret.is_generator = data['is_generator']
+ ret.is_coroutine = data['is_coroutine']
ret.is_static = data['is_static']
ret.is_class = data['is_class']
ret.is_decorated = data['is_decorated']
@@ -798,6 +802,7 @@ class ForStmt(Statement):
expr = None # type: Expression
body = None # type: Block
else_body = None # type: Block
+ is_async = False # True if `async for ...` (PEP 492, Python 3.5)
def __init__(self, index: Expression, expr: Expression, body: Block,
else_body: Block) -> None:
@@ -908,6 +913,7 @@ class WithStmt(Statement):
expr = None # type: List[Expression]
target = None # type: List[Expression]
body = None # type: Block
+ is_async = False # True if `async with ...` (PEP 492, Python 3.5)
def __init__(self, expr: List[Expression], target: List[Expression],
body: Block) -> None:
@@ -1283,6 +1289,12 @@ op_methods = {
'in': '__contains__',
} # type: Dict[str, str]
+comparison_fallback_method = '__cmp__'
+ops_falling_back_to_cmp = {'__ne__', '__eq__',
+ '__lt__', '__le__',
+ '__gt__', '__ge__'}
+
+
ops_with_inplace_method = {
'+', '-', '*', '/', '%', '//', '**', '&', '|', '^', '<<', '>>'}
@@ -1452,7 +1464,9 @@ class DictExpr(Expression):
def __init__(self, items: List[Tuple[Expression, Expression]]) -> None:
self.items = items
- if all(x[0].literal == LITERAL_YES and x[1].literal == LITERAL_YES
+ # key is None for **item, e.g. {'a': 1, **x} has
+ # keys ['a', None] and values [1, x].
+ if all(x[0] and x[0].literal == LITERAL_YES and x[1].literal == LITERAL_YES
for x in items):
self.literal = LITERAL_YES
self.literal_hash = ('Dict',) + tuple(
@@ -1496,7 +1510,7 @@ class GeneratorExpr(Expression):
"""Generator expression ... for ... in ... [ for ... in ... ] [ if ... ]."""
left_expr = None # type: Expression
- sequences_expr = None # type: List[Expression]
+ sequences = None # type: List[Expression]
condlists = None # type: List[List[Expression]]
indices = None # type: List[Expression]
@@ -1540,7 +1554,7 @@ class DictionaryComprehension(Expression):
key = None # type: Expression
value = None # type: Expression
- sequences_expr = None # type: List[Expression]
+ sequences = None # type: List[Expression]
condlists = None # type: List[List[Expression]]
indices = None # type: List[Expression]
@@ -1705,6 +1719,30 @@ class PromoteExpr(Expression):
return visitor.visit__promote_expr(self)
+class NewTypeExpr(Expression):
+ """NewType expression NewType(...)."""
+
+ info = None # type: Optional[TypeInfo]
+
+ def __init__(self, info: Optional['TypeInfo']) -> None:
+ self.info = info
+
+ def accept(self, visitor: NodeVisitor[T]) -> T:
+ return visitor.visit_newtype_expr(self)
+
+
+class AwaitExpr(Node):
+ """Await expression (await ...)."""
+
+ expr = None # type: Node
+
+ def __init__(self, expr: Node) -> None:
+ self.expr = expr
+
+ def accept(self, visitor: NodeVisitor[T]) -> T:
+ return visitor.visit_await_expr(self)
+
+
# Constants
@@ -1781,6 +1819,9 @@ class TypeInfo(SymbolNode):
# Is this a named tuple type?
is_named_tuple = False
+ # Is this a newtype type?
+ is_newtype = False
+
# Is this a dummy from deserialization?
is_dummy = False
@@ -1957,6 +1998,7 @@ class TypeInfo(SymbolNode):
'_promote': None if self._promote is None else self._promote.serialize(),
'tuple_type': None if self.tuple_type is None else self.tuple_type.serialize(),
'is_named_tuple': self.is_named_tuple,
+ 'is_newtype': self.is_newtype,
}
return data
@@ -1979,6 +2021,7 @@ class TypeInfo(SymbolNode):
ti.tuple_type = (None if data['tuple_type'] is None
else mypy.types.TupleType.deserialize(data['tuple_type']))
ti.is_named_tuple = data['is_named_tuple']
+ ti.is_newtype = data['is_newtype']
return ti
diff --git a/mypy/options.py b/mypy/options.py
index cf1340a..9718166 100644
--- a/mypy/options.py
+++ b/mypy/options.py
@@ -1,6 +1,7 @@
from mypy import defaults
import pprint
-from typing import Any
+import sys
+from typing import Any, Optional, Tuple
class BuildType:
@@ -16,6 +17,7 @@ class Options:
# -- build options --
self.build_type = BuildType.STANDARD
self.python_version = defaults.PYTHON3_VERSION
+ self.platform = sys.platform
self.custom_typing_module = None # type: str
self.report_dirs = {} # type: Dict[str, str]
self.silent_imports = False
@@ -41,9 +43,9 @@ class Options:
# -- development options --
self.verbosity = 0 # More verbose messages (for troubleshooting)
self.pdb = False
+ self.show_traceback = False
self.dump_type_stats = False
self.dump_inference_stats = False
- self.dirty_stubs = False
# -- test options --
# Stop after the semantic analysis phase
@@ -56,6 +58,8 @@ class Options:
self.fast_parser = False
self.incremental = False
self.cache_dir = defaults.MYPY_CACHE
+ self.suppress_error_context = False # Suppress "note: In function "foo":" messages.
+ self.shadow_file = None # type: Optional[Tuple[str, str]]
def __eq__(self, other: object) -> bool:
return self.__class__ == other.__class__ and self.__dict__ == other.__dict__
diff --git a/mypy/parse.py b/mypy/parse.py
index 3007902..94d7b7d 100644
--- a/mypy/parse.py
+++ b/mypy/parse.py
@@ -8,7 +8,7 @@ import re
from typing import List, Tuple, Any, Set, cast, Union, Optional
-from mypy import lex, docstring
+from mypy import lex
from mypy.lex import (
Token, Eof, Bom, Break, Name, Colon, Dedent, IntLit, StrLit, BytesLit,
UnicodeLit, FloatLit, Op, Indent, Keyword, Punct, LexError, ComplexLit,
@@ -479,6 +479,10 @@ class Parser:
if is_error:
return None
+ if typ:
+ for arg, arg_type in zip(args, typ.arg_types):
+ self.set_type_optional(arg_type, arg.initializer)
+
if typ and isinstance(typ.ret_type, UnboundType):
typ.ret_type.is_ret_type = True
@@ -782,8 +786,6 @@ class Parser:
else:
kind = nodes.ARG_POS
- self.set_type_optional(type, initializer)
-
return Argument(variable, type, initializer, kind), require_named
def set_type_optional(self, type: Type, initializer: Node) -> None:
@@ -859,17 +861,6 @@ class Parser:
type = self.parse_type_comment(brk, signature=True)
self.expect_indent()
stmt_list = [] # type: List[Node]
- if allow_type:
- cur = self.current()
- if type is None and isinstance(cur, StrLit):
- ds = docstring.parse_docstring(cur.parsed())
- if ds and False: # TODO: Enable when this is working.
- try:
- type = parse_str_as_signature(ds.as_type_str(), cur.line)
- except TypeParseError:
- # We don't require docstrings to be actually correct.
- # TODO: Report something here.
- type = None
while (not isinstance(self.current(), Dedent) and
not isinstance(self.current(), Eof)):
try:
@@ -957,6 +948,10 @@ class Parser:
stmt = self.parse_exec_stmt()
else:
stmt = self.parse_expression_or_assignment()
+ if ts == 'async' and self.current_str() == 'def':
+ self.parse_error_at(self.current(),
+ reason='Use --fast-parser to parse code using "async def"')
+ raise ParseError()
if stmt is not None:
stmt.set_line(t)
return stmt, is_simple
diff --git a/mypy/report.py b/mypy/report.py
index f506781..180bbe6 100644
--- a/mypy/report.py
+++ b/mypy/report.py
@@ -76,7 +76,9 @@ class LineCountReporter(AbstractReporter):
stats.ensure_dir_exists(output_dir)
def on_file(self, tree: MypyFile, type_map: Dict[Node, Type]) -> None:
- physical_lines = len(open(tree.path).readlines())
+ # Count physical lines. This assumes the file's encoding is a
+ # superset of ASCII (or at least uses \n in its line endings).
+ physical_lines = len(open(tree.path, 'rb').readlines())
func_counter = FuncCounterVisitor()
tree.accept(func_counter)
diff --git a/mypy/semanal.py b/mypy/semanal.py
index c8ae5e2..9956105 100644
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -43,6 +43,7 @@ TODO: Check if the third pass slows down type checking significantly.
traverse the entire AST.
"""
+import sys
from typing import (
List, Dict, Set, Tuple, cast, Any, overload, TypeVar, Union, Optional, Callable
)
@@ -57,21 +58,21 @@ from mypy.nodes import (
GlobalDecl, SuperExpr, DictExpr, CallExpr, RefExpr, OpExpr, UnaryExpr,
SliceExpr, CastExpr, RevealTypeExpr, TypeApplication, Context, SymbolTable,
SymbolTableNode, BOUND_TVAR, UNBOUND_TVAR, ListComprehension, GeneratorExpr,
- FuncExpr, MDEF, FuncBase, Decorator, SetExpr, TypeVarExpr,
+ FuncExpr, MDEF, FuncBase, Decorator, SetExpr, TypeVarExpr, NewTypeExpr,
StrExpr, BytesExpr, PrintStmt, ConditionalExpr, PromoteExpr,
ComparisonExpr, StarExpr, ARG_POS, ARG_NAMED, MroError, type_aliases,
YieldFromExpr, NamedTupleExpr, NonlocalDecl,
SetComprehension, DictionaryComprehension, TYPE_ALIAS, TypeAliasExpr,
- YieldExpr, ExecStmt, Argument, BackquoteExpr, ImportBase, COVARIANT, CONTRAVARIANT,
+ YieldExpr, ExecStmt, Argument, BackquoteExpr, ImportBase, AwaitExpr,
IntExpr, FloatExpr, UnicodeExpr,
- INVARIANT, UNBOUND_IMPORTED
+ COVARIANT, CONTRAVARIANT, INVARIANT, UNBOUND_IMPORTED, LITERAL_YES,
)
from mypy.visitor import NodeVisitor
from mypy.traverser import TraverserVisitor
from mypy.errors import Errors, report_internal_error
from mypy.types import (
NoneTyp, CallableType, Overloaded, Instance, Type, TypeVarType, AnyType,
- FunctionLike, UnboundType, TypeList, ErrorType, TypeVarDef,
+ FunctionLike, UnboundType, TypeList, ErrorType, TypeVarDef, Void,
replace_leading_arg_type, TupleType, UnionType, StarType, EllipsisType
)
from mypy.nodes import function_type, implicit_module_attrs
@@ -314,6 +315,13 @@ class SemanticAnalyzer(NodeVisitor):
# Second phase of analysis for function.
self.errors.push_function(defn.name())
self.analyze_function(defn)
+ if defn.is_coroutine and isinstance(defn.type, CallableType):
+ # A coroutine defined as `async def foo(...) -> T: ...`
+ # has external return type `Awaitable[T]`.
+ defn.type = defn.type.copy_modified(
+ ret_type=Instance(
+ self.named_type_or_none('typing.Awaitable').type,
+ [defn.type.ret_type]))
self.errors.pop_function()
def prepare_method_signature(self, func: FuncDef) -> None:
@@ -761,6 +769,8 @@ class SemanticAnalyzer(NodeVisitor):
defn.info.tuple_type = base
base_types.append(base.fallback)
elif isinstance(base, Instance):
+ if base.type.is_newtype:
+ self.fail("Cannot subclass NewType", defn)
base_types.append(base)
elif isinstance(base, AnyType):
defn.info.fallback_to_any = True
@@ -778,9 +788,10 @@ class SemanticAnalyzer(NodeVisitor):
# the bases of defn include classes imported from other
# modules in an import loop. We'll recompute it in ThirdPass.
if not self.verify_base_classes(defn):
- defn.info.mro = []
+ # Give it an MRO consisting of just the class itself and object.
+ defn.info.mro = [defn.info, self.object_type().type]
return
- calculate_class_mro(defn, self.fail)
+ calculate_class_mro(defn, self.fail_blocker)
# If there are cyclic imports, we may be missing 'object' in
# the MRO. Fix MRO if needed.
if defn.info.mro and defn.info.mro[-1].fullname() != 'builtins.object':
@@ -804,16 +815,16 @@ class SemanticAnalyzer(NodeVisitor):
for base in info.bases:
baseinfo = base.type
if self.is_base_class(info, baseinfo):
- self.fail('Cycle in inheritance hierarchy', defn)
+ self.fail('Cycle in inheritance hierarchy', defn, blocker=True)
# Clear bases to forcefully get rid of the cycle.
info.bases = []
if baseinfo.fullname() == 'builtins.bool':
self.fail("'%s' is not a valid base class" %
- baseinfo.name(), defn)
+ baseinfo.name(), defn, blocker=True)
return False
dup = find_duplicate(info.direct_base_classes())
if dup:
- self.fail('Duplicate base class "%s"' % dup.name(), defn)
+ self.fail('Duplicate base class "%s"' % dup.name(), defn, blocker=True)
return False
return True
@@ -997,7 +1008,10 @@ class SemanticAnalyzer(NodeVisitor):
def add_unknown_symbol(self, name: str, context: Context) -> None:
var = Var(name)
- var._fullname = self.qualified_name(name)
+ if self.type:
+ var._fullname = self.type.fullname() + "." + name
+ else:
+ var._fullname = self.qualified_name(name)
var.is_ready = True
var.type = AnyType()
self.add_symbol(name, SymbolTableNode(GDEF, var, self.cur_mod_id), context)
@@ -1071,6 +1085,7 @@ class SemanticAnalyzer(NodeVisitor):
for lvalue in s.lvalues:
self.store_declared_types(lvalue, s.type)
self.check_and_set_up_type_alias(s)
+ self.process_newtype_declaration(s)
self.process_typevar_declaration(s)
self.process_namedtuple_definition(s)
@@ -1277,6 +1292,118 @@ class SemanticAnalyzer(NodeVisitor):
# This has been flagged elsewhere as an error, so just ignore here.
pass
+ def process_newtype_declaration(self, s: AssignmentStmt) -> None:
+ """Check if s declares a NewType; if yes, store it in symbol table."""
+ # Extract and check all information from newtype declaration
+ name, call = self.analyze_newtype_declaration(s)
+ if name is None or call is None:
+ return
+
+ old_type = self.check_newtype_args(name, call, s)
+ if old_type is None:
+ return
+
+ # Create the corresponding class definition if the aliased type is subtypeable
+ if isinstance(old_type, TupleType):
+ newtype_class_info = self.build_newtype_typeinfo(name, old_type, old_type.fallback)
+ newtype_class_info.tuple_type = old_type
+ elif isinstance(old_type, Instance):
+ newtype_class_info = self.build_newtype_typeinfo(name, old_type, old_type)
+ else:
+ message = "Argument 2 to NewType(...) must be subclassable (got {})"
+ self.fail(message.format(old_type), s)
+ return
+
+ # If so, add it to the symbol table.
+ node = self.lookup(name, s)
+ if node is None:
+ self.fail("Could not find {} in current namespace".format(name), s)
+ return
+ # TODO: why does NewType work in local scopes despite always being of kind GDEF?
+ node.kind = GDEF
+ node.node = newtype_class_info
+ call.analyzed = NewTypeExpr(newtype_class_info).set_line(call.line)
+
+ def analyze_newtype_declaration(self,
+ s: AssignmentStmt) -> Tuple[Optional[str], Optional[CallExpr]]:
+ """Return the NewType call expression if `s` is a newtype declaration or None otherwise."""
+ name, call = None, None
+ if (len(s.lvalues) == 1
+ and isinstance(s.lvalues[0], NameExpr)
+ and isinstance(s.rvalue, CallExpr)
+ and isinstance(s.rvalue.callee, RefExpr)
+ and s.rvalue.callee.fullname == 'typing.NewType'):
+ lvalue = s.lvalues[0]
+ name = s.lvalues[0].name
+ if not lvalue.is_def:
+ if s.type:
+ self.fail("Cannot declare the type of a NewType declaration", s)
+ else:
+ self.fail("Cannot redefine '%s' as a NewType" % name, s)
+
+ # This dummy NewTypeExpr marks the call as sufficiently analyzed; it will be
+ # overwritten later with a fully complete NewTypeExpr if there are no other
+ # errors with the NewType() call.
+ call = s.rvalue
+ call.analyzed = NewTypeExpr(None).set_line(call.line)
+
+ return name, call
+
+ def check_newtype_args(self, name: str, call: CallExpr, context: Context) -> Optional[Type]:
+ has_failed = False
+ args, arg_kinds = call.args, call.arg_kinds
+ if len(args) != 2 or arg_kinds[0] != ARG_POS or arg_kinds[1] != ARG_POS:
+ self.fail("NewType(...) expects exactly two positional arguments", context)
+ return None
+
+ # Check first argument
+ if not isinstance(args[0], (StrExpr, BytesExpr, UnicodeExpr)):
+ self.fail("Argument 1 to NewType(...) must be a string literal", context)
+ has_failed = True
+ elif cast(StrExpr, call.args[0]).value != name:
+ self.fail("Argument 1 to NewType(...) does not match variable name", context)
+ has_failed = True
+
+ # Check second argument
+ try:
+ unanalyzed_type = expr_to_unanalyzed_type(call.args[1])
+ except TypeTranslationError:
+ self.fail("Argument 2 to NewType(...) must be a valid type", context)
+ 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:
+ class_def = ClassDef(name, Block([]))
+ class_def.fullname = self.qualified_name(name)
+
+ symbols = SymbolTable()
+ info = TypeInfo(symbols, class_def)
+ info.mro = [info] + base_type.type.mro
+ info.bases = [base_type]
+ info.is_newtype = True
+
+ # Add __init__ method
+ args = [Argument(Var('cls'), NoneTyp(), None, ARG_POS),
+ self.make_argument('item', old_type)]
+ signature = CallableType(
+ arg_types=[cast(Type, None), old_type],
+ arg_kinds=[arg.kind for arg in args],
+ arg_names=['self', 'item'],
+ ret_type=old_type,
+ fallback=self.named_type('__builtins__.function'),
+ name=name)
+ init_func = FuncDef('__init__', args, Block([]), typ=signature)
+ init_func.info = info
+ symbols['__init__'] = SymbolTableNode(MDEF, init_func)
+
+ return info
+
def process_typevar_declaration(self, s: AssignmentStmt) -> None:
"""Check if s declares a TypeVar; it yes, store it in symbol table."""
call = self.get_typevar_declaration(s)
@@ -1320,7 +1447,8 @@ class SemanticAnalyzer(NodeVisitor):
if len(call.args) < 1:
self.fail("Too few arguments for TypeVar()", context)
return False
- if not isinstance(call.args[0], (StrExpr, BytesExpr)) or not call.arg_kinds[0] == ARG_POS:
+ if (not isinstance(call.args[0], (StrExpr, BytesExpr, UnicodeExpr))
+ or not call.arg_kinds[0] == ARG_POS):
self.fail("TypeVar() expects a string literal as first argument", context)
return False
if cast(StrExpr, call.args[0]).value != name:
@@ -1466,13 +1594,14 @@ class SemanticAnalyzer(NodeVisitor):
return self.fail_namedtuple_arg("Too many arguments for namedtuple()", call)
if call.arg_kinds != [ARG_POS, ARG_POS]:
return self.fail_namedtuple_arg("Unexpected arguments to namedtuple()", call)
- if not isinstance(args[0], (StrExpr, BytesExpr)):
+ if not isinstance(args[0], (StrExpr, BytesExpr, UnicodeExpr)):
return self.fail_namedtuple_arg(
"namedtuple() expects a string literal as the first argument", call)
types = [] # type: List[Type]
ok = True
if not isinstance(args[1], ListExpr):
- if fullname == 'collections.namedtuple' and isinstance(args[1], (StrExpr, BytesExpr)):
+ if (fullname == 'collections.namedtuple'
+ and isinstance(args[1], (StrExpr, BytesExpr, UnicodeExpr))):
str_expr = cast(StrExpr, args[1])
items = str_expr.value.split()
else:
@@ -1482,7 +1611,8 @@ class SemanticAnalyzer(NodeVisitor):
listexpr = args[1]
if fullname == 'collections.namedtuple':
# The fields argument contains just names, with implicit Any types.
- if any(not isinstance(item, (StrExpr, BytesExpr)) for item in listexpr.items):
+ if any(not isinstance(item, (StrExpr, BytesExpr, UnicodeExpr))
+ for item in listexpr.items):
return self.fail_namedtuple_arg("String literal expected as namedtuple() item",
call)
items = [cast(StrExpr, item).value for item in listexpr.items]
@@ -1503,7 +1633,7 @@ class SemanticAnalyzer(NodeVisitor):
return self.fail_namedtuple_arg("Invalid NamedTuple field definition",
item)
name, type_node = item.items
- if isinstance(name, (StrExpr, BytesExpr)):
+ if isinstance(name, (StrExpr, BytesExpr, UnicodeExpr)):
items.append(name.value)
else:
return self.fail_namedtuple_arg("Invalid NamedTuple() field name", item)
@@ -1586,8 +1716,10 @@ class SemanticAnalyzer(NodeVisitor):
removed.append(i)
dec.func.is_abstract = True
self.check_decorated_function_is_method('abstractmethod', dec)
- elif refers_to_fullname(d, 'asyncio.tasks.coroutine'):
+ elif (refers_to_fullname(d, 'asyncio.coroutines.coroutine') or
+ refers_to_fullname(d, 'types.coroutine')):
removed.append(i)
+ dec.func.is_awaitable_coroutine = True
elif refers_to_fullname(d, 'builtins.staticmethod'):
removed.append(i)
dec.func.is_static = True
@@ -1687,7 +1819,9 @@ class SemanticAnalyzer(NodeVisitor):
self.fail("'continue' outside loop", s, True, blocker=True)
def visit_if_stmt(self, s: IfStmt) -> None:
- infer_reachability_of_if_statement(s, pyversion=self.options.python_version)
+ infer_reachability_of_if_statement(s,
+ pyversion=self.options.python_version,
+ platform=self.options.platform)
for i in range(len(s.expr)):
s.expr[i].accept(self)
self.visit_block(s.body[i])
@@ -1789,23 +1923,31 @@ class SemanticAnalyzer(NodeVisitor):
def visit_tuple_expr(self, expr: TupleExpr) -> None:
for item in expr.items:
+ if isinstance(item, StarExpr):
+ item.valid = True
item.accept(self)
def visit_list_expr(self, expr: ListExpr) -> None:
for item in expr.items:
+ if isinstance(item, StarExpr):
+ item.valid = True
item.accept(self)
def visit_set_expr(self, expr: SetExpr) -> None:
for item in expr.items:
+ if isinstance(item, StarExpr):
+ item.valid = True
item.accept(self)
def visit_dict_expr(self, expr: DictExpr) -> None:
for key, value in expr.items:
- key.accept(self)
+ if key is not None:
+ key.accept(self)
value.accept(self)
def visit_star_expr(self, expr: StarExpr) -> None:
if not expr.valid:
+ # XXX TODO Change this error message
self.fail('Can use starred expression only as assignment target', expr)
else:
expr.expr.accept(self)
@@ -1814,7 +1956,10 @@ class SemanticAnalyzer(NodeVisitor):
if not self.is_func_scope(): # not sure
self.fail("'yield from' outside function", e, True, blocker=True)
else:
- self.function_stack[-1].is_generator = True
+ if self.function_stack[-1].is_coroutine:
+ self.fail("'yield from' in async function", e, True, blocker=True)
+ else:
+ self.function_stack[-1].is_generator = True
if e.expr:
e.expr.accept(self)
@@ -2067,10 +2212,20 @@ class SemanticAnalyzer(NodeVisitor):
if not self.is_func_scope():
self.fail("'yield' outside function", expr, True, blocker=True)
else:
- self.function_stack[-1].is_generator = True
+ if self.function_stack[-1].is_coroutine:
+ self.fail("'yield' in async function", expr, True, blocker=True)
+ else:
+ self.function_stack[-1].is_generator = True
if expr.expr:
expr.expr.accept(self)
+ def visit_await_expr(self, expr: AwaitExpr) -> None:
+ if not self.is_func_scope():
+ self.fail("'await' outside function", expr)
+ elif not self.function_stack[-1].is_coroutine:
+ self.fail("'await' outside coroutine ('async def')", expr)
+ expr.expr.accept(self)
+
#
# Helpers
#
@@ -2094,7 +2249,7 @@ class SemanticAnalyzer(NodeVisitor):
return None
# 2. Class attributes (if within class definition)
if self.is_class_scope() and name in self.type.names:
- return self.type[name]
+ return self.type.names[name]
# 3. Local (function) scopes
for table in reversed(self.locals):
if table is not None and name in table:
@@ -2288,6 +2443,9 @@ class SemanticAnalyzer(NodeVisitor):
return
self.errors.report(ctx.get_line(), msg, blocker=blocker)
+ def fail_blocker(self, msg: str, ctx: Context) -> None:
+ self.fail(msg, ctx, blocker=True)
+
def note(self, msg: str, ctx: Context) -> None:
if (not self.options.check_untyped_defs and
self.function_stack and
@@ -2305,7 +2463,7 @@ class SemanticAnalyzer(NodeVisitor):
try:
node.accept(self)
except Exception as err:
- report_internal_error(err, self.errors.file, node.line)
+ report_internal_error(err, self.errors.file, node.line, self.errors)
class FirstPass(NodeVisitor):
@@ -2317,6 +2475,7 @@ class FirstPass(NodeVisitor):
def __init__(self, sem: SemanticAnalyzer) -> None:
self.sem = sem
self.pyversion = sem.options.python_version
+ self.platform = sem.options.platform
def analyze(self, file: MypyFile, fnam: str, mod_id: str) -> None:
"""Perform the first analysis pass.
@@ -2485,7 +2644,7 @@ class FirstPass(NodeVisitor):
self.sem.add_symbol(d.var.name(), SymbolTableNode(GDEF, d.var), d)
def visit_if_stmt(self, s: IfStmt) -> None:
- infer_reachability_of_if_statement(s, pyversion=self.pyversion)
+ infer_reachability_of_if_statement(s, pyversion=self.pyversion, platform=self.platform)
for node in s.body:
node.accept(self)
if s.else_body:
@@ -2517,7 +2676,7 @@ class ThirdPass(TraverserVisitor):
try:
node.accept(self)
except Exception as err:
- report_internal_error(err, self.errors.file, node.line)
+ report_internal_error(err, self.errors.file, node.line, self.errors)
def visit_block(self, b: Block) -> None:
if b.is_unreachable:
@@ -2538,7 +2697,7 @@ class ThirdPass(TraverserVisitor):
# 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)
+ calculate_class_mro(tdef, self.fail_blocker)
super().visit_class_def(tdef)
def visit_decorator(self, dec: Decorator) -> None:
@@ -2614,9 +2773,12 @@ class ThirdPass(TraverserVisitor):
analyzer = TypeAnalyserPass3(self.fail)
type.accept(analyzer)
- def fail(self, msg: str, ctx: Context) -> None:
+ def fail(self, msg: str, ctx: Context, *, blocker: bool = False) -> None:
self.errors.report(ctx.get_line(), msg)
+ def fail_blocker(self, msg: str, ctx: Context) -> None:
+ self.fail(msg, ctx, blocker=True)
+
def builtin_type(self, name: str, args: List[Type] = None) -> Instance:
names = self.modules['builtins']
sym = names.names[name]
@@ -2719,9 +2881,10 @@ def remove_imported_names_from_symtable(names: SymbolTable,
def infer_reachability_of_if_statement(s: IfStmt,
- pyversion: Tuple[int, int]) -> None:
+ pyversion: Tuple[int, int],
+ platform: str) -> None:
for i in range(len(s.expr)):
- result = infer_if_condition_value(s.expr[i], pyversion)
+ result = infer_if_condition_value(s.expr[i], pyversion, platform)
if result == ALWAYS_FALSE:
# The condition is always false, so we skip the if/elif body.
mark_block_unreachable(s.body[i])
@@ -2735,7 +2898,7 @@ def infer_reachability_of_if_statement(s: IfStmt,
break
-def infer_if_condition_value(expr: Node, pyversion: Tuple[int, int]) -> int:
+def infer_if_condition_value(expr: Node, pyversion: Tuple[int, int], platform: str) -> int:
"""Infer whether if condition is always true/false.
Return ALWAYS_TRUE if always true, ALWAYS_FALSE if always false,
@@ -2748,17 +2911,22 @@ def infer_if_condition_value(expr: Node, pyversion: Tuple[int, int]) -> int:
if alias.op == 'not':
expr = alias.expr
negated = True
+ result = TRUTH_VALUE_UNKNOWN
if isinstance(expr, NameExpr):
name = expr.name
elif isinstance(expr, MemberExpr):
name = expr.name
- result = TRUTH_VALUE_UNKNOWN
- if name == 'PY2':
- result = ALWAYS_TRUE if pyversion[0] == 2 else ALWAYS_FALSE
- elif name == 'PY3':
- result = ALWAYS_TRUE if pyversion[0] == 3 else ALWAYS_FALSE
- elif name == 'MYPY':
- result = ALWAYS_TRUE
+ else:
+ result = consider_sys_version_info(expr, pyversion)
+ if result == TRUTH_VALUE_UNKNOWN:
+ result = consider_sys_platform(expr, platform)
+ if result == TRUTH_VALUE_UNKNOWN:
+ if name == 'PY2':
+ result = ALWAYS_TRUE if pyversion[0] == 2 else ALWAYS_FALSE
+ elif name == 'PY3':
+ result = ALWAYS_TRUE if pyversion[0] == 3 else ALWAYS_FALSE
+ elif name == 'MYPY':
+ result = ALWAYS_TRUE
if negated:
if result == ALWAYS_TRUE:
result = ALWAYS_FALSE
@@ -2767,6 +2935,157 @@ def infer_if_condition_value(expr: Node, pyversion: Tuple[int, int]) -> int:
return result
+def consider_sys_version_info(expr: Node, pyversion: Tuple[int, ...]) -> int:
+ """Consider whether expr is a comparison involving sys.version_info.
+
+ Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN.
+ """
+ # Cases supported:
+ # - sys.version_info[<int>] <compare_op> <int>
+ # - sys.version_info[:<int>] <compare_op> <tuple_of_n_ints>
+ # - sys.version_info <compare_op> <tuple_of_1_or_2_ints>
+ # (in this case <compare_op> must be >, >=, <, <=, but cannot be ==, !=)
+ if not isinstance(expr, ComparisonExpr):
+ return TRUTH_VALUE_UNKNOWN
+ # Let's not yet support chained comparisons.
+ if len(expr.operators) > 1:
+ return TRUTH_VALUE_UNKNOWN
+ op = expr.operators[0]
+ if op not in ('==', '!=', '<=', '>=', '<', '>'):
+ return TRUTH_VALUE_UNKNOWN
+ thing = contains_int_or_tuple_of_ints(expr.operands[1])
+ if thing is None:
+ return TRUTH_VALUE_UNKNOWN
+ index = contains_sys_version_info(expr.operands[0])
+ if isinstance(index, int) and isinstance(thing, int):
+ # sys.version_info[i] <compare_op> k
+ if 0 <= index <= 1:
+ return fixed_comparison(pyversion[index], op, thing)
+ else:
+ return TRUTH_VALUE_UNKNOWN
+ elif isinstance(index, tuple) and isinstance(thing, tuple):
+ # Why doesn't mypy see that index can't be None here?
+ lo, hi = cast(tuple, index)
+ if lo is None:
+ lo = 0
+ if hi is None:
+ hi = 2
+ if 0 <= lo < hi <= 2:
+ val = pyversion[lo:hi]
+ if len(val) == len(thing) or len(val) > len(thing) and op not in ('==', '!='):
+ return fixed_comparison(val, op, thing)
+ return TRUTH_VALUE_UNKNOWN
+
+
+def consider_sys_platform(expr: Node, platform: str) -> int:
+ """Consider whether expr is a comparison involving sys.platform.
+
+ Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN.
+ """
+ # Cases supported:
+ # - sys.platform == 'posix'
+ # - sys.platform != 'win32'
+ # - sys.platform.startswith('win')
+ if isinstance(expr, ComparisonExpr):
+ # Let's not yet support chained comparisons.
+ if len(expr.operators) > 1:
+ return TRUTH_VALUE_UNKNOWN
+ op = expr.operators[0]
+ if op not in ('==', '!='):
+ return TRUTH_VALUE_UNKNOWN
+ if not is_sys_attr(expr.operands[0], 'platform'):
+ return TRUTH_VALUE_UNKNOWN
+ right = expr.operands[1]
+ if not isinstance(right, (StrExpr, UnicodeExpr)):
+ return TRUTH_VALUE_UNKNOWN
+ return fixed_comparison(platform, op, right.value)
+ elif isinstance(expr, CallExpr):
+ if not isinstance(expr.callee, MemberExpr):
+ return TRUTH_VALUE_UNKNOWN
+ if len(expr.args) != 1 or not isinstance(expr.args[0], (StrExpr, UnicodeExpr)):
+ return TRUTH_VALUE_UNKNOWN
+ if not is_sys_attr(expr.callee.expr, 'platform'):
+ return TRUTH_VALUE_UNKNOWN
+ if expr.callee.name != 'startswith':
+ return TRUTH_VALUE_UNKNOWN
+ if platform.startswith(expr.args[0].value):
+ return ALWAYS_TRUE
+ else:
+ return ALWAYS_FALSE
+ else:
+ return TRUTH_VALUE_UNKNOWN
+
+
+Targ = TypeVar('Targ', int, str, Tuple[int, ...])
+
+
+def fixed_comparison(left: Targ, op: str, right: Targ) -> int:
+ rmap = {False: ALWAYS_FALSE, True: ALWAYS_TRUE}
+ if op == '==':
+ return rmap[left == right]
+ if op == '!=':
+ return rmap[left != right]
+ if op == '<=':
+ return rmap[left <= right]
+ if op == '>=':
+ return rmap[left >= right]
+ if op == '<':
+ return rmap[left < right]
+ if op == '>':
+ return rmap[left > right]
+ return TRUTH_VALUE_UNKNOWN
+
+
+def contains_int_or_tuple_of_ints(expr: Node) -> Union[None, int, Tuple[int], Tuple[int, ...]]:
+ if isinstance(expr, IntExpr):
+ return expr.value
+ if isinstance(expr, TupleExpr):
+ if expr.literal == LITERAL_YES:
+ thing = []
+ for x in expr.items:
+ if not isinstance(x, IntExpr):
+ return None
+ thing.append(x.value)
+ return tuple(thing)
+ return None
+
+
+def contains_sys_version_info(expr: Node) -> Union[None, int, Tuple[Optional[int], Optional[int]]]:
+ if is_sys_attr(expr, 'version_info'):
+ return (None, None) # Same as sys.version_info[:]
+ if isinstance(expr, IndexExpr) and is_sys_attr(expr.base, 'version_info'):
+ index = expr.index
+ if isinstance(index, IntExpr):
+ return index.value
+ if isinstance(index, SliceExpr):
+ if index.stride is not None:
+ if not isinstance(index.stride, IntExpr) or index.stride.value != 1:
+ return None
+ begin = end = None
+ if index.begin_index is not None:
+ if not isinstance(index.begin_index, IntExpr):
+ return None
+ begin = index.begin_index.value
+ if index.end_index is not None:
+ if not isinstance(index.end_index, IntExpr):
+ return None
+ end = index.end_index.value
+ return (begin, end)
+ return None
+
+
+def is_sys_attr(expr: Node, name: str) -> bool:
+ # TODO: This currently doesn't work with code like this:
+ # - import sys as _sys
+ # - from sys import version_info
+ if isinstance(expr, MemberExpr) and expr.name == name:
+ if isinstance(expr.expr, NameExpr) and expr.expr.name == 'sys':
+ # TODO: Guard against a local named sys, etc.
+ # (Though later passes will still do most checking.)
+ return True
+ return False
+
+
def mark_block_unreachable(block: Block) -> None:
block.is_unreachable = True
block.accept(MarkImportsUnreachableVisitor())
diff --git a/mypy/stats.py b/mypy/stats.py
index 952dcd5..ac914f4 100644
--- a/mypy/stats.py
+++ b/mypy/stats.py
@@ -222,7 +222,7 @@ def dump_type_stats(tree: Node, path: str, inferred: bool = False,
def is_special_module(path: str) -> bool:
- return os.path.basename(path) in ('abc.py', 'typing.py', 'builtins.py')
+ return os.path.basename(path) in ('abc.pyi', 'typing.pyi', 'builtins.pyi')
def is_imprecise(t: Type) -> bool:
diff --git a/mypy/strconv.py b/mypy/strconv.py
index 8d2c084..c2461ca 100644
--- a/mypy/strconv.py
+++ b/mypy/strconv.py
@@ -199,8 +199,10 @@ class StrConv(NodeVisitor[str]):
return self.dump(a, o)
def visit_for_stmt(self, o):
- a = [o.index]
- a.extend([o.expr, o.body])
+ a = []
+ if o.is_async:
+ a.append(('Async', ''))
+ a.extend([o.index, o.expr, o.body])
if o.else_body:
a.append(('Else', o.else_body.body))
return self.dump(a, o)
@@ -243,6 +245,9 @@ class StrConv(NodeVisitor[str]):
def visit_yield_expr(self, o):
return self.dump([o.expr], o)
+ def visit_await_expr(self, o):
+ return self.dump([o.expr], o)
+
def visit_del_stmt(self, o):
return self.dump([o.expr], o)
@@ -264,6 +269,8 @@ class StrConv(NodeVisitor[str]):
def visit_with_stmt(self, o):
a = []
+ if o.is_async:
+ a.append(('Async', ''))
for i in range(len(o.expr)):
a.append(('Expr', [o.expr[i]]))
if o.target[i]:
@@ -426,6 +433,9 @@ class StrConv(NodeVisitor[str]):
def visit__promote_expr(self, o):
return 'PromoteExpr:{}({})'.format(o.line, o.type)
+ def visit_newtype_expr(self, o):
+ return 'NewTypeExpr:{}({}, {})'.format(o.line, o.fullname(), self.dump([o.value], o))
+
def visit_func_expr(self, o):
a = self.func_helper(o)
return self.dump(a, o)
diff --git a/mypy/stubutil.py b/mypy/stubutil.py
index b254798..2c8633c 100644
--- a/mypy/stubutil.py
+++ b/mypy/stubutil.py
@@ -1,8 +1,16 @@
import re
import sys
+from typing import Any, Optional, Tuple, Sequence, MutableSequence, List, MutableMapping
-def parse_signature(sig):
+
+# Type Alias for Signatures
+Sig = Tuple[str, str]
+
+
+def parse_signature(sig: str) -> Optional[Tuple[str,
+ List[str],
+ List[str]]]:
m = re.match(r'([.a-zA-Z0-9_]+)\(([^)]*)\)', sig)
if not m:
return None
@@ -31,8 +39,10 @@ def parse_signature(sig):
return (name, fixed, optional)
-def build_signature(fixed, optional):
- args = fixed[:]
+def build_signature(fixed: Sequence[str],
+ optional: Sequence[str]) -> str:
+ args = [] # type: MutableSequence[str]
+ args.extend(fixed)
for arg in optional:
if arg.startswith('*'):
args.append(arg)
@@ -44,7 +54,8 @@ def build_signature(fixed, optional):
return sig
-def parse_all_signatures(lines):
+def parse_all_signatures(lines: Sequence[str]) -> Tuple[List[Sig],
+ List[Sig]]:
sigs = []
class_sigs = []
for line in lines:
@@ -63,8 +74,8 @@ def parse_all_signatures(lines):
return sorted(sigs), sorted(class_sigs)
-def find_unique_signatures(sigs):
- sig_map = {}
+def find_unique_signatures(sigs: Sequence[Sig]) -> List[Sig]:
+ sig_map = {} # type: MutableMapping[str, List[str]]
for name, sig in sigs:
sig_map.setdefault(name, []).append(sig)
result = []
diff --git a/mypy/traverser.py b/mypy/traverser.py
index ddd4ea7..d77b003 100644
--- a/mypy/traverser.py
+++ b/mypy/traverser.py
@@ -180,7 +180,8 @@ class TraverserVisitor(NodeVisitor[None]):
def visit_dict_expr(self, o: DictExpr) -> None:
for k, v in o.items:
- k.accept(self)
+ if k is not None:
+ k.accept(self)
v.accept(self)
def visit_set_expr(self, o: SetExpr) -> None:
diff --git a/mypy/treetransform.py b/mypy/treetransform.py
index 829b86d..06ea5cb 100644
--- a/mypy/treetransform.py
+++ b/mypy/treetransform.py
@@ -15,11 +15,11 @@ from mypy.nodes import (
ConditionalExpr, DictExpr, SetExpr, NameExpr, IntExpr, StrExpr, BytesExpr,
UnicodeExpr, FloatExpr, CallExpr, SuperExpr, MemberExpr, IndexExpr,
SliceExpr, OpExpr, UnaryExpr, FuncExpr, TypeApplication, PrintStmt,
- SymbolTable, RefExpr, TypeVarExpr, PromoteExpr,
+ SymbolTable, RefExpr, TypeVarExpr, NewTypeExpr, PromoteExpr,
ComparisonExpr, TempNode, StarExpr,
YieldFromExpr, NamedTupleExpr, NonlocalDecl, SetComprehension,
DictionaryComprehension, ComplexExpr, TypeAliasExpr, EllipsisExpr,
- YieldExpr, ExecStmt, Argument, BackquoteExpr
+ YieldExpr, ExecStmt, Argument, BackquoteExpr, AwaitExpr,
)
from mypy.types import Type, FunctionLike, Instance
from mypy.visitor import NodeVisitor
@@ -339,6 +339,9 @@ class TransformVisitor(NodeVisitor[Node]):
def visit_yield_expr(self, node: YieldExpr) -> Node:
return YieldExpr(self.node(node.expr))
+ def visit_await_expr(self, node: AwaitExpr) -> Node:
+ return AwaitExpr(self.node(node.expr))
+
def visit_call_expr(self, node: CallExpr) -> Node:
return CallExpr(self.node(node.callee),
self.nodes(node.args),
@@ -450,6 +453,9 @@ class TransformVisitor(NodeVisitor[Node]):
def visit_type_alias_expr(self, node: TypeAliasExpr) -> TypeAliasExpr:
return TypeAliasExpr(node.type)
+ def visit_newtype_expr(self, node: NewTypeExpr) -> NewTypeExpr:
+ return NewTypeExpr(node.info)
+
def visit_namedtuple_expr(self, node: NamedTupleExpr) -> Node:
return NamedTupleExpr(node.info)
diff --git a/mypy/typeanal.py b/mypy/typeanal.py
index 0493d3a..447d1f0 100644
--- a/mypy/typeanal.py
+++ b/mypy/typeanal.py
@@ -19,7 +19,13 @@ from mypy import nodes
from mypy import experiments
-type_constructors = {'typing.Tuple', 'typing.Union', 'typing.Callable', 'typing.Type'}
+type_constructors = {
+ 'typing.Callable',
+ 'typing.Optional',
+ 'typing.Tuple',
+ 'typing.Type',
+ 'typing.Union',
+}
def analyze_type_alias(node: Node,
@@ -95,10 +101,7 @@ class TypeAnalyser(TypeVisitor[Type]):
return TypeVarType(sym.tvar_def, t.line)
elif fullname == 'builtins.None':
if experiments.STRICT_OPTIONAL:
- if t.is_ret_type:
- return Void()
- else:
- return NoneTyp()
+ return NoneTyp(is_ret_type=t.is_ret_type)
else:
return Void()
elif fullname == 'typing.Any':
@@ -198,7 +201,7 @@ class TypeAnalyser(TypeVisitor[Type]):
return t
def visit_type_var(self, t: TypeVarType) -> Type:
- raise RuntimeError('TypeVarType is already analyzed')
+ return t
def visit_callable_type(self, t: CallableType) -> Type:
return t.copy_modified(arg_types=self.anal_array(t.arg_types),
diff --git a/mypy/types.py b/mypy/types.py
index 1f6d957..d582079 100644
--- a/mypy/types.py
+++ b/mypy/types.py
@@ -1,6 +1,7 @@
"""Classes for representing mypy types."""
from abc import abstractmethod
+import copy
from typing import (
Any, TypeVar, Dict, List, Tuple, cast, Generic, Set, Sequence, Optional, Union
)
@@ -20,6 +21,8 @@ class Type(mypy.nodes.Context):
"""Abstract base class for all types."""
line = 0
+ can_be_true = True
+ can_be_false = True
def __init__(self, line: int = -1) -> None:
self.line = line
@@ -259,6 +262,7 @@ class Void(Type):
the result type of calling such callable.
"""
+ can_be_true = False
source = '' # May be None; function that generated this value
def __init__(self, source: str = None, line: int = -1) -> None:
@@ -294,6 +298,9 @@ class UninhabitedType(Type):
is_subtype(UninhabitedType, T) = True
"""
+ can_be_true = False
+ can_be_false = False
+
def __init__(self, line: int = -1) -> None:
super().__init__(line)
@@ -327,19 +334,24 @@ class NoneTyp(Type):
of a function, where 'None' means Void.
"""
- def __init__(self, line: int = -1) -> None:
+ can_be_true = False
+
+ def __init__(self, is_ret_type: bool = False, line: int = -1) -> None:
super().__init__(line)
+ self.is_ret_type = is_ret_type
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_none_type(self)
def serialize(self) -> JsonDict:
- return {'.class': 'NoneTyp'}
+ return {'.class': 'NoneTyp',
+ 'is_ret_type': self.is_ret_type,
+ }
@classmethod
def deserialize(self, data: JsonDict) -> 'NoneTyp':
assert data['.class'] == 'NoneTyp'
- return NoneTyp()
+ return NoneTyp(is_ret_type=data['is_ret_type'])
class ErasedType(Type):
@@ -477,6 +489,8 @@ class TypeVarType(Type):
class FunctionLike(Type):
"""Abstract base class for function types."""
+ can_be_false = False
+
@abstractmethod
def is_type_obj(self) -> bool: pass
@@ -738,6 +752,8 @@ class TupleType(Type):
self.items = items
self.fallback = fallback
self.implicit = implicit
+ self.can_be_true = len(self.items) > 0
+ self.can_be_false = len(self.items) == 0
super().__init__(line)
def length(self) -> int:
@@ -784,6 +800,8 @@ class UnionType(Type):
def __init__(self, items: List[Type], line: int = -1) -> None:
self.items = items
+ self.can_be_true = any(item.can_be_true for item in items)
+ self.can_be_false = any(item.can_be_false for item in items)
super().__init__(line)
@staticmethod
@@ -814,10 +832,20 @@ class UnionType(Type):
from mypy.subtypes import is_subtype
removed = set() # type: Set[int]
- for i in range(len(items)):
- if any(is_subtype(items[i], items[j]) for j in range(len(items))
- if j not in removed and j != i):
- removed.add(i)
+ for i, ti in enumerate(items):
+ if i in removed: continue
+ # Keep track of the truishness info for deleted subtypes which can be relevant
+ cbt = cbf = False
+ for j, tj in enumerate(items):
+ if i != j and is_subtype(tj, ti):
+ removed.add(j)
+ cbt = cbt or tj.can_be_true
+ cbf = cbf or tj.can_be_false
+ # if deleted subtypes had more general truthiness, use that
+ if not ti.can_be_true and cbt:
+ items[i] = true_or_false(ti)
+ elif not ti.can_be_false and cbf:
+ items[i] = true_or_false(ti)
simplified_set = [items[i] for i in range(len(items)) if i not in removed]
return UnionType.make_union(simplified_set)
@@ -1391,3 +1419,60 @@ def is_named_instance(t: Type, fullname: str) -> bool:
return (isinstance(t, Instance) and
t.type is not None and
t.type.fullname() == fullname)
+
+
+def copy_type(t: Type) -> Type:
+ """
+ Build a copy of the type; used to mutate the copy with truthiness information
+ """
+ return copy.copy(t)
+
+
+def true_only(t: Type) -> Type:
+ """
+ Restricted version of t with only True-ish values
+ """
+ if not t.can_be_true:
+ # All values of t are False-ish, so there are no true values in it
+ return UninhabitedType(line=t.line)
+ elif not t.can_be_false:
+ # All values of t are already True-ish, so true_only is idempotent in this case
+ return t
+ elif isinstance(t, UnionType):
+ # The true version of a union type is the union of the true versions of its components
+ new_items = [true_only(item) for item in t.items]
+ return UnionType.make_simplified_union(new_items, line=t.line)
+ else:
+ new_t = copy_type(t)
+ new_t.can_be_false = False
+ return new_t
+
+
+def false_only(t: Type) -> Type:
+ """
+ Restricted version of t with only False-ish values
+ """
+ if not t.can_be_false:
+ # All values of t are True-ish, so there are no false values in it
+ return UninhabitedType(line=t.line)
+ elif not t.can_be_true:
+ # All values of t are already False-ish, so false_only is idempotent in this case
+ return t
+ elif isinstance(t, UnionType):
+ # The false version of a union type is the union of the false versions of its components
+ new_items = [false_only(item) for item in t.items]
+ return UnionType.make_simplified_union(new_items, line=t.line)
+ else:
+ new_t = copy_type(t)
+ new_t.can_be_true = False
+ return new_t
+
+
+def true_or_false(t: Type) -> Type:
+ """
+ Unrestricted version of t with both True-ish and False-ish values
+ """
+ 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
+ return new_t
diff --git a/mypy/version.py b/mypy/version.py
index 908c0bb..9a8e054 100644
--- a/mypy/version.py
+++ b/mypy/version.py
@@ -1 +1 @@
-__version__ = '0.4.3'
+__version__ = '0.4.4'
diff --git a/mypy/visitor.py b/mypy/visitor.py
index b1e1b88..b4c2cc8 100644
--- a/mypy/visitor.py
+++ b/mypy/visitor.py
@@ -225,8 +225,14 @@ class NodeVisitor(Generic[T]):
def visit_namedtuple_expr(self, o: 'mypy.nodes.NamedTupleExpr') -> T:
pass
+ def visit_newtype_expr(self, o: 'mypy.nodes.NewTypeExpr') -> T:
+ pass
+
def visit__promote_expr(self, o: 'mypy.nodes.PromoteExpr') -> T:
pass
+ def visit_await_expr(self, o: 'mypy.nodes.AwaitExpr') -> T:
+ pass
+
def visit_temp_node(self, o: 'mypy.nodes.TempNode') -> T:
pass
diff --git a/mypy/waiter.py b/mypy/waiter.py
index 4bb6665..10fa402 100644
--- a/mypy/waiter.py
+++ b/mypy/waiter.py
@@ -161,7 +161,7 @@ class Waiter:
def _poll_current(self) -> Tuple[int, int]:
while True:
- time.sleep(.25)
+ time.sleep(.05)
for pid in self.current:
cmd = self.current[pid][1]
code = cmd.process.poll()
@@ -281,6 +281,18 @@ def parse_test_stats_from_output(output: str, fail_type: Optional[str]) -> Tuple
Return tuple (number of tests, number of test failures). Default
to the entire task representing a single test as a fallback.
"""
+
+ # pytest
+ m = re.search('^=+ (.*) in [0-9.]+ seconds =+\n\Z', output, re.MULTILINE)
+ if m:
+ counts = {}
+ for part in m.group(1).split(', '): # e.g., '3 failed, 32 passed, 345 deselected'
+ count, key = part.split()
+ counts[key] = int(count)
+ return (sum(c for k, c in counts.items() if k != 'deselected'),
+ counts.get('failed', 0))
+
+ # myunit
m = re.search('^([0-9]+)/([0-9]+) test cases failed(, ([0-9]+) skipped)?.$', output,
re.MULTILINE)
if m:
@@ -289,6 +301,7 @@ def parse_test_stats_from_output(output: str, fail_type: Optional[str]) -> Tuple
re.MULTILINE)
if m:
return int(m.group(1)), 0
+
# Couldn't find test counts, so fall back to single test per tasks.
if fail_type is not None:
return 1, 1
diff --git a/scripts/find_type.py b/scripts/find_type.py
new file mode 100755
index 0000000..f858cfb
--- /dev/null
+++ b/scripts/find_type.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python3
+# Usage: find_type.py FILENAME START_LINE START_COL END_LINE END_COL MYPY_AND_ARGS
+# Prints out the type of the expression in the given location if the mypy run
+# succeeds cleanly. Otherwise, prints out the errors encountered.
+# Note: this only works on expressions, and not assignment targets.
+# Note: MYPY_AND_ARGS is should be the remainder of argv, not a single
+# spaces-included argument.
+# NOTE: Line numbers are 1-based; column numbers are 0-based.
+#
+#
+# Example vim usage:
+# function RevealType()
+# " Set this to the command you use to run mypy on your project. Include the mypy invocation.
+# let mypycmd = 'python3 -m mypy mypy --incremental'
+# let [startline, startcol] = getpos("'<")[1:2]
+# let [endline, endcol] = getpos("'>")[1:2]
+# " Convert to 0-based column offsets
+# let startcol = startcol - 1
+# " Change this line to point to the find_type.py script.
+# execute '!python3 /path/to/mypy/scripts/find_type.py % ' . startline . ' ' . startcol . ' ' . endline . ' ' . endcol . ' ' . mypycmd
+# endfunction
+# vnoremap <Leader>t :call RevealType()<CR>
+#
+# For an Emacs example, see misc/macs.el.
+
+from typing import List, Tuple, Optional
+import subprocess
+import sys
+import tempfile
+import os.path
+import re
+
+REVEAL_TYPE_START = 'reveal_type('
+REVEAL_TYPE_END = ')'
+
+def update_line(line: str, s: str, pos: int) -> str:
+ return line[:pos] + s + line[pos:]
+
+def run_mypy(mypy_and_args: List[str], filename: str, tmp_name: str) -> str:
+ proc = subprocess.run(mypy_and_args + ['--shadow-file', filename, tmp_name], stdout=subprocess.PIPE)
+ assert(isinstance(proc.stdout, bytes)) # Guaranteed to be true because we called run with universal_newlines=False
+ return proc.stdout.decode(encoding="utf-8")
+
+def get_revealed_type(line: str, relevant_file: str, relevant_line: int) -> Optional[str]:
+ m = re.match("(.+?):(\d+): error: Revealed type is '(.*)'$", line)
+ if (m and
+ int(m.group(2)) == relevant_line and
+ os.path.samefile(relevant_file, m.group(1))):
+ return m.group(3)
+ else:
+ return None
+
+def process_output(output: str, filename: str, start_line: int) -> Tuple[Optional[str], bool]:
+ error_found = False
+ for line in output.splitlines():
+ t = get_revealed_type(line, filename, start_line)
+ if t:
+ return t, error_found
+ elif 'error:' in line:
+ error_found = True
+ return None, True # finding no reveal_type is an error
+
+def main():
+ filename, start_line_str, start_col_str, end_line_str, end_col_str, *mypy_and_args = sys.argv[1:]
+ start_line = int(start_line_str)
+ start_col = int(start_col_str)
+ end_line = int(end_line_str)
+ end_col = int(end_col_str)
+ with open(filename, 'r') as f:
+ lines = f.readlines()
+ lines[end_line - 1] = update_line(lines[end_line - 1], REVEAL_TYPE_END, end_col) # insert after end_col
+ lines[start_line - 1] = update_line(lines[start_line - 1], REVEAL_TYPE_START, start_col)
+ with tempfile.NamedTemporaryFile(mode='w', prefix='mypy') as tmp_f:
+ tmp_f.writelines(lines)
+ tmp_f.flush()
+
+ output = run_mypy(mypy_and_args, filename, tmp_f.name)
+ revealed_type, error = process_output(output, filename, start_line)
+ if revealed_type:
+ print(revealed_type)
+ if error:
+ print(output)
+ exit(int(error))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/setup.py b/setup.py
index 10da829..f344cce 100644
--- a/setup.py
+++ b/setup.py
@@ -10,6 +10,7 @@ if sys.version_info < (3, 2, 0):
exit(1)
from distutils.core import setup
+from distutils.command.build_py import build_py
from mypy.version import __version__
from mypy import git
@@ -30,6 +31,19 @@ types.
'''.lstrip()
+def cache_version_id():
+ """Returns the version id to use for the incremental hash.
+
+ If setup.py is run from a git repo, the git commit hash will be
+ included if possible. If not, then this function will fall back to
+ using the default version id from mypy/version.py."""
+ if git.is_git_repo('.') and git.have_git():
+ return __version__ + '-' + git.git_revision('.').decode('utf-8')
+ else:
+ # Default fallback
+ return __version__
+
+
def find_data_files(base, globs):
"""Find all interesting data files, for setup(data_files=)
@@ -51,6 +65,19 @@ def find_data_files(base, globs):
return rv
+
+class CustomPythonBuild(build_py):
+ def pin_version(self):
+ path = os.path.join(self.build_lib, 'mypy')
+ self.mkpath(path)
+ with open(os.path.join(path, 'version.py'), 'w') as stream:
+ stream.write('__version__ = "{}"\n'.format(cache_version_id()))
+
+ def run(self):
+ self.execute(self.pin_version, ())
+ build_py.run(self)
+
+
data_files = []
data_files += find_data_files('typeshed', ['*.py', '*.pyi'])
@@ -93,4 +120,5 @@ setup(name='mypy-lang',
scripts=scripts,
data_files=data_files,
classifiers=classifiers,
+ cmdclass={'build_py': CustomPythonBuild},
)
diff --git a/typeshed/stdlib/2.7/BaseHTTPServer.pyi b/typeshed/stdlib/2.7/BaseHTTPServer.pyi
new file mode 100644
index 0000000..8bb34b8
--- /dev/null
+++ b/typeshed/stdlib/2.7/BaseHTTPServer.pyi
@@ -0,0 +1,47 @@
+# Stubs for BaseHTTPServer (Python 2.7)
+
+from typing import Any, BinaryIO, Mapping, Optional, Tuple, Union
+import SocketServer
+import mimetools
+
+class HTTPServer(SocketServer.TCPServer):
+ server_name = ... # type: str
+ server_port = ... # type: int
+ def __init__(self, server_address: Tuple[str, int],
+ RequestHandlerClass: type) -> None: ...
+
+class BaseHTTPRequestHandler:
+ client_address = ... # type: Tuple[str, int]
+ server = ... # type: SocketServer.BaseServer
+ close_connection = ... # type: bool
+ command = ... # type: str
+ path = ... # type: str
+ request_version = ... # type: str
+ headers = ... # type: mimetools.Message
+ rfile = ... # type: BinaryIO
+ wfile = ... # type: BinaryIO
+ server_version = ... # type: str
+ sys_version = ... # type: str
+ error_message_format = ... # type: str
+ error_content_type = ... # type: str
+ protocol_version = ... # type: str
+ MessageClass = ... # type: type
+ responses = ... # type: Mapping[int, Tuple[str, str]]
+ def __init__(self, request: bytes, client_address: Tuple[str, int],
+ server: SocketServer.BaseServer) -> None: ...
+ def handle(self) -> None: ...
+ def handle_one_request(self) -> None: ...
+ def send_error(self, code: int, message: Optional[str] = ...) -> None: ...
+ def send_response(self, code: int,
+ message: Optional[str] = ...) -> None: ...
+ def send_header(self, keyword: str, value: str) -> None: ...
+ def end_headers(self) -> None: ...
+ def flush_headers(self) -> None: ...
+ def log_request(self, code: Union[int, str] = ...,
+ size: Union[int, str] = ...) -> None: ...
+ def log_error(self, format: str, *args: Any) -> None: ...
+ def log_message(self, format: str, *args: Any) -> None: ...
+ def version_string(self) -> str: ...
+ def date_time_string(self, timestamp: Optional[int] = ...) -> str: ...
+ def log_date_time_string(self) -> str: ...
+ def address_string(self) -> str: ...
diff --git a/typeshed/stdlib/2.7/ConfigParser.pyi b/typeshed/stdlib/2.7/ConfigParser.pyi
index 7b027ce..5fdf380 100644
--- a/typeshed/stdlib/2.7/ConfigParser.pyi
+++ b/typeshed/stdlib/2.7/ConfigParser.pyi
@@ -1,4 +1,4 @@
-from typing import Any, Tuple
+from typing import Any, Tuple, IO
__all__ = ... # type: list[str]
DEFAULTSECT = ... # type: str
@@ -74,7 +74,7 @@ class RawConfigParser:
def has_section(self, section: str) -> bool: ...
def options(self, section: str) -> list[str]: ...
def read(self, filenames: str) -> list[str]: ...
- def readfp(self, fp: file, filename: str = ...) -> None: ...
+ def readfp(self, fp: IO[str], filename: str = ...) -> None: ...
def get(self, section: str, option: str) -> str: ...
def items(self, section: str) -> list[Tuple[Any,Any]]: ...
def _get(self, section: str, conv: type, option: str) -> Any: ...
diff --git a/typeshed/stdlib/2.7/Cookie.pyi b/typeshed/stdlib/2.7/Cookie.pyi
index 2aea075..f42cafc 100644
--- a/typeshed/stdlib/2.7/Cookie.pyi
+++ b/typeshed/stdlib/2.7/Cookie.pyi
@@ -14,7 +14,7 @@ class Morsel(dict):
value = ... # type: Any
coded_value = ... # type: Any
def set(self, key, val, coded_val, LegalChars=..., idmap=..., translate=...): ...
- def output(self, attrs=None, header=''): ...
+ def output(self, attrs=None, header=...): ...
def js_output(self, attrs=None): ...
def OutputString(self, attrs=None): ...
@@ -23,7 +23,7 @@ class BaseCookie(dict):
def value_encode(self, val): ...
def __init__(self, input=None): ...
def __setitem__(self, key, value): ...
- def output(self, attrs=None, header='', sep=''): ...
+ def output(self, attrs=None, header=..., sep=...): ...
def js_output(self, attrs=None): ...
def load(self, rawdata): ...
diff --git a/typeshed/stdlib/2.7/SocketServer.pyi b/typeshed/stdlib/2.7/SocketServer.pyi
index 4cd6e2d..14a739b 100644
--- a/typeshed/stdlib/2.7/SocketServer.pyi
+++ b/typeshed/stdlib/2.7/SocketServer.pyi
@@ -1,6 +1,6 @@
# Stubs for socketserver
-from typing import BinaryIO, Optional, Tuple
+from typing import Any, BinaryIO, Optional, Tuple
from socket import SocketType
import sys
import types
@@ -68,7 +68,18 @@ class ForkingUDPServer(ForkingMixIn, UDPServer): ...
class ThreadingTCPServer(ThreadingMixIn, TCPServer): ...
class ThreadingUDPServer(ThreadingMixIn, UDPServer): ...
+
class BaseRequestHandler:
+ # Those are technically of types, respectively:
+ # * Union[SocketType, Tuple[bytes, SocketType]]
+ # * Union[Tuple[str, int], str]
+ # But there are some concerns that having unions here would cause
+ # too much inconvenience to people using it (see
+ # https://github.com/python/typeshed/pull/384#issuecomment-234649696)
+ request = ... # type: Any
+ client_address = ... # type: Any
+
+ server = ... # type: BaseServer
def setup(self) -> None: ...
def handle(self) -> None: ...
def finish(self) -> None: ...
diff --git a/typeshed/stdlib/2.7/__builtin__.pyi b/typeshed/stdlib/2.7/__builtin__.pyi
index 0ce76c9..0ef4f3b 100644
--- a/typeshed/stdlib/2.7/__builtin__.pyi
+++ b/typeshed/stdlib/2.7/__builtin__.pyi
@@ -8,7 +8,7 @@ from typing import (
Sequence, Mapping, Tuple, List, Any, Dict, Callable, Generic, Set,
AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs,
SupportsRound, IO, BinaryIO, Union, AnyStr, MutableSequence, MutableMapping,
- MutableSet
+ MutableSet, ItemsView, KeysView, ValuesView, Optional, Container,
)
from abc import abstractmethod, ABCMeta
@@ -110,7 +110,7 @@ class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
def __str__(self) -> str: ...
def __float__(self) -> float: ...
- def __int__(self) -> int: return self
+ def __int__(self) -> int: ...
def __abs__(self) -> int: ...
def __hash__(self) -> int: ...
@@ -157,7 +157,7 @@ class float(SupportsFloat, SupportsInt, SupportsAbs[float]):
def __str__(self) -> str: ...
def __int__(self) -> int: ...
- def __float__(self) -> float: return self
+ def __float__(self) -> float: ...
def __abs__(self) -> float: ...
def __hash__(self) -> int: ...
@@ -430,7 +430,7 @@ class bytearray(MutableSequence[int]):
@overload
def __setitem__(self, i: int, x: int) -> None: ...
@overload
- def __setitem__(self, s: slice, x: Union[Sequence[int], str]) -> None: ...
+ def __setitem__(self, s: slice, x: Union[Iterable[int], str]) -> None: ...
def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ...
def __delitem__(self, i: Union[int, slice]) -> None: ...
def __delslice__(self, start: int, stop: int) -> None: ...
@@ -504,7 +504,7 @@ class list(MutableSequence[_T], Generic[_T]):
@overload
def __setitem__(self, i: int, o: _T) -> None: ...
@overload
- def __setitem__(self, s: slice, o: Sequence[_T]) -> None: ...
+ def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ...
def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ...
def __delitem__(self, i: Union[int, slice]) -> None: ...
def __delslice(self, start: int, stop: int) -> None: ...
@@ -546,6 +546,9 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
def iterkeys(self) -> Iterator[_KT]: ...
def itervalues(self) -> Iterator[_VT]: ...
def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ...
+ def viewkeys(self) -> KeysView[_KT]: ...
+ def viewvalues(self) -> ValuesView[_VT]: ...
+ def viewitems(self) -> ItemsView[_KT, _VT]: ...
@staticmethod
@overload
def fromkeys(seq: Sequence[_T]) -> Dict[_T, Any]: ... # TODO: Actually a class method
@@ -570,9 +573,9 @@ class set(MutableSet[_T], Generic[_T]):
def discard(self, element: _T) -> None: ...
def intersection(self, *s: Iterable[Any]) -> set[_T]: ...
def intersection_update(self, *s: Iterable[Any]) -> None: ...
- def isdisjoint(self, s: AbstractSet[Any]) -> bool: ...
- def issubset(self, s: AbstractSet[Any]) -> bool: ...
- def issuperset(self, s: AbstractSet[Any]) -> bool: ...
+ def isdisjoint(self, s: Iterable[Any]) -> bool: ...
+ def issubset(self, s: Iterable[Any]) -> bool: ...
+ def issuperset(self, s: Iterable[Any]) -> bool: ...
def pop(self) -> _T: ...
def remove(self, element: _T) -> None: ...
def symmetric_difference(self, s: Iterable[_T]) -> set[_T]: ...
@@ -603,13 +606,13 @@ class frozenset(AbstractSet[_T], Generic[_T]):
@overload
def __init__(self, iterable: Iterable[_T]) -> None: ...
def copy(self) -> frozenset[_T]: ...
- def difference(self, *s: AbstractSet[Any]) -> frozenset[_T]: ...
- def intersection(self, *s: AbstractSet[Any]) -> frozenset[_T]: ...
- def isdisjoint(self, s: AbstractSet[_T]) -> bool: ...
- def issubset(self, s: AbstractSet[Any]) -> bool: ...
- def issuperset(self, s: AbstractSet[Any]) -> bool: ...
- def symmetric_difference(self, s: AbstractSet[_T]) -> frozenset[_T]: ...
- def union(self, *s: AbstractSet[_T]) -> frozenset[_T]: ...
+ def difference(self, *s: Iterable[Any]) -> frozenset[_T]: ...
+ def intersection(self, *s: Iterable[Any]) -> frozenset[_T]: ...
+ def isdisjoint(self, s: Iterable[_T]) -> bool: ...
+ def issubset(self, s: Iterable[Any]) -> bool: ...
+ def issuperset(self, s: Iterable[Any]) -> bool: ...
+ def symmetric_difference(self, s: Iterable[_T]) -> frozenset[_T]: ...
+ def union(self, *s: Iterable[_T]) -> frozenset[_T]: ...
def __len__(self) -> int: ...
def __contains__(self, o: object) -> bool: ...
def __iter__(self) -> Iterator[_T]: ...
@@ -690,9 +693,7 @@ def iter(iterable: Iterable[_T]) -> Iterator[_T]: ...
@overload
def iter(function: Callable[[], _T], sentinel: _T) -> Iterator[_T]: ...
def isinstance(o: object, t: Union[type, Tuple[type, ...]]) -> bool: ...
-def issubclass(cls: type, classinfo: type) -> bool: ...
-# TODO support this
-#def issubclass(type cld, classinfo: Sequence[type]) -> bool: ...
+def issubclass(cls: type, classinfo: Union[type, Tuple[type, ...]]) -> bool: ...
def len(o: Sized) -> int: ...
@overload
def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> List[_S]: ...
@@ -704,7 +705,6 @@ def map(func: Callable[[_T1, _T2], _S],
def max(arg1: _T, arg2: _T, *args: _T, key: Callable[[_T], Any] = None) -> _T: ...
@overload
def max(iterable: Iterable[_T], key: Callable[[_T], Any] = None) -> _T: ...
-# TODO memoryview
@overload
def min(arg1: _T, arg2: _T, *args: _T, key: Callable[[_T], Any] = None) -> _T: ...
@overload
@@ -800,6 +800,36 @@ class buffer(Sized):
def __len__(self) -> int: ...
def __mul__(self, x: int) -> str: ...
+class memoryview(Sized, Container[bytes]):
+ format = ... # type: str
+ itemsize = ... # type: int
+ shape = ... # type: Optional[Tuple[int, ...]]
+ strides = ... # type: Optional[Tuple[int, ...]]
+ suboffsets = ... # type: Optional[Tuple[int, ...]]
+ readonly = ... # type: bool
+ ndim = ... # type: int
+
+ def __init__(self, obj: Union[str, bytearray, buffer, memoryview]) -> None: ...
+
+ @overload
+ def __getitem__(self, i: int) -> bytes: ...
+ @overload
+ def __getitem__(self, s: slice) -> memoryview: ...
+
+ def __contains__(self, x: object) -> bool: ...
+ def __iter__(self) -> Iterator[bytes]: ...
+ def __len__(self) -> int: ...
+
+ @overload
+ def __setitem__(self, i: int, o: bytes) -> None: ...
+ @overload
+ def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ...
+ @overload
+ def __setitem__(self, s: slice, o: memoryview) -> None: ...
+
+ def tobytes(self) -> bytes: ...
+ def tolist(self) -> List[int]: ...
+
class BaseException:
args = ... # type: Any
message = ... # type: str
@@ -834,7 +864,8 @@ class MemoryError(StandardError): ...
class NameError(StandardError): ...
class NotImplementedError(RuntimeError): ...
class OSError(EnvironmentError): ...
-class WindowsError(OSError): ...
+class WindowsError(OSError):
+ winerror = ... # type: int
class OverflowError(ArithmeticError): ...
class ReferenceError(StandardError): ...
class SyntaxError(StandardError):
diff --git a/typeshed/stdlib/2.7/_locale.pyi b/typeshed/stdlib/2.7/_locale.pyi
deleted file mode 100644
index 20584fc..0000000
--- a/typeshed/stdlib/2.7/_locale.pyi
+++ /dev/null
@@ -1,81 +0,0 @@
-from typing import Optional, Dict, Any
-
-ABDAY_1 = ... # type: int
-ABDAY_2 = ... # type: int
-ABDAY_3 = ... # type: int
-ABDAY_4 = ... # type: int
-ABDAY_5 = ... # type: int
-ABDAY_6 = ... # type: int
-ABDAY_7 = ... # type: int
-ABMON_1 = ... # type: int
-ABMON_10 = ... # type: int
-ABMON_11 = ... # type: int
-ABMON_12 = ... # type: int
-ABMON_2 = ... # type: int
-ABMON_3 = ... # type: int
-ABMON_4 = ... # type: int
-ABMON_5 = ... # type: int
-ABMON_6 = ... # type: int
-ABMON_7 = ... # type: int
-ABMON_8 = ... # type: int
-ABMON_9 = ... # type: int
-ALT_DIGITS = ... # type: int
-AM_STR = ... # type: int
-CHAR_MAX = ... # type: int
-CODESET = ... # type: int
-CRNCYSTR = ... # type: int
-DAY_1 = ... # type: int
-DAY_2 = ... # type: int
-DAY_3 = ... # type: int
-DAY_4 = ... # type: int
-DAY_5 = ... # type: int
-DAY_6 = ... # type: int
-DAY_7 = ... # type: int
-D_FMT = ... # type: int
-D_T_FMT = ... # type: int
-ERA = ... # type: int
-ERA_D_FMT = ... # type: int
-ERA_D_T_FMT = ... # type: int
-ERA_T_FMT = ... # type: int
-LC_ALL = ... # type: int
-LC_COLLATE = ... # type: int
-LC_CTYPE = ... # type: int
-LC_MESSAGES = ... # type: int
-LC_MONETARY = ... # type: int
-LC_NUMERIC = ... # type: int
-LC_TIME = ... # type: int
-MON_1 = ... # type: int
-MON_10 = ... # type: int
-MON_11 = ... # type: int
-MON_12 = ... # type: int
-MON_2 = ... # type: int
-MON_3 = ... # type: int
-MON_4 = ... # type: int
-MON_5 = ... # type: int
-MON_6 = ... # type: int
-MON_7 = ... # type: int
-MON_8 = ... # type: int
-MON_9 = ... # type: int
-NOEXPR = ... # type: int
-PM_STR = ... # type: int
-RADIXCHAR = ... # type: int
-THOUSEP = ... # type: int
-T_FMT = ... # type: int
-T_FMT_AMPM = ... # type: int
-YESEXPR = ... # type: int
-_DATE_FMT = ... # type: int
-
-class Error(Exception):
- pass
-
-def bind_textdomain_codeset(domain: Optional[str], codeset: Optional[str]) -> Optional[str]: pass
-def bindtextdomain(domain: Optional[str], dir: Optional[str]) -> str: pass
-def dcgettext(domain: Optional[str], msg: str, category: int) -> str: pass
-def dgettext(domain: Optional[str], msg: str) -> str: pass
-def gettext(msg: str) -> str: pass
-def localeconv() -> Dict[str, Any]: pass
-def nl_langinfo(key: int) -> str: pass
-def setlocale(i: int, s: str) -> str: pass
-def strcoll(left: str, right: str) -> int: pass
-def strxfrm(s: str) -> str: pass
-def textdomain(domain: Optional[str]) -> str: pass
diff --git a/typeshed/stdlib/2.7/ast.pyi b/typeshed/stdlib/2.7/ast.pyi
index 1864d31..6e11445 100644
--- a/typeshed/stdlib/2.7/ast.pyi
+++ b/typeshed/stdlib/2.7/ast.pyi
@@ -1,7 +1,7 @@
# Python 2.7 ast
import typing
-from typing import Any, Tuple, Iterator, Union
+from typing import Any, Iterator, Union
from _ast import (
Add, alias, And, arguments, Assert, Assign, AST, Attribute, AugAssign,
diff --git a/typeshed/stdlib/2.7/bisect.pyi b/typeshed/stdlib/2.7/bisect.pyi
deleted file mode 100644
index 5d3f2e5..0000000
--- a/typeshed/stdlib/2.7/bisect.pyi
+++ /dev/null
@@ -1,6 +0,0 @@
-def bisect(a: list, x: object, lo: int = ..., hi: int = ...) -> int: ...
-def bisect_left(a: list, x: object, lo: int = ..., hi: int = ...) -> int: ...
-def bisect_right(a: list, x: object, lo: int = ..., hi: int = ...) -> int: ...
-def insort_left(a: list, x: object, lo: int = ..., hi: int = ...) -> int: ...
-def insort_right(a: list, x: object, lo: int = ..., hi: int = ...) -> int: ...
-def insort(a: list, x: object, lo: int = ..., hi: int = ...) -> int: ...
diff --git a/typeshed/stdlib/2.7/builtins.pyi b/typeshed/stdlib/2.7/builtins.pyi
index 0ce76c9..0ef4f3b 100644
--- a/typeshed/stdlib/2.7/builtins.pyi
+++ b/typeshed/stdlib/2.7/builtins.pyi
@@ -8,7 +8,7 @@ from typing import (
Sequence, Mapping, Tuple, List, Any, Dict, Callable, Generic, Set,
AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs,
SupportsRound, IO, BinaryIO, Union, AnyStr, MutableSequence, MutableMapping,
- MutableSet
+ MutableSet, ItemsView, KeysView, ValuesView, Optional, Container,
)
from abc import abstractmethod, ABCMeta
@@ -110,7 +110,7 @@ class int(SupportsInt, SupportsFloat, SupportsAbs[int]):
def __str__(self) -> str: ...
def __float__(self) -> float: ...
- def __int__(self) -> int: return self
+ def __int__(self) -> int: ...
def __abs__(self) -> int: ...
def __hash__(self) -> int: ...
@@ -157,7 +157,7 @@ class float(SupportsFloat, SupportsInt, SupportsAbs[float]):
def __str__(self) -> str: ...
def __int__(self) -> int: ...
- def __float__(self) -> float: return self
+ def __float__(self) -> float: ...
def __abs__(self) -> float: ...
def __hash__(self) -> int: ...
@@ -430,7 +430,7 @@ class bytearray(MutableSequence[int]):
@overload
def __setitem__(self, i: int, x: int) -> None: ...
@overload
- def __setitem__(self, s: slice, x: Union[Sequence[int], str]) -> None: ...
+ def __setitem__(self, s: slice, x: Union[Iterable[int], str]) -> None: ...
def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ...
def __delitem__(self, i: Union[int, slice]) -> None: ...
def __delslice__(self, start: int, stop: int) -> None: ...
@@ -504,7 +504,7 @@ class list(MutableSequence[_T], Generic[_T]):
@overload
def __setitem__(self, i: int, o: _T) -> None: ...
@overload
- def __setitem__(self, s: slice, o: Sequence[_T]) -> None: ...
+ def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ...
def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ...
def __delitem__(self, i: Union[int, slice]) -> None: ...
def __delslice(self, start: int, stop: int) -> None: ...
@@ -546,6 +546,9 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
def iterkeys(self) -> Iterator[_KT]: ...
def itervalues(self) -> Iterator[_VT]: ...
def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ...
+ def viewkeys(self) -> KeysView[_KT]: ...
+ def viewvalues(self) -> ValuesView[_VT]: ...
+ def viewitems(self) -> ItemsView[_KT, _VT]: ...
@staticmethod
@overload
def fromkeys(seq: Sequence[_T]) -> Dict[_T, Any]: ... # TODO: Actually a class method
@@ -570,9 +573,9 @@ class set(MutableSet[_T], Generic[_T]):
def discard(self, element: _T) -> None: ...
def intersection(self, *s: Iterable[Any]) -> set[_T]: ...
def intersection_update(self, *s: Iterable[Any]) -> None: ...
- def isdisjoint(self, s: AbstractSet[Any]) -> bool: ...
- def issubset(self, s: AbstractSet[Any]) -> bool: ...
- def issuperset(self, s: AbstractSet[Any]) -> bool: ...
+ def isdisjoint(self, s: Iterable[Any]) -> bool: ...
+ def issubset(self, s: Iterable[Any]) -> bool: ...
+ def issuperset(self, s: Iterable[Any]) -> bool: ...
def pop(self) -> _T: ...
def remove(self, element: _T) -> None: ...
def symmetric_difference(self, s: Iterable[_T]) -> set[_T]: ...
@@ -603,13 +606,13 @@ class frozenset(AbstractSet[_T], Generic[_T]):
@overload
def __init__(self, iterable: Iterable[_T]) -> None: ...
def copy(self) -> frozenset[_T]: ...
- def difference(self, *s: AbstractSet[Any]) -> frozenset[_T]: ...
- def intersection(self, *s: AbstractSet[Any]) -> frozenset[_T]: ...
- def isdisjoint(self, s: AbstractSet[_T]) -> bool: ...
- def issubset(self, s: AbstractSet[Any]) -> bool: ...
- def issuperset(self, s: AbstractSet[Any]) -> bool: ...
- def symmetric_difference(self, s: AbstractSet[_T]) -> frozenset[_T]: ...
- def union(self, *s: AbstractSet[_T]) -> frozenset[_T]: ...
+ def difference(self, *s: Iterable[Any]) -> frozenset[_T]: ...
+ def intersection(self, *s: Iterable[Any]) -> frozenset[_T]: ...
+ def isdisjoint(self, s: Iterable[_T]) -> bool: ...
+ def issubset(self, s: Iterable[Any]) -> bool: ...
+ def issuperset(self, s: Iterable[Any]) -> bool: ...
+ def symmetric_difference(self, s: Iterable[_T]) -> frozenset[_T]: ...
+ def union(self, *s: Iterable[_T]) -> frozenset[_T]: ...
def __len__(self) -> int: ...
def __contains__(self, o: object) -> bool: ...
def __iter__(self) -> Iterator[_T]: ...
@@ -690,9 +693,7 @@ def iter(iterable: Iterable[_T]) -> Iterator[_T]: ...
@overload
def iter(function: Callable[[], _T], sentinel: _T) -> Iterator[_T]: ...
def isinstance(o: object, t: Union[type, Tuple[type, ...]]) -> bool: ...
-def issubclass(cls: type, classinfo: type) -> bool: ...
-# TODO support this
-#def issubclass(type cld, classinfo: Sequence[type]) -> bool: ...
+def issubclass(cls: type, classinfo: Union[type, Tuple[type, ...]]) -> bool: ...
def len(o: Sized) -> int: ...
@overload
def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> List[_S]: ...
@@ -704,7 +705,6 @@ def map(func: Callable[[_T1, _T2], _S],
def max(arg1: _T, arg2: _T, *args: _T, key: Callable[[_T], Any] = None) -> _T: ...
@overload
def max(iterable: Iterable[_T], key: Callable[[_T], Any] = None) -> _T: ...
-# TODO memoryview
@overload
def min(arg1: _T, arg2: _T, *args: _T, key: Callable[[_T], Any] = None) -> _T: ...
@overload
@@ -800,6 +800,36 @@ class buffer(Sized):
def __len__(self) -> int: ...
def __mul__(self, x: int) -> str: ...
+class memoryview(Sized, Container[bytes]):
+ format = ... # type: str
+ itemsize = ... # type: int
+ shape = ... # type: Optional[Tuple[int, ...]]
+ strides = ... # type: Optional[Tuple[int, ...]]
+ suboffsets = ... # type: Optional[Tuple[int, ...]]
+ readonly = ... # type: bool
+ ndim = ... # type: int
+
+ def __init__(self, obj: Union[str, bytearray, buffer, memoryview]) -> None: ...
+
+ @overload
+ def __getitem__(self, i: int) -> bytes: ...
+ @overload
+ def __getitem__(self, s: slice) -> memoryview: ...
+
+ def __contains__(self, x: object) -> bool: ...
+ def __iter__(self) -> Iterator[bytes]: ...
+ def __len__(self) -> int: ...
+
+ @overload
+ def __setitem__(self, i: int, o: bytes) -> None: ...
+ @overload
+ def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ...
+ @overload
+ def __setitem__(self, s: slice, o: memoryview) -> None: ...
+
+ def tobytes(self) -> bytes: ...
+ def tolist(self) -> List[int]: ...
+
class BaseException:
args = ... # type: Any
message = ... # type: str
@@ -834,7 +864,8 @@ class MemoryError(StandardError): ...
class NameError(StandardError): ...
class NotImplementedError(RuntimeError): ...
class OSError(EnvironmentError): ...
-class WindowsError(OSError): ...
+class WindowsError(OSError):
+ winerror = ... # type: int
class OverflowError(ArithmeticError): ...
class ReferenceError(StandardError): ...
class SyntaxError(StandardError):
diff --git a/typeshed/stdlib/2.7/calendar.pyi b/typeshed/stdlib/2.7/calendar.pyi
index e5ee51b..cb458ac 100644
--- a/typeshed/stdlib/2.7/calendar.pyi
+++ b/typeshed/stdlib/2.7/calendar.pyi
@@ -51,7 +51,7 @@ class HTMLCalendar(Calendar):
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: ...
+ def formatyearpage(self, theyear: int, width: int = 3, css: Optional[str] = ..., encoding: Optional[str] = ...) -> str: ...
class TimeEncoding:
def __init__(self, locale: LocaleType) -> None: ...
diff --git a/typeshed/stdlib/2.7/codecs.pyi b/typeshed/stdlib/2.7/codecs.pyi
index 582bf40..3ae1b16 100644
--- a/typeshed/stdlib/2.7/codecs.pyi
+++ b/typeshed/stdlib/2.7/codecs.pyi
@@ -40,14 +40,14 @@ def decode(obj: _encoded, encoding: str = ..., errors: str = ...) -> _decoded:
def lookup(encoding: str) -> 'CodecInfo':
...
class CodecInfo(Tuple[_encode_type, _decode_type, _stream_reader_type, _stream_writer_type]):
- def __init__(self, encode: _encode_type, decode: _decode_type, streamreader: _stream_reader_type = ..., streamwriter: _stream_writer_type = ..., incrementalencoder: _incremental_encoder_type = ..., incrementaldecoder: _incremental_decode_type = ..., name: str = ...) -> None:
- self.encode = encode
- self.decode = decode
- self.streamreader = streamreader
- self.streamwriter = streamwriter
- self.incrementalencoder = incrementalencoder
- self.incrementaldecoder = incrementaldecoder
- self.name = name
+ def __init__(self, encode: _encode_type, decode: _decode_type, streamreader: _stream_reader_type = ..., streamwriter: _stream_writer_type = ..., incrementalencoder: _incremental_encoder_type = ..., incrementaldecoder: _incremental_decode_type = ..., name: str = ...) -> None: ...
+ encode = ... # type: _encode_type
+ decode = ... # type: _decode_type
+ streamreader = ... # type: _stream_reader_type
+ streamwriter = ... # type: _stream_writer_type
+ incrementalencoder = ... # type: _incremental_encoder_type
+ incrementaldecoder = ... # type: _incremental_decode_type
+ name = ... # type: str
def getencoder(encoding: str) -> _encode_type:
...
@@ -115,8 +115,9 @@ class Codec:
...
class IncrementalEncoder:
+ errors = ... # type: str
def __init__(self, errors: str = ...) -> None:
- self.errors = errors
+ ...
@abstractmethod
def encode(self, object: _decoded, final: bool = ...) -> _encoded:
...
@@ -129,8 +130,9 @@ class IncrementalEncoder:
...
class IncrementalDecoder:
+ errors = ... # type: str
def __init__(self, errors: str = ...) -> None:
- self.errors = errors
+ ...
@abstractmethod
def decode(self, object: _encoded, final: bool = ...) -> _decoded:
...
@@ -143,18 +145,18 @@ class IncrementalDecoder:
# These are not documented but used in encodings/*.py implementations.
class BufferedIncrementalEncoder(IncrementalEncoder):
+ buffer = ... # type: str
def __init__(self, errors: str = ...) -> None:
- IncrementalEncoder.__init__(self, errors)
- self.buffer = ''
+ ...
@abstractmethod
def _buffer_encode(self, input: _decoded, errors: str, final: bool) -> _encoded:
...
def encode(self, input: _decoded, final: bool = ...) -> _encoded:
...
class BufferedIncrementalDecoder(IncrementalDecoder):
+ buffer = ... # type: str
def __init__(self, errors: str = ...) -> None:
- IncrementalDecoder.__init__(self, errors)
- self.buffer = b''
+ ...
@abstractmethod
def _buffer_decode(self, input: _encoded, errors: str, final: bool) -> Tuple[_decoded, int]:
...
@@ -164,8 +166,9 @@ class BufferedIncrementalDecoder(IncrementalDecoder):
# TODO: it is not possible to specify the requirement that all other
# attributes and methods are passed-through from the stream.
class StreamWriter(Codec):
+ errors = ... # type: str
def __init__(self, stream: BinaryIO, errors: str = ...) -> None:
- self.errors = errors
+ ...
def write(self, obj: _decoded) -> None:
...
def writelines(self, list: List[str]) -> None:
@@ -174,8 +177,9 @@ class StreamWriter(Codec):
...
class StreamReader(Codec):
+ errors = ... # type: str
def __init__(self, stream: BinaryIO, errors: str = ...) -> None:
- self.errors = errors
+ ...
def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> _decoded:
...
def readline(self, size: int = ..., keepends: bool = ...) -> _decoded:
diff --git a/typeshed/stdlib/2.7/contextlib.pyi b/typeshed/stdlib/2.7/contextlib.pyi
deleted file mode 100644
index 4400098..0000000
--- a/typeshed/stdlib/2.7/contextlib.pyi
+++ /dev/null
@@ -1,17 +0,0 @@
-# Stubs for contextlib
-
-# NOTE: These are incomplete!
-
-from typing import Callable, Generic, Iterator, TypeVar
-
-_T = TypeVar('_T')
-
-class ContextManager(Generic[_T]):
- def __enter__(self) -> _T: ...
- def __exit__(self, *exc_info) -> None: ...
-
-# TODO this doesn't capture the relationship that the returned function's args are the same as func's.
-def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
-
-class closing(ContextManager[_T], Generic[_T]):
- def __init__(self, thing: _T) -> None: ...
diff --git a/typeshed/stdlib/2.7/datetime.pyi b/typeshed/stdlib/2.7/datetime.pyi
index 30651f2..ef4f9a6 100644
--- a/typeshed/stdlib/2.7/datetime.pyi
+++ b/typeshed/stdlib/2.7/datetime.pyi
@@ -10,8 +10,8 @@ MAXYEAR = 0
class tzinfo(object):
def tzname(self, dt: Optional[datetime]) -> str: ...
- def utcoffset(self, dt: Optional[datetime]) -> timedelta: ...
- def dst(self, dt: Optional[datetime]) -> timedelta: ...
+ def utcoffset(self, dt: Optional[datetime]) -> Optional[timedelta]: ...
+ def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ...
def fromutc(self, dt: datetime) -> datetime: ...
class timezone(tzinfo):
diff --git a/typeshed/stdlib/2.7/decimal.pyi b/typeshed/stdlib/2.7/decimal.pyi
new file mode 100644
index 0000000..ebb6635
--- /dev/null
+++ b/typeshed/stdlib/2.7/decimal.pyi
@@ -0,0 +1,231 @@
+# Stubs for decimal (Python 2)
+#
+# NOTE: This dynamically typed stub was automatically generated by stubgen.
+
+from typing import Any, SupportsAbs, SupportsFloat, SupportsInt
+
+ROUND_DOWN = ... # type: Any
+ROUND_HALF_UP = ... # type: Any
+ROUND_HALF_EVEN = ... # type: Any
+ROUND_CEILING = ... # type: Any
+ROUND_FLOOR = ... # type: Any
+ROUND_UP = ... # type: Any
+ROUND_HALF_DOWN = ... # type: Any
+ROUND_05UP = ... # type: Any
+
+class DecimalException(ArithmeticError):
+ def handle(self, context, *args): ...
+
+class Clamped(DecimalException): ...
+
+class InvalidOperation(DecimalException): ...
+
+class ConversionSyntax(InvalidOperation): ...
+
+class DivisionByZero(DecimalException, ZeroDivisionError): ...
+
+class DivisionImpossible(InvalidOperation): ...
+
+class DivisionUndefined(InvalidOperation, ZeroDivisionError): ...
+
+class Inexact(DecimalException): ...
+
+class InvalidContext(InvalidOperation): ...
+
+class Rounded(DecimalException): ...
+
+class Subnormal(DecimalException): ...
+
+class Overflow(Inexact, Rounded): ...
+
+class Underflow(Inexact, Rounded, Subnormal): ...
+
+def setcontext(context): ...
+def getcontext(): ...
+def localcontext(ctx=None): ...
+
+class Decimal(SupportsAbs[Decimal], SupportsFloat, SupportsInt):
+ def __new__(cls, value=..., context=None): ...
+ @classmethod
+ def from_float(cls, f): ...
+ def __nonzero__(self): ...
+ def __eq__(self, other, context=None): ...
+ def __ne__(self, other, context=None): ...
+ def __lt__(self, other, context=None): ...
+ def __le__(self, other, context=None): ...
+ def __gt__(self, other, context=None): ...
+ def __ge__(self, other, context=None): ...
+ def compare(self, other, context=None): ...
+ def __hash__(self): ...
+ def as_tuple(self): ...
+ def to_eng_string(self, context=None): ...
+ def __neg__(self, context=None): ...
+ def __pos__(self, context=None): ...
+ def __abs__(self, round=True, context=None): ...
+ def __add__(self, other, context=None): ...
+ def __radd__(self, other, context=None): ...
+ def __sub__(self, other, context=None): ...
+ def __rsub__(self, other, context=None): ...
+ def __mul__(self, other, context=None): ...
+ def __rmul__(self, other, context=None): ...
+ def __truediv__(self, other, context=None): ...
+ def __rtruediv__(self, other, context=None): ...
+ def __div__(self, other, context=None): ...
+ def __rdiv__(self, other, context=None): ...
+ def __divmod__(self, other, context=None): ...
+ def __rdivmod__(self, other, context=None): ...
+ def __mod__(self, other, context=None): ...
+ def __rmod__(self, other, context=None): ...
+ def remainder_near(self, other, context=None): ...
+ def __floordiv__(self, other, context=None): ...
+ def __rfloordiv__(self, other, context=None): ...
+ def __float__(self): ...
+ def __int__(self): ...
+ def __trunc__(self): ...
+ real = ... # type: property
+ imag = ... # type: property
+ def conjugate(self): ...
+ def __complex__(self): ...
+ def __long__(self): ...
+ def fma(self, other, third, context=None): ...
+ def __pow__(self, other, modulo=None, context=None): ...
+ def __rpow__(self, other, context=None): ...
+ def normalize(self, context=None): ...
+ def quantize(self, exp, rounding=None, context=None, watchexp=True): ...
+ def same_quantum(self, other): ...
+ def to_integral_exact(self, rounding=None, context=None): ...
+ def to_integral_value(self, rounding=None, context=None): ...
+ def to_integral(self, rounding=None, context=None): ...
+ def sqrt(self, context=None): ...
+ def max(self, other, context=None): ...
+ def min(self, other, context=None): ...
+ def adjusted(self): ...
+ def canonical(self, context=None): ...
+ def compare_signal(self, other, context=None): ...
+ def compare_total(self, other): ...
+ def compare_total_mag(self, other): ...
+ def copy_abs(self): ...
+ def copy_negate(self): ...
+ def copy_sign(self, other): ...
+ def exp(self, context=None): ...
+ def is_canonical(self): ...
+ def is_finite(self): ...
+ def is_infinite(self): ...
+ def is_nan(self): ...
+ def is_normal(self, context=None): ...
+ def is_qnan(self): ...
+ def is_signed(self): ...
+ def is_snan(self): ...
+ def is_subnormal(self, context=None): ...
+ def is_zero(self): ...
+ def ln(self, context=None): ...
+ def log10(self, context=None): ...
+ def logb(self, context=None): ...
+ def logical_and(self, other, context=None): ...
+ def logical_invert(self, context=None): ...
+ def logical_or(self, other, context=None): ...
+ def logical_xor(self, other, context=None): ...
+ def max_mag(self, other, context=None): ...
+ def min_mag(self, other, context=None): ...
+ def next_minus(self, context=None): ...
+ def next_plus(self, context=None): ...
+ def next_toward(self, other, context=None): ...
+ def number_class(self, context=None): ...
+ def radix(self): ...
+ def rotate(self, other, context=None): ...
+ def scaleb(self, other, context=None): ...
+ def shift(self, other, context=None): ...
+ def __reduce__(self): ...
+ def __copy__(self): ...
+ def __deepcopy__(self, memo): ...
+ def __format__(self, specifier, context=None, _localeconv=None): ...
+
+class _ContextManager:
+ new_context = ... # type: Any
+ def __init__(self, new_context): ...
+ saved_context = ... # type: Any
+ def __enter__(self): ...
+ def __exit__(self, t, v, tb): ...
+
+class Context:
+ prec = ... # type: Any
+ rounding = ... # type: Any
+ Emin = ... # type: Any
+ Emax = ... # type: Any
+ capitals = ... # type: Any
+ traps = ... # type: Any
+ flags = ... # type: Any
+ def __init__(self, prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=None, _clamp=0, _ignored_flags=None): ...
+ def clear_flags(self): ...
+ def copy(self): ...
+ __copy__ = ... # type: Any
+ __hash__ = ... # type: Any
+ def Etiny(self): ...
+ def Etop(self): ...
+ def create_decimal(self, num=...): ...
+ def create_decimal_from_float(self, f): ...
+ def abs(self, a): ...
+ def add(self, a, b): ...
+ def canonical(self, a): ...
+ def compare(self, a, b): ...
+ def compare_signal(self, a, b): ...
+ def compare_total(self, a, b): ...
+ def compare_total_mag(self, a, b): ...
+ def copy_abs(self, a): ...
+ def copy_decimal(self, a): ...
+ def copy_negate(self, a): ...
+ def copy_sign(self, a, b): ...
+ def divide(self, a, b): ...
+ def divide_int(self, a, b): ...
+ def divmod(self, a, b): ...
+ def exp(self, a): ...
+ def fma(self, a, b, c): ...
+ def is_canonical(self, a): ...
+ def is_finite(self, a): ...
+ def is_infinite(self, a): ...
+ def is_nan(self, a): ...
+ def is_normal(self, a): ...
+ def is_qnan(self, a): ...
+ def is_signed(self, a): ...
+ def is_snan(self, a): ...
+ def is_subnormal(self, a): ...
+ def is_zero(self, a): ...
+ def ln(self, a): ...
+ def log10(self, a): ...
+ def logb(self, a): ...
+ def logical_and(self, a, b): ...
+ def logical_invert(self, a): ...
+ def logical_or(self, a, b): ...
+ def logical_xor(self, a, b): ...
+ def max(self, a, b): ...
+ def max_mag(self, a, b): ...
+ def min(self, a, b): ...
+ def min_mag(self, a, b): ...
+ def minus(self, a): ...
+ def multiply(self, a, b): ...
+ def next_minus(self, a): ...
+ def next_plus(self, a): ...
+ def next_toward(self, a, b): ...
+ def normalize(self, a): ...
+ def number_class(self, a): ...
+ def plus(self, a): ...
+ def power(self, a, b, modulo=None): ...
+ def quantize(self, a, b): ...
+ def radix(self): ...
+ def remainder(self, a, b): ...
+ def remainder_near(self, a, b): ...
+ def rotate(self, a, b): ...
+ def same_quantum(self, a, b): ...
+ def scaleb(self, a, b): ...
+ def shift(self, a, b): ...
+ def sqrt(self, a): ...
+ def subtract(self, a, b): ...
+ def to_eng_string(self, a): ...
+ def to_sci_string(self, a): ...
+ def to_integral_exact(self, a): ...
+ def to_integral_value(self, a): ...
+ def to_integral(self, a): ...
+
+DefaultContext = ... # type: Any
+BasicContext = ... # type: Any
+ExtendedContext = ... # type: Any
diff --git a/typeshed/stdlib/2.7/distutils/__init__.pyi b/typeshed/stdlib/2.7/distutils/__init__.pyi
index d4853fe..e69de29 100644
--- a/typeshed/stdlib/2.7/distutils/__init__.pyi
+++ b/typeshed/stdlib/2.7/distutils/__init__.pyi
@@ -1,7 +0,0 @@
-# Stubs for distutils (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-__revision__ = ... # type: Any
diff --git a/typeshed/stdlib/2.7/distutils/emxccompiler.pyi b/typeshed/stdlib/2.7/distutils/emxccompiler.pyi
new file mode 100644
index 0000000..97e4a29
--- /dev/null
+++ b/typeshed/stdlib/2.7/distutils/emxccompiler.pyi
@@ -0,0 +1,5 @@
+# Stubs for emxccompiler
+
+from distutils.unixccompiler import UnixCCompiler
+
+class EMXCCompiler(UnixCCompiler): ...
diff --git a/typeshed/stdlib/2.7/distutils/version.pyi b/typeshed/stdlib/2.7/distutils/version.pyi
deleted file mode 100644
index a850144..0000000
--- a/typeshed/stdlib/2.7/distutils/version.pyi
+++ /dev/null
@@ -1,23 +0,0 @@
-# Stubs for distutils.version (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-class Version:
- def __init__(self, vstring=...) -> None: ...
-
-class StrictVersion(Version):
- version_re = ... # type: Any
- version = ... # type: Any
- prerelease = ... # type: Any
- def parse(self, vstring): ...
- def __cmp__(self, other): ...
-
-class LooseVersion(Version):
- component_re = ... # type: Any
- def __init__(self, vstring=...) -> None: ...
- vstring = ... # type: Any
- version = ... # type: Any
- def parse(self, vstring): ...
- def __cmp__(self, other): ...
diff --git a/typeshed/stdlib/2.7/email/utils.pyi b/typeshed/stdlib/2.7/email/utils.pyi
index 33e8894..48d2aa3 100644
--- a/typeshed/stdlib/2.7/email/utils.pyi
+++ b/typeshed/stdlib/2.7/email/utils.pyi
@@ -1,6 +1,6 @@
# Stubs for email.utils (Python 2)
#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+# Derived from stub automatically generated by stubgen.
from email._parseaddr import AddressList as _AddressList
from email._parseaddr import mktime_tz as mktime_tz
@@ -19,4 +19,4 @@ def unquote(str): ...
def decode_rfc2231(s): ...
def encode_rfc2231(s, charset=None, language=None): ...
def decode_params(params): ...
-def collapse_rfc2231_value(value, errors='', fallback_charset=''): ...
+def collapse_rfc2231_value(value, errors=..., fallback_charset=...): ...
diff --git a/typeshed/stdlib/2.7/functools.pyi b/typeshed/stdlib/2.7/functools.pyi
index c163764..8840765 100644
--- a/typeshed/stdlib/2.7/functools.pyi
+++ b/typeshed/stdlib/2.7/functools.pyi
@@ -24,7 +24,7 @@ def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Seque
updated: Sequence[str] = ...) -> None: ...
def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ...
def total_ordering(cls: type) -> type: ...
-def cmp_to_key(mycmp: Callable[[_T, _T], bool]) -> Callable[[_T], Any]: ...
+def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ...
class partial(Generic[_T]):
func = ... # Callable[..., _T]
diff --git a/typeshed/stdlib/2.7/gettext.pyi b/typeshed/stdlib/2.7/gettext.pyi
index 7752aa1..51dd523 100644
--- a/typeshed/stdlib/2.7/gettext.pyi
+++ b/typeshed/stdlib/2.7/gettext.pyi
@@ -14,28 +14,30 @@ def lngettext(singular: str, plural: str, n: int) -> str: ...
def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ...
def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ...
-class Translations(object):
+class NullTranslations(object):
+ def __init__(self, fp: IO[str] = ...) -> None: ...
def _parse(self, fp: IO[str]) -> None: ...
- def add_fallback(self, fallback: Any) -> None: ...
+ def add_fallback(self, fallback: NullTranslations) -> None: ...
def gettext(self, message: str) -> str: ...
def lgettext(self, message: str) -> str: ...
- def ugettext(self, message: str) -> unicode: ...
+ def ugettext(self, message: Union[str, unicode]) -> unicode: ...
def ngettext(self, singular: str, plural: str, n: int) -> str: ...
def lngettext(self, singular: str, plural: str, n: int) -> str: ...
- def ungettext(self, singular: str, plural: str, n: int) -> unicode: ...
+ def ungettext(self, singular: Union[str, unicode], plural: Union[str, unicode], n: int) -> unicode: ...
def info(self) -> Any: ...
def charset(self) -> Any: ...
def output_charset(self) -> Any: ...
def set_output_charset(self, charset: Any) -> None: ...
def install(self, unicode: bool = ..., names: Any = ...) -> None: ...
-class NullTranslations(Translations): ...
-class GNUTranslations(Translations): ...
+class GNUTranslations(NullTranslations):
+ LE_MAGIC = ... # type: int
+ BE_MAGIC = ... # type: int
def find(domain: str, localedir: str = ..., languages: List[str] = ...,
all: Any = ...) -> Optional[Union[str, List[str]]]: ...
def translation(domain: str, localedir: str = ..., languages: List[str] = ...,
- class_: Any = ..., fallback: Any = ..., codeset: Any = ...) -> Translations: ...
+ class_: Any = ..., fallback: Any = ..., codeset: Any = ...) -> NullTranslations: ...
def install(domain: str, localedir: str = ..., unicode: Any = ..., codeset: Any = ...,
names: Any = ...) -> None: ...
diff --git a/typeshed/stdlib/2.7/hmac.pyi b/typeshed/stdlib/2.7/hmac.pyi
deleted file mode 100644
index 65282cd..0000000
--- a/typeshed/stdlib/2.7/hmac.pyi
+++ /dev/null
@@ -1,13 +0,0 @@
-# Stubs for hmac (Python 2)
-
-from typing import Any, AnyStr
-
-class HMAC:
- def update(self, msg: str) -> None: ...
- def digest(self) -> str: ...
- def hexdigest(self) -> str: ...
- def copy(self) -> HMAC: ...
-
-def new(key: str, msg: str = ..., digestmod: Any = ...) -> HMAC: ...
-
-def compare_digest(a: AnyStr, b: AnyStr) -> bool: ...
diff --git a/typeshed/stdlib/2.7/inspect.pyi b/typeshed/stdlib/2.7/inspect.pyi
index 818f525..4800b29 100644
--- a/typeshed/stdlib/2.7/inspect.pyi
+++ b/typeshed/stdlib/2.7/inspect.pyi
@@ -9,8 +9,8 @@ ModuleInfo = NamedTuple('ModuleInfo', [('name', str),
('module_type', int),
])
def getmembers(object: object,
- predicate: Callable[[Any], bool] = ...,
- ) -> List[Tuple[str, object]]: ...
+ predicate: Callable[[Any], bool] = ...
+ ) -> List[Tuple[str, object]]: ...
def getmoduleinfo(path: str) -> Optional[ModuleInfo]: ...
def getmodulename(path: str) -> Optional[str]: ...
diff --git a/typeshed/stdlib/2.7/locale.pyi b/typeshed/stdlib/2.7/locale.pyi
deleted file mode 100644
index b79617e..0000000
--- a/typeshed/stdlib/2.7/locale.pyi
+++ /dev/null
@@ -1,33 +0,0 @@
-# Stubs for locale (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-from _locale import *
-
-class _unicode: ...
-
-CHAR_MAX = ... # type: Any
-LC_ALL = ... # type: Any
-LC_COLLATE = ... # type: Any
-LC_CTYPE = ... # type: Any
-LC_MESSAGES = ... # type: Any
-LC_MONETARY = ... # type: Any
-LC_NUMERIC = ... # type: Any
-LC_TIME = ... # type: Any
-Error = ... # type: Any
-
-def localeconv(): ...
-def strcoll(a, b): ...
-def strxfrm(s): ...
-def format(percent, value, grouping=False, monetary=False, *additional): ...
-def format_string(f, val, grouping=False): ...
-def currency(val, symbol=True, grouping=False, international=False): ...
-def str(val): ...
-def atof(string, func=...): ...
-def atoi(str): ...
-def normalize(localename): ...
-def getdefaultlocale(envvars=...): ...
-def getlocale(category=...): ...
-def resetlocale(category=...): ...
-def getpreferredencoding(do_setlocale=True): ...
diff --git a/typeshed/stdlib/2.7/mimetypes.pyi b/typeshed/stdlib/2.7/mimetypes.pyi
deleted file mode 100644
index a06fcd9..0000000
--- a/typeshed/stdlib/2.7/mimetypes.pyi
+++ /dev/null
@@ -1,26 +0,0 @@
-# Stubs for mimetypes (Python 2)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-class MimeTypes:
- encodings_map = ... # type: Any
- suffix_map = ... # type: Any
- types_map = ... # type: Any
- types_map_inv = ... # type: Any
- def __init__(self, filenames=..., strict=True): ...
- def add_type(self, type, ext, strict=True): ...
- def guess_type(self, url, strict=True): ...
- def guess_all_extensions(self, type, strict=True): ...
- def guess_extension(self, type, strict=True): ...
- def read(self, filename, strict=True): ...
- def readfp(self, fp, strict=True): ...
- def read_windows_registry(self, strict=True): ...
-
-def guess_type(url, strict=True): ...
-def guess_all_extensions(type, strict=True): ...
-def guess_extension(type, strict=True): ...
-def add_type(type, ext, strict=True): ...
-def init(files=None): ...
-def read_mime_types(file): ...
diff --git a/typeshed/stdlib/2.7/os/__init__.pyi b/typeshed/stdlib/2.7/os/__init__.pyi
index 3f9aa0d..4d8e014 100644
--- a/typeshed/stdlib/2.7/os/__init__.pyi
+++ b/typeshed/stdlib/2.7/os/__init__.pyi
@@ -4,7 +4,7 @@ from typing import (
List, Tuple, Union, Sequence, Mapping, IO, Any, Optional, AnyStr, Iterator,
MutableMapping, NamedTuple
)
-import os.path as path
+from os import path
error = OSError
name = ... # type: str
@@ -83,8 +83,8 @@ def isatty(fd: int) -> bool: ...
def lseek(fd: int, pos: int, how: int) -> None: ...
SEEK_SET = 0
-SEEK_CUR = 1
-SEEK_END = 2
+SEEK_CUR = 0
+SEEK_END = 0
# TODO(prvak): maybe file should be unicode? (same with all other paths...)
def open(file: unicode, flags: int, mode: int = ...) -> int: ...
@@ -257,11 +257,6 @@ 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
-F_OK = 0
-R_OK = 0
-W_OK = 0
-X_OK = 0
-
P_NOWAIT = 0
P_NOWAITO = 0
P_WAIT = 0
diff --git a/typeshed/stdlib/2.7/platform.pyi b/typeshed/stdlib/2.7/platform.pyi
index 83c61fa..a8c6693 100644
--- a/typeshed/stdlib/2.7/platform.pyi
+++ b/typeshed/stdlib/2.7/platform.pyi
@@ -1,33 +1,33 @@
# Stubs for platform (Python 2)
#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+# Based on stub generated by stubgen.
from typing import Any
__copyright__ = ... # type: Any
DEV_NULL = ... # type: Any
-def libc_ver(executable=..., lib='', version='', chunksize=2048): ...
-def linux_distribution(distname='', version='', id='', supported_dists=..., full_distribution_name=1): ...
-def dist(distname='', version='', id='', supported_dists=...): ...
+def libc_ver(executable=..., lib=..., version=..., chunksize=2048): ...
+def linux_distribution(distname=..., version=..., id=..., supported_dists=..., full_distribution_name=1): ...
+def dist(distname=..., version=..., id=..., supported_dists=...): ...
class _popen:
tmpfile = ... # type: Any
pipe = ... # type: Any
bufsize = ... # type: Any
mode = ... # type: Any
- def __init__(self, cmd, mode='', bufsize=None): ...
+ def __init__(self, cmd, mode=..., bufsize=None): ...
def read(self): ...
def readlines(self): ...
def close(self, remove=..., error=...): ...
__del__ = ... # type: Any
-def popen(cmd, mode='', bufsize=None): ...
-def win32_ver(release='', version='', csd='', ptype=''): ...
-def mac_ver(release='', versioninfo=..., machine=''): ...
-def java_ver(release='', vendor='', vminfo=..., osinfo=...): ...
+def popen(cmd, mode=..., bufsize=None): ...
+def win32_ver(release=..., version=..., csd=..., ptype=...): ...
+def mac_ver(release=..., versioninfo=..., machine=...): ...
+def java_ver(release=..., vendor=..., vminfo=..., osinfo=...): ...
def system_alias(system, release, version): ...
-def architecture(executable=..., bits='', linkage=''): ...
+def architecture(executable=..., bits=..., linkage=...): ...
def uname(): ...
def system(): ...
def node(): ...
diff --git a/typeshed/stdlib/2.7/rfc822.pyi b/typeshed/stdlib/2.7/rfc822.pyi
index 1c2b032..636a985 100644
--- a/typeshed/stdlib/2.7/rfc822.pyi
+++ b/typeshed/stdlib/2.7/rfc822.pyi
@@ -1,6 +1,6 @@
# Stubs for rfc822 (Python 2)
#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+# Based on stub generated by stubgen.
from typing import Any
@@ -33,7 +33,7 @@ class Message:
def __getitem__(self, name): ...
def __setitem__(self, name, value): ...
def __delitem__(self, name): ...
- def setdefault(self, name, default=''): ...
+ def setdefault(self, name, default=...): ...
def has_key(self, name): ...
def __contains__(self, name): ...
def __iter__(self): ...
diff --git a/typeshed/stdlib/2.7/simplejson/__init__.pyi b/typeshed/stdlib/2.7/simplejson/__init__.pyi
index 84e6483..d34e42b 100644
--- a/typeshed/stdlib/2.7/simplejson/__init__.pyi
+++ b/typeshed/stdlib/2.7/simplejson/__init__.pyi
@@ -5,6 +5,6 @@ def dump(obj: Any, fp: IO[str], *args: Any, **kwds: Any) -> None: ...
def loads(s: str, **kwds: Any) -> Any: ...
def load(fp: IO[str]) -> Any: ...
-from .scanner import JSONDecodeError
-from .decoder import JSONDecoder
-from .encoder import JSONEncoder, JSONEncoderForHTML
+from simplejson.scanner import JSONDecodeError
+from simplejson.decoder import JSONDecoder
+from simplejson.encoder import JSONEncoder, JSONEncoderForHTML
diff --git a/typeshed/stdlib/2.7/socket.pyi b/typeshed/stdlib/2.7/socket.pyi
index e12e35c..d99a127 100644
--- a/typeshed/stdlib/2.7/socket.pyi
+++ b/typeshed/stdlib/2.7/socket.pyi
@@ -22,7 +22,7 @@ SOCK_CLOEXEC = 0
SOCK_NONBLOCK = 0
SOMAXCONN = 0
has_ipv6 = False
-_GLOBAL_DEFAULT_TIMEOUT = 0.0
+_GLOBAL_DEFAULT_TIMEOUT = ... # type: Any
SocketType = ... # type: Any
SocketIO = ... # type: Any
diff --git a/typeshed/stdlib/2.7/sqlite3/dbapi2.pyi b/typeshed/stdlib/2.7/sqlite3/dbapi2.pyi
index 42a7f30..5ef3a3c 100644
--- a/typeshed/stdlib/2.7/sqlite3/dbapi2.pyi
+++ b/typeshed/stdlib/2.7/sqlite3/dbapi2.pyi
@@ -106,7 +106,7 @@ class Connection:
def create_aggregate(self, name: str, num_params: int, aggregate_class: type) -> None: ...
def create_collation(self, name: str, callable: Any) -> None: ...
def create_function(self, name: str, num_params: int, func: Any) -> None: ...
- def cursor(self, cursorClass= Union[type, None]) -> Cursor: ...
+ def cursor(self, cursorClass=...) -> Cursor: ...
def execute(self, sql: str, parameters: Iterable = ...) -> Cursor: ...
# TODO: please check in executemany() if seq_of_parameters type is possible like this
def executemany(self, sql: str, seq_of_parameters: Iterable[Iterable]) -> Cursor: ...
diff --git a/typeshed/stdlib/2.7/ssl.pyi b/typeshed/stdlib/2.7/ssl.pyi
index 103fc45..1225d9a 100644
--- a/typeshed/stdlib/2.7/ssl.pyi
+++ b/typeshed/stdlib/2.7/ssl.pyi
@@ -1,190 +1,204 @@
-# Stubs for ssl (Python 2)
-
-from typing import Any
-from socket import socket, error as socket_error
-from collections import namedtuple
-
-class SSLError(OSError): ...
-class SSLEOFError(SSLError): ...
-class SSLSyscallError(SSLError): ...
+# Stubs for ssl
+
+from typing import (
+ Any, Dict, Callable, List, NamedTuple, Optional, Set, Tuple, Union,
+)
+import socket
+import sys
+
+_PCTRTT = Tuple[Tuple[str, str], ...]
+_PCTRTTT = Tuple[_PCTRTT, ...]
+_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]]
+_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None]
+_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]]
+_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes]
+_SrvnmeCbType = Callable[['SSLSocket', Optional[str], 'SSLSocket'], Optional[int]]
+
+class SSLError(OSError):
+ library = ... # type: str
+ reason = ... # type: str
+class SSLZeroReturnError(SSLError): ...
class SSLWantReadError(SSLError): ...
class SSLWantWriteError(SSLError): ...
-class SSLZeroReturnError(SSLError): ...
+class SSLSyscallError(SSLError): ...
+class SSLEOFError(SSLError): ...
+class CertificateError(Exception): ...
-OPENSSL_VERSION = ... # type: str
-OPENSSL_VERSION_INFO = ... # type: Any
-OPENSSL_VERSION_NUMBER = ... # type: int
-VERIFY_CRL_CHECK_CHAIN = ... # type: int
-VERIFY_CRL_CHECK_LEAF = ... # type: int
-VERIFY_DEFAULT = ... # type: int
-VERIFY_X509_STRICT = ... # type: int
+def wrap_socket(sock: socket.socket, keyfile: Optional[str] = ...,
+ certfile: Optional[str] = ..., server_side: bool = ...,
+ cert_reqs: int = ..., ssl_version: int = ...,
+ ca_certs: Optional[str] = ...,
+ do_handshake_on_connect: bool = ...,
+ suppress_ragged_eofs: bool = ...,
+ ciphers: Optional[str] = ...) -> 'SSLSocket': ...
-ALERT_DESCRIPTION_ACCESS_DENIED = ... # type: int
-ALERT_DESCRIPTION_BAD_CERTIFICATE = ... # type: int
-ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = ... # type: int
-ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = ... # type: int
-ALERT_DESCRIPTION_BAD_RECORD_MAC = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_REVOKED = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = ... # type: int
-ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = ... # type: int
-ALERT_DESCRIPTION_CLOSE_NOTIFY = ... # type: int
-ALERT_DESCRIPTION_DECODE_ERROR = ... # type: int
-ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = ... # type: int
-ALERT_DESCRIPTION_DECRYPT_ERROR = ... # type: int
-ALERT_DESCRIPTION_HANDSHAKE_FAILURE = ... # type: int
-ALERT_DESCRIPTION_ILLEGAL_PARAMETER = ... # type: int
-ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = ... # type: int
-ALERT_DESCRIPTION_INTERNAL_ERROR = ... # type: int
-ALERT_DESCRIPTION_NO_RENEGOTIATION = ... # type: int
-ALERT_DESCRIPTION_PROTOCOL_VERSION = ... # type: int
-ALERT_DESCRIPTION_RECORD_OVERFLOW = ... # type: int
-ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = ... # type: int
-ALERT_DESCRIPTION_UNKNOWN_CA = ... # type: int
-ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = ... # type: int
-ALERT_DESCRIPTION_UNRECOGNIZED_NAME = ... # type: int
-ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = ... # type: int
-ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = ... # type: int
-ALERT_DESCRIPTION_USER_CANCELLED = ... # type: int
-OP_ALL = ... # type: int
-OP_CIPHER_SERVER_PREFERENCE = ... # type: int
-OP_NO_COMPRESSION = ... # type: int
-OP_NO_SSLv2 = ... # type: int
-OP_NO_SSLv3 = ... # type: int
-OP_NO_TLSv1 = ... # type: int
-OP_NO_TLSv1_1 = ... # type: int
-OP_NO_TLSv1_2 = ... # type: int
-OP_SINGLE_DH_USE = ... # type: int
-OP_SINGLE_ECDH_USE = ... # type: int
+def create_default_context(purpose: Any = ..., *,
+ cafile: Optional[str] = ...,
+ capath: Optional[str] = ...,
+ cadata: Optional[str] = ...) -> 'SSLContext': ...
+
+
+def RAND_status() -> bool: ...
+def RAND_egd(path: str) -> None: ...
+def RAND_add(bytes: bytes, entropy: float) -> None: ...
+
+
+def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ...
+def cert_time_to_seconds(cert_time: str) -> int: ...
+def get_server_certificate(addr: Tuple[str, int], ssl_version: int = ...,
+ ca_certs: Optional[str] = ...) -> str: ...
+def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ...
+def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ...
+DefaultVerifyPaths = NamedTuple('DefaultVerifyPaths',
+ [('cafile', str), ('capath', str),
+ ('openssl_cafile_env', str),
+ ('openssl_cafile', str),
+ ('openssl_capath_env', str),
+ ('openssl_capath', str)])
+def get_default_verify_paths() -> DefaultVerifyPaths: ...
+
+if sys.platform == 'win32':
+ def enum_certificates(store_name: str) -> _EnumRetType: ...
+ def enum_crls(store_name: str) -> _EnumRetType: ...
-SSL_ERROR_EOF = ... # type: int
-SSL_ERROR_INVALID_ERROR_CODE = ... # type: int
-SSL_ERROR_SSL = ... # type: int
-SSL_ERROR_SYSCALL = ... # type: int
-SSL_ERROR_WANT_CONNECT = ... # type: int
-SSL_ERROR_WANT_READ = ... # type: int
-SSL_ERROR_WANT_WRITE = ... # type: int
-SSL_ERROR_WANT_X509_LOOKUP = ... # type: int
-SSL_ERROR_ZERO_RETURN = ... # type: int
CERT_NONE = ... # type: int
CERT_OPTIONAL = ... # type: int
CERT_REQUIRED = ... # type: int
+VERIFY_DEFAULT = ... # type: int
+VERIFY_CRL_CHECK_LEAF = ... # type: int
+VERIFY_CRL_CHECK_CHAIN = ... # type: int
+VERIFY_X509_STRICT = ... # type: int
+VERIFY_X509_TRUSTED_FIRST = ... # type: int
+
PROTOCOL_SSLv23 = ... # type: int
+PROTOCOL_SSLv2 = ... # type: int
PROTOCOL_SSLv3 = ... # type: int
PROTOCOL_TLSv1 = ... # type: int
PROTOCOL_TLSv1_1 = ... # type: int
PROTOCOL_TLSv1_2 = ... # type: int
+OP_ALL = ... # type: int
+OP_NO_SSLv2 = ... # type: int
+OP_NO_SSLv3 = ... # type: int
+OP_NO_TLSv1 = ... # type: int
+OP_NO_TLSv1_1 = ... # type: int
+OP_NO_TLSv1_2 = ... # type: int
+OP_CIPHER_SERVER_PREFERENCE = ... # type: int
+OP_SINGLE_DH_USE = ... # type: int
+OP_SINGLE_ECDH_USE = ... # type: int
+OP_NO_COMPRESSION = ... # type: int
+
+HAS_ALPN = ... # type: int
HAS_ECDH = ... # type: bool
-HAS_NPN = ... # type: bool
HAS_SNI = ... # type: bool
+HAS_NPN = ... # type: bool
+CHANNEL_BINDING_TYPES = ... # type: List[str]
+
+OPENSSL_VERSION = ... # type: str
+OPENSSL_VERSION_INFO = ... # type: Tuple[int, int, int, int, int]
+OPENSSL_VERSION_NUMBER = ... # type: int
-CHANNEL_BINDING_TYPES = ... # type: Any
-
-class CertificateError(ValueError): ...
-
-def match_hostname(cert, hostname): ...
-
-DefaultVerifyPaths = namedtuple('DefaultVerifyPaths', 'cafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capath')
-
-def get_default_verify_paths(): ...
-
-class _ASN1Object:
- def __new__(cls, oid): ...
- @classmethod
- def fromnid(cls, nid): ...
- @classmethod
- def fromname(cls, name): ...
-
-class Purpose(_ASN1Object):
- SERVER_AUTH = ... # type: Purpose
- CLIENT_AUTH = ... # type: Purpose
-
-class _SSLContext:
- check_hostname = ... # type: Any
- options = ... # type: Any
- verify_flags = ... # type: Any
- verify_mode = ... # type: Any
- def __init__(self, *args, **kwargs) -> None: ...
- def _set_npn_protocols(self, *args, **kwargs): ...
- def _wrap_socket(self, *args, **kwargs): ...
- def cert_store_stats(self): ...
- def get_ca_certs(self, binary_form=...): ...
- def load_cert_chain(self, *args, **kwargs): ...
- def load_dh_params(self, *args, **kwargs): ...
- def load_verify_locations(self, *args, **kwargs): ...
- def session_stats(self, *args, **kwargs): ...
- def set_ciphers(self, *args, **kwargs): ...
- def set_default_verify_paths(self, *args, **kwargs): ...
- def set_ecdh_curve(self, *args, **kwargs): ...
- def set_servername_callback(self, method): ...
-
-class SSLContext(_SSLContext):
- def __new__(cls, protocol, *args, **kwargs): ...
- protocol = ... # type: Any
- def __init__(self, protocol): ...
- def wrap_socket(self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None): ...
- def set_npn_protocols(self, npn_protocols): ...
- def set_alpn_protocols(self, alpn_protocols): ...
- def load_default_certs(self, purpose=...): ...
-
-def create_default_context(purpose=..., cafile=None, capath=None, cadata=None): ...
-
-class SSLSocket(socket):
- keyfile = ... # type: Any
- certfile = ... # type: Any
- cert_reqs = ... # type: Any
- ssl_version = ... # type: Any
- ca_certs = ... # type: Any
- ciphers = ... # type: Any
- server_side = ... # type: Any
- server_hostname = ... # type: Any
- do_handshake_on_connect = ... # type: Any
- suppress_ragged_eofs = ... # type: Any
- def __init__(self, sock=None, keyfile=None, certfile=None, server_side=False, cert_reqs=..., ssl_version=..., ca_certs=None, do_handshake_on_connect=True, family=..., type=..., proto=0, fileno=None, suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, server_hostname=None, _context=None): ...
+ALERT_DESCRIPTION_HANDSHAKE_FAILURE = ... # type: int
+ALERT_DESCRIPTION_INTERNAL_ERROR = ... # type: int
+ALERT_DESCRIPTION_ACCESS_DENIED = ... # type: int
+ALERT_DESCRIPTION_BAD_CERTIFICATE = ... # type: int
+ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = ... # type: int
+ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = ... # type: int
+ALERT_DESCRIPTION_BAD_RECORD_MAC = ... # type: int
+ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = ... # type: int
+ALERT_DESCRIPTION_CERTIFICATE_REVOKED = ... # type: int
+ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = ... # type: int
+ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = ... # type: int
+ALERT_DESCRIPTION_CLOSE_NOTIFY = ... # type: int
+ALERT_DESCRIPTION_DECODE_ERROR = ... # type: int
+ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = ... # type: int
+ALERT_DESCRIPTION_DECRYPT_ERROR = ... # type: int
+ALERT_DESCRIPTION_ILLEGAL_PARAMETER = ... # type: int
+ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = ... # type: int
+ALERT_DESCRIPTION_NO_RENEGOTIATION = ... # type: int
+ALERT_DESCRIPTION_PROTOCOL_VERSION = ... # type: int
+ALERT_DESCRIPTION_RECORD_OVERFLOW = ... # type: int
+ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = ... # type: int
+ALERT_DESCRIPTION_UNKNOWN_CA = ... # type: int
+ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = ... # type: int
+ALERT_DESCRIPTION_UNRECOGNIZED_NAME = ... # type: int
+ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = ... # type: int
+ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = ... # type: int
+ALERT_DESCRIPTION_USER_CANCELLED = ... # type: int
+
+_PurposeType = NamedTuple('_PurposeType',
+ [('nid', int), ('shortname', str),
+ ('longname', str), ('oid', str)])
+class Purpose:
+ SERVER_AUTH = ... # type: _PurposeType
+ CLIENT_AUTH = ... # type: _PurposeType
+
+
+class SSLSocket(socket.socket):
+ def do_handshake(self) -> None: ...
+ def getpeercert(self, binary_form: bool = ...) -> _PeerCertRetType: ...
+ def cipher(self) -> Tuple[str, int, int]: ...
+ def compression(self) -> Optional[str]: ...
+ def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ...
+ def selected_alpn_protocol(self) -> Optional[str]: ...
+ def selected_npn_protocol(self) -> Optional[str]: ...
+ def unwrap(self) -> socket.socket: ...
+ def version(self) -> Optional[str]: ...
+
+
+class SSLContext:
+ check_hostname = ... # type: bool
+ options = ... # type: int
@property
- def context(self): ...
- @context.setter
- def context(self, ctx): ...
- def dup(self): ...
- def read(self, len=0, buffer=None): ...
- def write(self, data): ...
- def getpeercert(self, binary_form=False): ...
- def selected_npn_protocol(self): ...
- def selected_alpn_protocol(self): ...
- def cipher(self): ...
- def compression(self): ...
- def send(self, data, flags=0): ...
- def sendto(self, data, flags_or_addr, addr=None): ...
- def sendall(self, data, flags=0): ...
- def recv(self, buflen=1024, flags=0): ...
- def recv_into(self, buffer, nbytes=None, flags=0): ...
- def recvfrom(self, buflen=1024, flags=0): ...
- def recvfrom_into(self, buffer, nbytes=None, flags=0): ...
- def pending(self): ...
- def shutdown(self, how): ...
- def close(self): ...
- def unwrap(self): ...
- def do_handshake(self, block=False): ...
- def connect(self, addr): ...
- def connect_ex(self, addr): ...
- def accept(self): ...
- def makefile(self, mode='', bufsize=-1): ...
- def get_channel_binding(self, cb_type=''): ...
- def version(self): ...
-
-def wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=..., ssl_version=..., ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None): ...
-def cert_time_to_seconds(cert_time): ...
-
-PEM_HEADER = ... # type: Any
-PEM_FOOTER = ... # type: Any
-
-def DER_cert_to_PEM_cert(der_cert_bytes): ...
-def PEM_cert_to_DER_cert(pem_cert_string): ...
-def get_server_certificate(addr, ssl_version=..., ca_certs=None): ...
-def get_protocol_name(protocol_code): ...
-def sslwrap_simple(sock, keyfile=None, certfile=None): ...
+ def protocol(self) -> int: ...
+ verify_flags = ... # type: int
+ verify_mode = ... # type: int
+ def __init__(self, protocol: int) -> None: ...
+ def cert_store_stats(self) -> Dict[str, int]: ...
+ def load_cert_chain(self, certfile: str, keyfile: Optional[str] = ...,
+ password: _PasswordType = ...) -> None: ...
+ def load_default_certs(self, purpose: _PurposeType = ...) -> None: ...
+ def load_verify_locations(self, cafile: Optional[str] = ...,
+ capath: Optional[str] = ...,
+ cadata: Union[str, bytes, None] = ...) -> None: ...
+ def get_ca_certs(self,
+ binary_form: bool = ...) -> Union[List[_PeerCertRetDictType], List[bytes]]: ...
+ def set_default_verify_paths(self) -> None: ...
+ def set_ciphers(self, ciphers: str) -> None: ...
+ def set_alpn_protocols(protocols: List[str]) -> None: ...
+ def set_npn_protocols(protocols: List[str]) -> None: ...
+ def set_servername_callback(self,
+ server_name_callback: Optional[_SrvnmeCbType]) -> None: ...
+ def load_dh_params(self, dhfile: str) -> None: ...
+ def set_ecdh_curve(self, curve_name: str) -> None: ...
+ def wrap_socket(self, sock: socket.socket, server_side: bool = ...,
+ do_handshake_on_connect: bool = ...,
+ suppress_ragged_eofs: bool = ...,
+ server_hostname: Optional[str] = ...) -> 'SSLContext': ...
+ def session_stats(self) -> Dict[str, int]: ...
+
+
+# TODO below documented in cpython but not in docs.python.org
+# taken from python 3.4
+SSL_ERROR_EOF = ... # type: int
+SSL_ERROR_INVALID_ERROR_CODE = ... # type: int
+SSL_ERROR_SSL = ... # type: int
+SSL_ERROR_SYSCALL = ... # type: int
+SSL_ERROR_WANT_CONNECT = ... # type: int
+SSL_ERROR_WANT_READ = ... # type: int
+SSL_ERROR_WANT_WRITE = ... # type: int
+SSL_ERROR_WANT_X509_LOOKUP = ... # type: int
+SSL_ERROR_ZERO_RETURN = ... # type: int
+
+def get_protocol_name(protocol_code: int) -> str: ...
+
+AF_INET = ... # type: int
+PEM_FOOTER = ... # type: str
+PEM_HEADER = ... # type: str
+SOCK_STREAM = ... # type: int
+SOL_SOCKET = ... # type: int
+SO_TYPE = ... # type: int
diff --git a/typeshed/stdlib/2.7/stat.pyi b/typeshed/stdlib/2.7/stat.pyi
index b158ff7..dd3418d 100644
--- a/typeshed/stdlib/2.7/stat.pyi
+++ b/typeshed/stdlib/2.7/stat.pyi
@@ -33,6 +33,7 @@ S_IRWXU = 0
S_IRUSR = 0
S_IWUSR = 0
S_IXUSR = 0
+S_IRWXG = 0
S_IRGRP = 0
S_IWGRP = 0
S_IXGRP = 0
diff --git a/typeshed/stdlib/2.7/subprocess.pyi b/typeshed/stdlib/2.7/subprocess.pyi
index df8da0a..f3b1eb4 100644
--- a/typeshed/stdlib/2.7/subprocess.pyi
+++ b/typeshed/stdlib/2.7/subprocess.pyi
@@ -72,17 +72,17 @@ class Popen:
def __init__(self,
args: Union[str, Sequence[str]],
bufsize: int = ...,
- executable: str = ...,
- stdin: _FILE = ...,
- stdout: _FILE = ...,
- stderr: _FILE = ...,
- preexec_fn: Callable[[], Any] = ...,
+ executable: Optional[str] = ...,
+ stdin: Optional[_FILE] = ...,
+ stdout: Optional[_FILE] = ...,
+ stderr: Optional[_FILE] = ...,
+ preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
- cwd: str = ...,
- env: Mapping[str, str] = ...,
+ cwd: Optional[str] = ...,
+ env: Optional[Mapping[str, str]] = ...,
universal_newlines: bool = ...,
- startupinfo: Any = ...,
+ startupinfo: Optional[Any] = ...,
creationflags: int = ...) -> None: ...
def poll(self) -> int: ...
diff --git a/typeshed/stdlib/2.7/sys.pyi b/typeshed/stdlib/2.7/sys.pyi
index 3576159..e373328 100644
--- a/typeshed/stdlib/2.7/sys.pyi
+++ b/typeshed/stdlib/2.7/sys.pyi
@@ -1,9 +1,10 @@
"""Stubs for the 'sys' module."""
from typing import (
- IO, Union, List, Sequence, Any, Dict, Tuple, BinaryIO, Optional, Callable, overload
+ IO, Union, List, Sequence, Any, Dict, Tuple, BinaryIO, Optional, Callable,
+ overload, Type,
)
-from types import FrameType, ModuleType, TracebackType
+from types import FrameType, ModuleType, TracebackType, ClassType
class _flags:
bytes_warning = ... # type: int
@@ -86,6 +87,9 @@ path_hooks = ... # type: List[Any]
path_importer_cache = ... # type: Dict[str, Any]
displayhook = ... # type: Optional[Callable[[int], None]]
excepthook = ... # type: Optional[Callable[[type, BaseException, TracebackType], None]]
+exc_type = ... # type: Optional[type]
+exc_value = ... # type: Union[BaseException, ClassType]
+exc_traceback = ... # type: TracebackType
class _WindowsVersionType:
major = ... # type: Any
@@ -109,7 +113,7 @@ def __excepthook__(type_: type, value: BaseException, traceback: TracebackType)
def exc_clear() -> None:
raise DeprecationWarning()
# TODO should be a union of tuple, see mypy#1178
-def exc_info() -> Tuple[Optional[type],
+def exc_info() -> Tuple[Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType]]: ...
diff --git a/typeshed/stdlib/2.7/threading.pyi b/typeshed/stdlib/2.7/threading.pyi
deleted file mode 100644
index 3c0c78c..0000000
--- a/typeshed/stdlib/2.7/threading.pyi
+++ /dev/null
@@ -1,95 +0,0 @@
-# Stubs for threading
-
-from typing import Any, Optional, Callable, TypeVar, Union, List, Mapping, Sequence
-
-def active_count() -> int: ...
-def activeCount() -> int: ...
-
-def current_thread() -> Thread: ...
-def currentThread() -> Thread: ...
-def enumerate() -> List[Thread]: ...
-
-class Thread(object):
- name = ... # type: str
- ident = 0
- daemon = False
-
- def __init__(self, group: Any = ..., target: Callable[..., Any] = ...,
- name: str = ..., args: Sequence[Any] = ...,
- kwargs: Mapping[str, Any] = ...) -> None: ...
- def start(self) -> None: ...
- def run(self) -> None: ...
- def join(self, timeout: float = ...) -> None: ...
- def is_alive(self) -> bool: ...
-
- # Legacy methods
- def isAlive(self) -> bool: ...
- def getName(self) -> str: ...
- def setName(self, name: str) -> None: ...
- def isDaemon(self) -> bool: ...
- def setDaemon(self, daemon: bool) -> None: ...
-
-class Timer(Thread):
- def __init__(self, interval: float, function: Callable[..., Any],
- args: Sequence[Any] = ...,
- kwargs: Mapping[str, Any] = ...) -> None: ...
- def cancel(self) -> None : ...
-
-# TODO: better type
-def settrace(func: Callable[[Any, str, Any], Any]) -> None: ...
-def setprofile(func: Any) -> None: ...
-def stack_size(size: int = ...) -> None: ...
-
-class ThreadError(Exception):
- pass
-
-class local(Any): ...
-
-class Event(object):
- def is_set(self) -> bool: ...
- def isSet(self) -> bool: ...
- def set(self) -> None: ...
- def clear(self) -> None: ...
- # TODO can it return None?
- def wait(self, timeout: float = ...) -> bool: ...
-
-class Lock(object):
- def acquire(self, blocking: bool = ...) -> bool: ...
- def release(self) -> None: ...
- def locked(self) -> bool: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
-
-class RLock(object):
- def acquire(self, blocking: int = ...) -> Optional[bool]: ...
- def release(self) -> None: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
-
-class Semaphore(object):
- def acquire(self, blocking: bool = ...) -> Optional[bool]: ...
- def release(self) -> None: ...
- def __init__(self, value: int = ...) -> None: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
-
-class BoundedSemaphore(Semaphore):
- def acquire(self, blocking: bool = ...) -> Optional[bool]: ...
- def release(self) -> None: ...
- def __init__(self, value: int = ...) -> None: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
-
-_T = TypeVar('_T')
-
-class Condition(object):
- def acquire(self, blocking: bool = ...) -> bool: ...
- def release(self) -> None: ...
- def notify(self, n: int = ...) -> None: ...
- def notify_all(self) -> None: ...
- def notifyAll(self) -> None: ...
- def wait(self, timeout: float = ...) -> bool: ...
- def wait_for(self, predicate: Callable[[], _T], timeout: float = ...) -> Union[_T, bool]: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
- def __init__(self, lock: Lock = ...) -> None: ...
diff --git a/typeshed/stdlib/2.7/traceback.pyi b/typeshed/stdlib/2.7/traceback.pyi
deleted file mode 100644
index 6f7387a..0000000
--- a/typeshed/stdlib/2.7/traceback.pyi
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Any, IO, AnyStr, Callable, Tuple, List
-from types import TracebackType, FrameType
-
-ExtractTbResult = List[Tuple[str, int, str, str]]
-
-def print_tb(traceback: TracebackType, limit: int = ..., file: IO[str] = ...) -> None: ...
-def print_exception(type: type, value: Exception, limit: int = ..., file: IO[str] = ...) -> None: ...
-def print_exc(limit: int = ..., file: IO[str] = ...) -> None: ...
-def format_exc(limit: int = ...) -> str: ...
-def print_last(limit: int = ..., file: IO[str] = ...) -> None: ...
-def print_stack(f: FrameType = ..., limit: int = ..., file: IO[AnyStr] = ...) -> None: ...
-def extract_tb(f: TracebackType, limit: int = ...) -> ExtractTbResult: ...
-def extract_stack(f: FrameType = ..., limit: int = ...) -> ExtractTbResult: ...
-def format_list(list: ExtractTbResult) -> List[str]: ...
-def format_exception_only(type: type, value: List[str]) -> List[str]: ...
-def format_exception(type: type, value: BaseException, tb: TracebackType, limit: int = ...) -> List[str]: ...
-def format_tb(f: TracebackType, limit: int = ...) -> List[str]: ...
-def format_stack(f: FrameType = ..., limit: int = ...) -> List[str]: ...
-def tb_lineno(tb: TracebackType) -> AnyStr: ...
-def _print(f: IO[str], str: str = ..., terminator: str = ...) -> None: ...
diff --git a/typeshed/stdlib/2.7/typing.pyi b/typeshed/stdlib/2.7/typing.pyi
index bee6314..dc1497c 100644
--- a/typeshed/stdlib/2.7/typing.pyi
+++ b/typeshed/stdlib/2.7/typing.pyi
@@ -16,6 +16,7 @@ Type = object()
builtinclass = object()
_promote = object()
NamedTuple = object()
+NewType = object()
# Type aliases
@@ -43,6 +44,7 @@ _KT = TypeVar('_KT') # Key type.
_VT = TypeVar('_VT') # Value type.
_T_co = TypeVar('_T_co', covariant=True) # Any type covariant containers.
_V_co = TypeVar('_V_co', covariant=True) # Any type covariant containers.
+_KT_co = TypeVar('_KT_co', covariant=True) # Key type covariant containers.
_VT_co = TypeVar('_VT_co', covariant=True) # Value type covariant containers.
_T_contra = TypeVar('_T_contra', contravariant=True) # Ditto contravariant.
@@ -117,7 +119,7 @@ class MutableSequence(Sequence[_T], Generic[_T]):
def __setitem__(self, i: int, o: _T) -> None: ...
@overload
@abstractmethod
- def __setitem__(self, s: slice, o: Sequence[_T]) -> None: ...
+ def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ...
@abstractmethod
def __delitem__(self, i: Union[int, slice]) -> None: ...
# Mixin methods
@@ -143,6 +145,8 @@ class AbstractSet(Sized, Iterable[_T_co], Container[_T_co], Generic[_T_co]):
# TODO: argument can be any container?
def isdisjoint(self, s: AbstractSet[Any]) -> bool: ...
+class FrozenSet(AbstractSet[_T], Generic[_T]): ...
+
class MutableSet(AbstractSet[_T], Generic[_T]):
@abstractmethod
def add(self, x: _T) -> None: ...
@@ -157,6 +161,21 @@ class MutableSet(AbstractSet[_T], Generic[_T]):
def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ...
def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ...
+class MappingView(Sized):
+ def __len__(self) -> int: ...
+
+class ItemsView(AbstractSet[Tuple[_KT_co, _VT_co]], MappingView, Generic[_KT_co, _VT_co]):
+ def __contains__(self, o: object) -> bool: ...
+ def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ...
+
+class KeysView(AbstractSet[_KT_co], MappingView, Generic[_KT_co]):
+ def __contains__(self, o: object) -> bool: ...
+ def __iter__(self) -> Iterator[_KT_co]: ...
+
+class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]):
+ def __contains__(self, o: object) -> bool: ...
+ def __iter__(self) -> Iterator[_VT_co]: ...
+
class Mapping(Sized, Iterable[_KT], Container[_KT], Generic[_KT, _VT]):
@abstractmethod
def __getitem__(self, k: _KT) -> _VT: ...
@@ -319,3 +338,7 @@ class Pattern(Generic[AnyStr]):
@overload
def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr,
count: int = ...) -> Tuple[AnyStr, int]: ...
+
+# Functions
+
+def get_type_hints(obj: Callable) -> dict[str, Any]: ...
diff --git a/typeshed/stdlib/2.7/unittest.pyi b/typeshed/stdlib/2.7/unittest.pyi
index a914cec..9c9ba90 100644
--- a/typeshed/stdlib/2.7/unittest.pyi
+++ b/typeshed/stdlib/2.7/unittest.pyi
@@ -27,7 +27,7 @@ class TestResult:
errors = ... # type: List[Tuple[Testable, str]]
failures = ... # type: List[Tuple[Testable, str]]
testsRun = 0
- shouldStop = False
+ shouldStop = ... # type: bool
def wasSuccessful(self) -> bool: ...
def stop(self) -> None: ...
diff --git a/typeshed/stdlib/2.7/urllib2.pyi b/typeshed/stdlib/2.7/urllib2.pyi
index fba73a0..0ce8a7a 100644
--- a/typeshed/stdlib/2.7/urllib2.pyi
+++ b/typeshed/stdlib/2.7/urllib2.pyi
@@ -1,10 +1,13 @@
-from typing import AnyStr
+from typing import AnyStr, Dict, Union
from urllib import addinfourl
-class URLError(IOError): ...
+class URLError(IOError):
+ reason = ... # type: Union[str, BaseException]
-class HTTPError(URLError, addinfourl): ...
+class HTTPError(URLError, addinfourl):
+ code = ... # type: int
+ headers = ... # type: Dict[str, str]
class Request(object):
host = ... # type: str
@@ -61,8 +64,10 @@ class HTTPRedirectHandler(BaseHandler):
max_repeats = ... # int
max_redirections = ... # int
def redirect_request(self, req, fp, code, msg, headers, newurl): ...
+ def http_error_301(self, req, fp, code, msg, headers): ...
def http_error_302(self, req, fp, code, msg, headers): ...
- http_error_301 = http_error_303 = http_error_307 = http_error_302
+ def http_error_303(self, req, fp, code, msg, headers): ...
+ def http_error_307(self, req, fp, code, msg, headers): ...
inf_msg = ... # type: str
@@ -120,12 +125,12 @@ class AbstractHTTPHandler(BaseHandler):
class HTTPHandler(AbstractHTTPHandler):
def http_open(self, req): ...
- http_request = AbstractHTTPHandler.do_request_
+ def http_request(self, request): ...
class HTTPSHandler(AbstractHTTPHandler):
def __init__(self, debuglevel=0, context=None): ...
def https_open(self, req): ...
- https_request = AbstractHTTPHandler.do_request_
+ def https_request(self, request): ...
class HTTPCookieProcessor(BaseHandler):
def __init__(self, cookiejar=None): ...
diff --git a/typeshed/stdlib/2.7/xml/etree/ElementInclude.pyi b/typeshed/stdlib/2.7/xml/etree/ElementInclude.pyi
index a9e04f2..09acc8f 100644
--- a/typeshed/stdlib/2.7/xml/etree/ElementInclude.pyi
+++ b/typeshed/stdlib/2.7/xml/etree/ElementInclude.pyi
@@ -3,7 +3,7 @@
# NOTE: This dynamically typed stub was automatically generated by stubgen.
from typing import Union, Optional, Callable
-from .ElementTree import Element
+from xml.etree.ElementTree import Element
XINCLUDE = ... # type: str
XINCLUDE_INCLUDE = ... # type: str
diff --git a/typeshed/stdlib/2.7/xml/etree/ElementPath.pyi b/typeshed/stdlib/2.7/xml/etree/ElementPath.pyi
index e17e5bb..e057b88 100644
--- a/typeshed/stdlib/2.7/xml/etree/ElementPath.pyi
+++ b/typeshed/stdlib/2.7/xml/etree/ElementPath.pyi
@@ -3,7 +3,7 @@
# NOTE: This dynamically typed stub was automatically generated by stubgen.
from typing import Pattern, Dict, Generator, Tuple, List, Union, TypeVar, Callable, Optional
-from .ElementTree import Element
+from xml.etree.ElementTree import Element
xpath_tokenizer_re = ... # type: Pattern
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2.7/xml/sax/__init__.pyi
index e69de29..9e3d009 100644
--- a/typeshed/stdlib/2.7/xml/sax/__init__.pyi
+++ b/typeshed/stdlib/2.7/xml/sax/__init__.pyi
@@ -0,0 +1,20 @@
+# Stubs for xml.sax (Python 2.7)
+#
+# 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/argparse.pyi b/typeshed/stdlib/2and3/argparse.pyi
index da1f6fd..32b734c 100644
--- a/typeshed/stdlib/2and3/argparse.pyi
+++ b/typeshed/stdlib/2and3/argparse.pyi
@@ -25,7 +25,7 @@ class ArgumentParser:
usage: Optional[str] = ...,
description: Optional[str] = ...,
epilog: Optional[str] = ...,
- parents: List[ArgumentParser] = ...,
+ parents: Sequence[ArgumentParser] = ...,
formatter_class: Type[HelpFormatter] = ...,
prefix_chars: str = ...,
fromfile_prefix_chars: Optional[str] = ...,
@@ -34,12 +34,12 @@ class ArgumentParser:
add_help: bool = ...,
allow_abbrev: bool = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
prog: Optional[str] = ...,
usage: Optional[str] = ...,
description: Optional[str] = ...,
epilog: Optional[str] = ...,
- parents: List[ArgumentParser] = ...,
+ parents: Sequence[ArgumentParser] = ...,
formatter_class: Type[HelpFormatter] = ...,
prefix_chars: str = ...,
fromfile_prefix_chars: Optional[str] = ...,
@@ -47,12 +47,12 @@ class ArgumentParser:
conflict_handler: str = ...,
add_help: bool = ...) -> None: ...
def add_argument(self,
- *name_or_flags: Union[str, List[str]],
- action: Union[str, Action] = ...,
+ *name_or_flags: Union[str, Sequence[str]],
+ action: Union[str, Type[Action]] = ...,
nargs: Union[int, str] = ...,
const: Any = ...,
default: Any = ...,
- type: Callable[[str], _T] = ...,
+ type: Union[Callable[[str], _T], FileType] = ...,
choices: Iterable[_T] = ...,
required: bool = ...,
help: str = ...,
@@ -79,9 +79,8 @@ class ArgumentParser:
def print_help(self, file: Optional[IO[str]] = ...) -> None: ...
def format_usage(self) -> str: ...
def format_help(self) -> str: ...
- def parse_known_args(self, args: Optional[str] = ...,
- namespace: Optional[Namespace] = ...) \
- -> Tuple[Namespace, List[str]]: ...
+ def parse_known_args(self, args: Optional[Sequence[str]] = ...,
+ namespace: Optional[Namespace] = ...) -> Tuple[Namespace, List[str]]: ...
def convert_arg_line_to_args(self, arg_line: str) -> List[str]: ...
def exit(self, status: int = ..., message: Optional[str] = ...) -> None: ...
def error(self, message: str) -> None: ...
@@ -99,18 +98,19 @@ if sys.version_info >= (3,):
class Action:
def __init__(self,
- option_strings: List[str],
+ option_strings: Sequence[str],
dest: str = ...,
nargs: Optional[Union[int, str]] = ...,
const: Any = ...,
default: Any = ...,
- type: Optional[Callable[[str], _T]] = ...,
+ type: Union[Callable[[str], _T], FileType, None] = ...,
choices: Optional[Iterable[_T]] = ...,
required: bool = ...,
help: Optional[str] = ...,
metavar: Union[str, Tuple[str, ...]] = ...) -> None: ...
def __call__(self, parser: ArgumentParser, namespace: Namespace,
- values: List[Any], option_string: str = ...) -> None: ...
+ values: Union[str, Sequence[Any], None],
+ option_string: str = ...) -> None: ...
class Namespace:
def __getattr__(self, name: str) -> Any: ...
@@ -122,21 +122,21 @@ class FileType:
encoding: Optional[str] = ...,
errors: Optional[str] = ...) -> None: ...
elif sys.version_info >= (3,):
- def __init__(self, # type: ignore
+ def __init__(self,
mode: str = ..., bufsize: int = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
mode: str = ..., bufsize: Optional[int] = ...) -> None: ...
def __call__(self, string: str) -> IO[Any]: ...
class _ArgumentGroup:
def add_argument(self,
- *name_or_flags: Union[str, List[str]],
- action: Union[str, Action] = ...,
+ *name_or_flags: Union[str, Sequence[str]],
+ action: Union[str, Type[Action]] = ...,
nargs: Union[int, str] = ...,
const: Any = ...,
default: Any = ...,
- type: Callable[[str], _T] = ...,
+ type: Union[Callable[[str], _T], FileType] = ...,
choices: Iterable[_T] = ...,
required: bool = ...,
help: str = ...,
diff --git a/typeshed/stdlib/2and3/bisect.pyi b/typeshed/stdlib/2and3/bisect.pyi
new file mode 100644
index 0000000..51ffc9b
--- /dev/null
+++ b/typeshed/stdlib/2and3/bisect.pyi
@@ -0,0 +1,22 @@
+# Stubs for bisect
+
+from typing import Any, Sequence, TypeVar
+
+_T = TypeVar('_T')
+
+# TODO uncomment when mypy#2035 is fixed
+#def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ...
+#def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ...
+#def bisect(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ...
+#
+#def insort_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ...
+#def insort_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ...
+#def insort(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ...
+
+def bisect_left(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ...
+def bisect_right(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ...
+def bisect(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ...
+
+def insort_left(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ...
+def insort_right(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ...
+def insort(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ...
diff --git a/typeshed/stdlib/2and3/cmath.pyi b/typeshed/stdlib/2and3/cmath.pyi
index ffd1610..7e7389c 100644
--- a/typeshed/stdlib/2and3/cmath.pyi
+++ b/typeshed/stdlib/2and3/cmath.pyi
@@ -30,5 +30,5 @@ def sqrt(x:_C) -> complex: ...
def tan(x:_C) -> complex: ...
def tanh(x:_C) -> complex: ...
-if sys.version_info[0] >= 3:
+if sys.version_info >= (3,):
def isfinite(z:_C) -> bool: ...
diff --git a/typeshed/stdlib/2and3/code.pyi b/typeshed/stdlib/2and3/code.pyi
new file mode 100644
index 0000000..e775851
--- /dev/null
+++ b/typeshed/stdlib/2and3/code.pyi
@@ -0,0 +1,27 @@
+# Stubs for code
+
+from typing import Any, Callable, Mapping, Optional
+from types import CodeType
+
+class InteractiveInterpreter:
+ def __init__(self, locals: Optional[Mapping[str, Any]] = ...) -> None: ...
+ def runsource(self, source: str, filename: str = ...,
+ symbol: str = ...) -> bool: ...
+ def runcode(self, code: CodeType) -> None: ...
+ def showsyntaxerror(self, filename: Optional[str] = ...) -> None: ...
+ def showtraceback(self) -> None: ...
+ def write(self, data: str) -> None: ...
+
+class InteractiveConsole(InteractiveInterpreter):
+ def __init__(self, locals: Optional[Mapping[str, Any]] = ...,
+ filename: str = ...) -> None: ...
+ def interact(self, banner: Optional[str] = ...) -> None: ...
+ def push(self, line: str) -> bool: ...
+ def resetbuffer(self) -> None: ...
+ def raw_input(self, prompt: str = ...) -> str: ...
+
+def interact(banner: Optional[str] = ...,
+ readfunc: Optional[Callable[[str], str]] = ...,
+ local: Optional[Mapping[str, Any]] = ...) -> None: ...
+def compile_command(source: str, filename: str = ...,
+ symbol: str = ...) -> Optional[CodeType]: ...
diff --git a/typeshed/stdlib/2and3/colorsys.pyi b/typeshed/stdlib/2and3/colorsys.pyi
new file mode 100644
index 0000000..ee17ba9
--- /dev/null
+++ b/typeshed/stdlib/2and3/colorsys.pyi
@@ -0,0 +1,15 @@
+# Stubs for colorsys
+
+from typing import Tuple
+
+def rgb_to_yiq(r: float, g: float, b: float) -> Tuple[float, float, float]: ...
+def yiq_to_rgb(y: float, i: float, q: float) -> Tuple[float, float, float]: ...
+def rgb_to_hls(r: float, g: float, b: float) -> Tuple[float, float, float]: ...
+def hls_to_rgb(h: float, l: float, s: float) -> Tuple[float, float, float]: ...
+def rgb_to_hsv(r: float, g: float, b: float) -> Tuple[float, float, float]: ...
+def hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]: ...
+
+# TODO undocumented
+ONE_SIXTH = ... # type: float
+ONE_THIRD = ... # type: float
+TWO_THIRD = ... # type: float
diff --git a/typeshed/stdlib/2and3/contextlib.pyi b/typeshed/stdlib/2and3/contextlib.pyi
new file mode 100644
index 0000000..0f14afa
--- /dev/null
+++ b/typeshed/stdlib/2and3/contextlib.pyi
@@ -0,0 +1,53 @@
+# Stubs for contextlib
+
+from typing import (
+ Any, Callable, Generator, IO, Iterable, Iterator, Optional, Type,
+ Generic, TypeVar,
+)
+from types import TracebackType
+import sys
+
+_T = TypeVar('_T')
+_ExitFunc = Callable[[Optional[Type[BaseException]],
+ Optional[Exception],
+ 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: ...
+
+def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
+
+if sys.version_info < (3,):
+ def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ...
+
+class closing(Generic[_T], ContextManager[_T]):
+ def __init__(self, thing: _T) -> None: ...
+
+if sys.version_info >= (3, 4):
+ class suppress(ContextManager[None]):
+ def __init__(self, *exceptions: Type[BaseException]) -> None: ...
+
+ class redirect_stdout(ContextManager[None]):
+ def __init__(self, new_target: IO[str]) -> None: ...
+
+if sys.version_info >= (3, 5):
+ class redirect_stderr(ContextManager[None]):
+ def __init__(self, new_target: IO[str]) -> None: ...
+
+if sys.version_info >= (3,):
+ class ContextDecorator:
+ def __call__(self, func: Callable[..., None]) -> Callable[..., ContextManager[None]]: ...
+
+ class ExitStack(ContextManager[ExitStack]):
+ def __init__(self) -> None: ...
+ def enter_context(self, cm: ContextManager[_T]) -> _T: ...
+ def push(self, exit: _CM_EF) -> _CM_EF: ...
+ def callback(self, callback: Callable[..., None],
+ *args: Any, **kwds: Any) -> Callable[..., None]: ...
+ def pop_all(self) -> ExitStack: ...
+ def close(self) -> None: ...
diff --git a/typeshed/stdlib/3/distutils/__init__.pyi b/typeshed/stdlib/2and3/distutils/__init__.pyi
similarity index 100%
rename from typeshed/stdlib/3/distutils/__init__.pyi
rename to typeshed/stdlib/2and3/distutils/__init__.pyi
diff --git a/typeshed/stdlib/2and3/distutils/archive_util.pyi b/typeshed/stdlib/2and3/distutils/archive_util.pyi
new file mode 100644
index 0000000..12172f3
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/archive_util.pyi
@@ -0,0 +1,12 @@
+# Stubs for distutils.archive_util
+
+from typing import Optional
+
+
+def make_archive(base_name: str, format: str, root_dir: Optional[str] = ...,
+ base_dir: Optional[str] = ..., verbose: int = ...,
+ dry_run: int = ...) -> str: ...
+def make_tarball(base_name: str, base_dir: str, compress: Optional[str] = ...,
+ verbose: int = ..., dry_run: int = ...) -> str: ...
+def make_zipfile(base_name: str, base_dir: str, verbose: int = ...,
+ dry_run: int = ...) -> str: ...
diff --git a/typeshed/stdlib/2and3/distutils/bcppcompiler.pyi b/typeshed/stdlib/2and3/distutils/bcppcompiler.pyi
new file mode 100644
index 0000000..9f27a0a
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/bcppcompiler.pyi
@@ -0,0 +1,6 @@
+# Stubs for distutils.bcppcompiler
+
+from distutils.ccompiler import CCompiler
+
+
+class BCPPCompiler(CCompiler): ...
diff --git a/typeshed/stdlib/2and3/distutils/ccompiler.pyi b/typeshed/stdlib/2and3/distutils/ccompiler.pyi
new file mode 100644
index 0000000..94fad8b
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/ccompiler.pyi
@@ -0,0 +1,119 @@
+# Stubs for distutils.ccompiler
+
+from typing import Any, Callable, List, Optional, Tuple, Union
+
+
+_Macro = Union[Tuple[str], Tuple[str, str]]
+
+
+def gen_lib_options(compiler: CCompiler, library_dirs: List[str],
+ runtime_library_dirs: List[str],
+ libraries: List[str]) -> List[str]: ...
+def gen_preprocess_options(macros: List[_Macro],
+ include_dirs: List[str]) -> List[str]: ...
+def get_default_compiler(osname: Optional[str] = ...,
+ platform: Optional[str] = ...) -> str: ...
+def new_compiler(plat: Optional[str] = ..., compiler: Optional[str] = ...,
+ verbose: int = ..., dry_run: int = ...,
+ force: int = ...) -> CCompiler: ...
+def show_compilers() -> None: ...
+
+class CCompiler:
+ def __init__(self, verbose: int = ..., dry_run: int = ...,
+ force: int = ...) -> None: ...
+ def add_include_dir(self, dir: str) -> None: ...
+ def set_include_dirs(self, dirs: List[str]) -> None: ...
+ def add_library(self, libname: str) -> None: ...
+ def set_libraries(self, libnames: List[str]) -> None: ...
+ def add_library_dir(self, dir: str) -> None: ...
+ def set_library_dirs(self, dirs: List[str]) -> None: ...
+ def add_runtime_library_dir(self, dir: str) -> None: ...
+ def set_runtime_library_dirs(self, dirs: List[str]) -> None: ...
+ def define_macro(self, name: str, value: Optional[str] = ...) -> None: ...
+ def undefine_macro(self, name: str) -> None: ...
+ def add_link_object(self, object: str) -> None: ...
+ def set_link_objects(self, objects: List[str]) -> None: ...
+ def detect_language(self, sources: Union[str, List[str]]) -> Optional[str]: ...
+ def find_library_file(self, dirs: List[str], lib: str,
+ debug: bool = ...) -> Optional[str]: ...
+ def has_function(self, funcname: str, includes: Optional[List[str]] = ...,
+ include_dirs: Optional[List[str]] = ...,
+ libraries: Optional[List[str]] = ...,
+ library_dirs: Optional[List[str]] = ...) -> bool: ...
+ def library_dir_option(self, dir: str) -> str: ...
+ def library_option(self, lib: str) -> str: ...
+ def runtime_library_dir_option(self, dir: str) -> str: ...
+ def set_executables(self, **args: str) -> None: ...
+ def compile(self, sources: List[str], output_dir: Optional[str] = ...,
+ macros: Optional[_Macro] = ...,
+ include_dirs: Optional[List[str]] = ..., debug: bool = ...,
+ extra_preargs: Optional[List[str]] = ...,
+ extra_postargs: Optional[List[str]] = ...,
+ depends: Optional[List[str]] = ...) -> List[str]: ...
+ def create_static_lib(self, objects: List[str], output_libname: str,
+ output_dir: Optional[str] = ..., debug: bool = ...,
+ target_lang: Optional[str] = ...) -> None: ...
+ def link(self, target_desc: str, objects: List[str], output_filename: str,
+ output_dir: Optional[str] = ...,
+ libraries: Optional[List[str]] = ...,
+ library_dirs: Optional[List[str]] = ...,
+ runtime_library_dirs: Optional[List[str]] = ...,
+ export_symbols: Optional[List[str]] = ..., debug: bool = ...,
+ extra_preargs: Optional[List[str]] = ...,
+ extra_postargs: Optional[List[str]] = ...,
+ build_temp: Optional[str] = ...,
+ target_lang: Optional[str] = ...) -> None: ...
+ def link_executable(self, objects: List[str], output_progname: str,
+ output_dir: Optional[str] = ...,
+ libraries: Optional[List[str]] = ...,
+ library_dirs: Optional[List[str]] = ...,
+ runtime_library_dirs: Optional[List[str]] = ...,
+ debug: bool = ...,
+ extra_preargs: Optional[List[str]] = ...,
+ extra_postargs: Optional[List[str]] = ...,
+ target_lang: Optional[str] = ...) -> None: ...
+ def link_shared_lib(self, objects: List[str], output_libname: str,
+ output_dir: Optional[str] = ...,
+ libraries: Optional[List[str]] = ...,
+ library_dirs: Optional[List[str]] = ...,
+ runtime_library_dirs: Optional[List[str]] = ...,
+ export_symbols: Optional[List[str]] = ...,
+ debug: bool = ...,
+ extra_preargs: Optional[List[str]] = ...,
+ extra_postargs: Optional[List[str]] = ...,
+ build_temp: Optional[str] = ...,
+ target_lang: Optional[str] = ...) -> None: ...
+ def link_shared_object(self, objects: List[str], output_filename: str,
+ output_dir: Optional[str] = ...,
+ libraries: Optional[List[str]] = ...,
+ library_dirs: Optional[List[str]] = ...,
+ runtime_library_dirs: Optional[List[str]] = ...,
+ export_symbols: Optional[List[str]] = ...,
+ debug: bool = ...,
+ extra_preargs: Optional[List[str]] = ...,
+ extra_postargs: Optional[List[str]] = ...,
+ build_temp: Optional[str] = ...,
+ target_lang: Optional[str] = ...) -> None: ...
+ def preprocess(self, source: str, output_file: Optional[str] = ...,
+ macros: Optional[List[_Macro]] = ...,
+ include_dirs: Optional[List[str]] = ...,
+ extra_preargs: Optional[List[str]] = ...,
+ extra_postargs: Optional[List[str]] = ...) -> None: ...
+ def executable_filename(self, basename: str, strip_dir: int = ...,
+ output_dir: str = ...) -> str: ...
+ def library_filename(self, libname: str, lib_type: str = ...,
+ strip_dir: int = ...,
+ output_dir: str = ...) -> str: ...
+ def object_filenames(self, source_filenames: List[str],
+ strip_dir: int = ...,
+ output_dir: str = ...) -> List[str]: ...
+ def shared_object_filename(self, basename: str, strip_dir: int = ...,
+ output_dir: str = ...) -> str: ...
+ def execute(self, func: Callable[..., None], args: Tuple[Any, ...],
+ msg: Optional[str] = ..., level: int = ...) -> None: ...
+ def spawn(self, cmd: List[str]) -> None: ...
+ def mkpath(self, name: str, mode: int = ...) -> None: ...
+ def move_file(self, src: str, dst: str) -> str: ...
+ def announce(self, msg: str, level: int = ...) -> None: ...
+ def warn(self, msg: str) -> None: ...
+ def debug_print(self, msg: str) -> None: ...
diff --git a/typeshed/stdlib/2and3/distutils/cmd.pyi b/typeshed/stdlib/2and3/distutils/cmd.pyi
new file mode 100644
index 0000000..126ef15
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/cmd.pyi
@@ -0,0 +1,15 @@
+# Stubs for distutils.cmd
+
+from typing import Callable, List, Tuple, Union
+from abc import abstractmethod
+from distutils.dist import Distribution
+
+class Command:
+ sub_commands = ... # type: List[Tuple[str, Union[Callable[[], bool], str, None]]]
+ def __init__(self, dist: Distribution) -> None: ...
+ @abstractmethod
+ def initialize_options(self) -> None: ...
+ @abstractmethod
+ def finalize_options(self) -> None: ...
+ @abstractmethod
+ def run(self) -> None: ...
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/__init__.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/__init__.pyi
diff --git a/typeshed/third_party/3/pkg_resources/_vendor/__init__.py b/typeshed/stdlib/2and3/distutils/command/bdist.pyi
similarity index 100%
copy from typeshed/third_party/3/pkg_resources/_vendor/__init__.py
copy to typeshed/stdlib/2and3/distutils/command/bdist.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/bdist_dumb.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/bdist_dumb.pyi
diff --git a/typeshed/stdlib/2and3/distutils/command/bdist_msi.pyi b/typeshed/stdlib/2and3/distutils/command/bdist_msi.pyi
new file mode 100644
index 0000000..3813699
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/command/bdist_msi.pyi
@@ -0,0 +1,5 @@
+# Stubs for distutils.command.bdist_msi
+
+from distutils.cmd import Command
+
+class bdist_msi(Command): ...
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/bdist_packager.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/bdist_packager.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/bdist_rpm.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/bdist_rpm.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/bdist_wininst.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/bdist_wininst.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/build.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/build.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/build_clib.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/build_clib.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/build_ext.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/build_ext.pyi
diff --git a/typeshed/stdlib/2and3/distutils/command/build_py.pyi b/typeshed/stdlib/2and3/distutils/command/build_py.pyi
new file mode 100644
index 0000000..23b3f9e
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/command/build_py.pyi
@@ -0,0 +1,8 @@
+# Stubs for distutils.command.bdist_msi
+
+from distutils.cmd import Command
+import sys
+
+if sys.version_info >= (3,):
+ class build_py(Command): ...
+ class build_py_2to3(Command): ...
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/build_scripts.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/build_scripts.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/check.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/check.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/clean.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/clean.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/config.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/config.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/install.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/install.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/install_data.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/install_data.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/install_headers.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/install_headers.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/install_lib.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/install_lib.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/install_scripts.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/install_scripts.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/register.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/register.pyi
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/command/sdist.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/command/sdist.pyi
diff --git a/typeshed/stdlib/2and3/distutils/core.pyi b/typeshed/stdlib/2and3/distutils/core.pyi
new file mode 100644
index 0000000..38d6a1a
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/core.pyi
@@ -0,0 +1,35 @@
+# Stubs for distutils.core
+
+from typing import Any, List, Mapping, Optional, Tuple, Type, Union
+from distutils.cmd import Command as Command
+from distutils.dist import Distribution as Distribution
+from distutils.extension import Extension as Extension
+
+def setup(name: str = ...,
+ version: str = ...,
+ description: str = ...,
+ long_description: str = ...,
+ author: str = ...,
+ author_email: str = ...,
+ maintainer: str = ...,
+ maintainer_email: str = ...,
+ url: str = ...,
+ download_url: str = ...,
+ packages: List[str] = ...,
+ py_modules: List[str] = ...,
+ scripts: List[str] = ...,
+ ext_modules: List[Extension] = ...,
+ classifiers: List[str] = ...,
+ distclass: Type[Distribution] = ...,
+ script_name: str = ...,
+ script_args: List[str] = ...,
+ options: Mapping[str, Any] = ...,
+ license: str = ...,
+ keywords: Union[List[str], str] = ...,
+ platforms: Union[List[str], str] = ...,
+ cmdclass: Mapping[str, Command] = ...,
+ data_files: List[Tuple[str, List[str]]] = ...,
+ package_dir: Mapping[str, str] = ...) -> None: ...
+def run_setup(script_name: str,
+ script_args: Optional[List[str]] = ...,
+ stop_after: str = ...) -> Distribution: ...
diff --git a/typeshed/stdlib/2and3/distutils/cygwinccompiler.pyi b/typeshed/stdlib/2and3/distutils/cygwinccompiler.pyi
new file mode 100644
index 0000000..1bfab90
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/cygwinccompiler.pyi
@@ -0,0 +1,7 @@
+# Stubs for distutils.cygwinccompiler
+
+from distutils.unixccompiler import UnixCCompiler
+
+
+class CygwinCCompiler(UnixCCompiler): ...
+class Mingw32CCompiler(CygwinCCompiler): ...
diff --git a/typeshed/stdlib/2and3/distutils/debug.pyi b/typeshed/stdlib/2and3/distutils/debug.pyi
new file mode 100644
index 0000000..c3a1849
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/debug.pyi
@@ -0,0 +1,3 @@
+# Stubs for distutils.debug
+
+DEBUG = ... # type: bool
diff --git a/typeshed/stdlib/2and3/distutils/dep_util.pyi b/typeshed/stdlib/2and3/distutils/dep_util.pyi
new file mode 100644
index 0000000..7df5847
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/dep_util.pyi
@@ -0,0 +1,8 @@
+# Stubs for distutils.dep_util
+
+from typing import List, Tuple
+
+def newer(source: str, target: str) -> bool: ...
+def newer_pairwise(sources: List[str],
+ targets: List[str]) -> List[Tuple[str, str]]: ...
+def newer_group(sources: List[str], target: str, missing: str = ...) -> bool: ...
diff --git a/typeshed/stdlib/2and3/distutils/dir_util.pyi b/typeshed/stdlib/2and3/distutils/dir_util.pyi
new file mode 100644
index 0000000..667ac2f
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/dir_util.pyi
@@ -0,0 +1,15 @@
+# Stubs for distutils.dir_util
+
+from typing import List
+
+
+def mkpath(name: str, mode: int = ..., verbose: int = ...,
+ dry_run: int = ...) -> List[str]: ...
+def create_tree(base_dir: str, files: List[str], mode: int = ...,
+ verbose: int = ..., dry_run: int = ...) -> None: ...
+def copy_tree(src: str, dst: str, preserve_mode: int = ...,
+ preserve_times: int = ..., preserve_symlinks: int = ...,
+ update: int = ..., verbose: int = ...,
+ dry_run: int = ...) -> List[str]: ...
+def remove_tree(directory: str, verbose: int = ...,
+ dry_run: int = ...) -> None: ...
diff --git a/typeshed/stdlib/2and3/distutils/dist.pyi b/typeshed/stdlib/2and3/distutils/dist.pyi
new file mode 100644
index 0000000..2d9c162
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/dist.pyi
@@ -0,0 +1,7 @@
+# Stubs for distutils.dist
+
+from typing import Any, Mapping, Optional
+
+
+class Distribution:
+ def __init__(self, attrs: Optional[Mapping[str, Any]] = ...) -> None: ...
diff --git a/typeshed/stdlib/2and3/distutils/errors.pyi b/typeshed/stdlib/2and3/distutils/errors.pyi
new file mode 100644
index 0000000..49ca06f
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/errors.pyi
@@ -0,0 +1,4 @@
+# Stubs for distutils.errors
+
+class DistutilsExecError(Exception): ...
+class DistutilsFileError(Exception): ...
diff --git a/typeshed/stdlib/2and3/distutils/extension.pyi b/typeshed/stdlib/2and3/distutils/extension.pyi
new file mode 100644
index 0000000..81dae10
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/extension.pyi
@@ -0,0 +1,39 @@
+# Stubs for distutils.extension
+
+from typing import List, Optional, Tuple
+import sys
+
+class Extension:
+ if sys.version_info >= (3,):
+ def __init__(self,
+ *, name: str = ...,
+ sources: List[str] = ...,
+ include_dirs: List[str] = ...,
+ define_macros: List[Tuple[str, Optional[str]]] = ...,
+ undef_macros: List[str] = ...,
+ library_dirs: List[str] = ...,
+ libraries: List[str] = ...,
+ runtime_library_dirs: List[str] = ...,
+ extra_objects: List[str] = ...,
+ extra_compile_args: List[str] = ...,
+ extra_link_args: List[str] = ...,
+ export_symbols: List[str] = ...,
+ depends: List[str] = ...,
+ language: str = ...,
+ optional: bool = ...) -> None: ...
+ else:
+ def __init__(self,
+ *, name: str = ...,
+ sources: List[str] = ...,
+ include_dirs: List[str] = ...,
+ define_macros: List[Tuple[str, Optional[str]]] = ...,
+ undef_macros: List[str] = ...,
+ library_dirs: List[str] = ...,
+ libraries: List[str] = ...,
+ runtime_library_dirs: List[str] = ...,
+ extra_objects: List[str] = ...,
+ extra_compile_args: List[str] = ...,
+ extra_link_args: List[str] = ...,
+ export_symbols: List[str] = ...,
+ depends: List[str] = ...,
+ language: str = ...) -> None: ...
diff --git a/typeshed/stdlib/2and3/distutils/fancy_getopt.pyi b/typeshed/stdlib/2and3/distutils/fancy_getopt.pyi
new file mode 100644
index 0000000..aa7e964
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/fancy_getopt.pyi
@@ -0,0 +1,27 @@
+# Stubs for distutils.fancy_getopt
+
+from typing import (
+ Any, List, Mapping, Optional, Tuple, Union,
+ TypeVar, overload,
+)
+
+_Option = Tuple[str, str, str]
+_GR = Tuple[List[str], OptionDummy]
+
+def fancy_getopt(options: List[_Option],
+ negative_opt: Mapping[_Option, _Option],
+ object: Any,
+ args: Optional[List[str]]) -> Union[List[str], _GR]: ...
+def wrap_text(text: str, width: int) -> List[str]: ...
+
+class FancyGetopt:
+ def __init__(self, option_table: Optional[List[_Option]] = ...) -> None: ...
+ # TODO kinda wrong, `getopt(object=object())` is invalid
+ @overload
+ def getopt(self, args: Optional[List[str]] = ...) -> _GR: ...
+ @overload
+ def getopt(self, args: Optional[List[str]], object: Any) -> List[str]: ...
+ def get_option_order(self) -> List[Tuple[str, str]]: ...
+ def generate_help(self, header: Optional[str] = ...) -> List[str]: ...
+
+class OptionDummy: ...
diff --git a/typeshed/stdlib/2and3/distutils/file_util.pyi b/typeshed/stdlib/2and3/distutils/file_util.pyi
new file mode 100644
index 0000000..6324d63
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/file_util.pyi
@@ -0,0 +1,12 @@
+# Stubs for distutils.file_util
+
+from typing import Optional, Sequence, Tuple
+
+
+def copy_file(src: str, dst: str, preserve_mode: bool = ...,
+ preserve_times: bool = ..., update: bool = ...,
+ link: Optional[str] = ..., verbose: bool = ...,
+ dry_run: bool = ...) -> Tuple[str, str]: ...
+def move_file(src: str, dst: str, verbose: bool = ...,
+ dry_run: bool = ...) -> str: ...
+def write_file(filename: str, contents: Sequence[str]) -> None: ...
diff --git a/typeshed/stdlib/2and3/distutils/filelist.pyi b/typeshed/stdlib/2and3/distutils/filelist.pyi
new file mode 100644
index 0000000..4ecaeba
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/filelist.pyi
@@ -0,0 +1,3 @@
+# Stubs for distutils.filelist
+
+class FileList: ...
diff --git a/typeshed/stdlib/2.7/xml/sax/__init__.pyi b/typeshed/stdlib/2and3/distutils/log.pyi
similarity index 100%
copy from typeshed/stdlib/2.7/xml/sax/__init__.pyi
copy to typeshed/stdlib/2and3/distutils/log.pyi
diff --git a/typeshed/stdlib/2and3/distutils/msvccompiler.pyi b/typeshed/stdlib/2and3/distutils/msvccompiler.pyi
new file mode 100644
index 0000000..ffc9e44
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/msvccompiler.pyi
@@ -0,0 +1,6 @@
+# Stubs for distutils.msvccompiler
+
+from distutils.ccompiler import CCompiler
+
+
+class MSVCCompiler(CCompiler): ...
diff --git a/typeshed/stdlib/2and3/distutils/spawn.pyi b/typeshed/stdlib/2and3/distutils/spawn.pyi
new file mode 100644
index 0000000..f8acb8a
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/spawn.pyi
@@ -0,0 +1,8 @@
+# Stubs for distutils.spawn
+
+from typing import Optional
+
+def spawn(cmd: List[str], search_path: bool = ...,
+ verbose: bool = ..., dry_run: bool = ...) -> None: ...
+def find_executable(executable: str,
+ path: Optional[str] = ...) -> Optional[str]: ...
diff --git a/typeshed/stdlib/2and3/distutils/sysconfig.pyi b/typeshed/stdlib/2and3/distutils/sysconfig.pyi
new file mode 100644
index 0000000..f87cd46
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/sysconfig.pyi
@@ -0,0 +1,19 @@
+# Stubs for distutils.sysconfig
+
+from typing import Mapping, Optional, Union
+from distutils.ccompiler import CCompiler
+
+PREFIX = ... # type: str
+EXEC_PREFIX = ... # type: str
+
+def get_config_var(name: str) -> Union[int, str, None]: ...
+def get_config_vars(*args: str) -> Mapping[str, Union[int, str]]: ...
+def get_config_h_filename() -> str: ...
+def get_makefile_filename() -> str: ...
+def get_python_inc(plat_specific: bool = ...,
+ prefix: Optional[str] = ...) -> str: ...
+def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ...,
+ prefix: Optional[str] = ...) -> str: ...
+
+def customize_compiler(compiler: CCompiler) -> None: ...
+def set_python_build() -> None: ...
diff --git a/typeshed/stdlib/2and3/distutils/text_file.pyi b/typeshed/stdlib/2and3/distutils/text_file.pyi
new file mode 100644
index 0000000..b4fcb59
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/text_file.pyi
@@ -0,0 +1,18 @@
+# Stubs for distutils.text_file
+
+from typing import IO, Optional, Tuple, Union
+
+class TextFile:
+ def __init__(self, filename: Optional[str] = ...,
+ file: Optional[IO[str]] = ...,
+ *, strip_comments: bool = ...,
+ lstrip_ws: bool = ..., rstrip_ws: bool = ...,
+ skip_blanks: bool = ..., join_lines: bool = ...,
+ collapse_join: bool = ...) -> None: ...
+ def open(self, filename: str) -> None: ...
+ def close(self) -> None: ...
+ def warn(self, msg: str,
+ line: Union[List[int], Tuple[int, int], int] = ...) -> None: ...
+ def readline(self) -> Optional[str]: ...
+ def readlines(self) -> List[str]: ...
+ def unreadline(self, line: str) -> str: ...
diff --git a/typeshed/stdlib/2and3/distutils/unixccompiler.pyi b/typeshed/stdlib/2and3/distutils/unixccompiler.pyi
new file mode 100644
index 0000000..7ab7298
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/unixccompiler.pyi
@@ -0,0 +1,6 @@
+# Stubs for distutils.unixccompiler
+
+from distutils.ccompiler import CCompiler
+
+
+class UnixCCompiler(CCompiler): ...
diff --git a/typeshed/stdlib/2and3/distutils/util.pyi b/typeshed/stdlib/2and3/distutils/util.pyi
new file mode 100644
index 0000000..97db9e0
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/util.pyi
@@ -0,0 +1,20 @@
+# Stubs for distutils.util
+
+from typing import Any, Callable, Mapping, Optional, Tuple
+
+
+def get_platform() -> str: ...
+def convert_path(pathname: str) -> str: ...
+def change_root(new_root: str, pathname: str) -> str: ...
+def check_environ() -> None: ...
+def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ...
+def split_quoted(s: str) -> List[str]: ...
+def execute(func: Callable[..., None], args: Tuple[Any, ...],
+ msg: Optional[str] = ..., verbose: bool = ...,
+ dry_run: bool = ...) -> None: ...
+def strtobool(val: str) -> bool: ...
+def byte_compile(py_files: List[str], optimize: int = ..., force: bool = ...,
+ prefix: Optional[str] = ..., base_dir: Optional[str] = ...,
+ verbose: bool = ..., dry_run: bool = ...,
+ direct: Optional[bool] = ...) -> None: ...
+def rfc822_escape(header: str) -> str: ...
diff --git a/typeshed/stdlib/2and3/distutils/version.pyi b/typeshed/stdlib/2and3/distutils/version.pyi
new file mode 100644
index 0000000..6b6efbf
--- /dev/null
+++ b/typeshed/stdlib/2and3/distutils/version.pyi
@@ -0,0 +1,35 @@
+# 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
+
+class Version:
+ def __init__(self, vstring=None): ...
+
+ if sys.version_info >= (3,):
+ def __eq__(self, other): ...
+ def __lt__(self, other): ...
+ def __le__(self, other): ...
+ def __gt__(self, other): ...
+ def __ge__(self, other): ...
+
+class StrictVersion(Version):
+ version_re = ... # type: Any
+ version = ... # type: Any
+ prerelease = ... # type: Any
+ def parse(self, vstring): ...
+
+ if sys.version_info < (3,):
+ def __cmp__(self, other): ...
+
+class LooseVersion(Version):
+ component_re = ... # type: Any
+ def __init__(self, vstring=None): ...
+ vstring = ... # type: Any
+ version = ... # type: Any
+ def parse(self, vstring): ...
+
+ if sys.version_info < (3,):
+ def __cmp__(self, other): ...
diff --git a/typeshed/stdlib/2.7/errno.pyi b/typeshed/stdlib/2and3/errno.pyi
similarity index 95%
rename from typeshed/stdlib/2.7/errno.pyi
rename to typeshed/stdlib/2and3/errno.pyi
index c60170d..8f6ce18 100644
--- a/typeshed/stdlib/2.7/errno.pyi
+++ b/typeshed/stdlib/2and3/errno.pyi
@@ -1,129 +1,129 @@
-"""Stubs for the 'errno' module."""
+# Stubs for errno
-from typing import Dict
+from typing import Mapping
+import sys
-errorcode = ... # type: Dict[int, str]
+errorcode = ... # type: Mapping[int, str]
+EPERM = ... # type: int
+ENOENT = ... # type: int
+ESRCH = ... # type: int
+EINTR = ... # type: int
+EIO = ... # type: int
+ENXIO = ... # type: int
E2BIG = ... # type: int
-EACCES = ... # type: int
-EADDRINUSE = ... # type: int
-EADDRNOTAVAIL = ... # type: int
-EADV = ... # type: int
-EAFNOSUPPORT = ... # type: int
-EAGAIN = ... # type: int
-EALREADY = ... # type: int
-EBADE = ... # type: int
+ENOEXEC = ... # type: int
EBADF = ... # type: int
-EBADFD = ... # type: int
-EBADMSG = ... # type: int
-EBADR = ... # type: int
-EBADRQC = ... # type: int
-EBADSLT = ... # type: int
-EBFONT = ... # type: int
-EBUSY = ... # type: int
ECHILD = ... # type: int
-ECHRNG = ... # type: int
-ECOMM = ... # type: int
-ECONNABORTED = ... # type: int
-ECONNREFUSED = ... # type: int
-ECONNRESET = ... # type: int
-EDEADLK = ... # type: int
-EDEADLOCK = ... # type: int
-EDESTADDRREQ = ... # type: int
-EDOM = ... # type: int
-EDOTDOT = ... # type: int
-EDQUOT = ... # type: int
-EEXIST = ... # type: int
+EAGAIN = ... # type: int
+ENOMEM = ... # type: int
+EACCES = ... # type: int
EFAULT = ... # type: int
+ENOTBLK = ... # type: int
+EBUSY = ... # type: int
+EEXIST = ... # type: int
+EXDEV = ... # type: int
+ENODEV = ... # type: int
+ENOTDIR = ... # type: int
+EISDIR = ... # type: int
+EINVAL = ... # type: int
+ENFILE = ... # type: int
+EMFILE = ... # type: int
+ENOTTY = ... # type: int
+ETXTBSY = ... # type: int
EFBIG = ... # type: int
-EHOSTDOWN = ... # type: int
-EHOSTUNREACH = ... # type: int
+ENOSPC = ... # type: int
+ESPIPE = ... # type: int
+EROFS = ... # type: int
+EMLINK = ... # type: int
+EPIPE = ... # type: int
+EDOM = ... # type: int
+ERANGE = ... # type: int
+EDEADLCK = ... # type: int
+ENAMETOOLONG = ... # type: int
+ENOLCK = ... # type: int
+ENOSYS = ... # type: int
+ENOTEMPTY = ... # type: int
+ELOOP = ... # type: int
+EWOULDBLOCK = ... # type: int
+ENOMSG = ... # type: int
EIDRM = ... # type: int
-EILSEQ = ... # type: int
-EINPROGRESS = ... # type: int
-EINTR = ... # type: int
-EINVAL = ... # type: int
-EIO = ... # type: int
-EISCONN = ... # type: int
-EISDIR = ... # type: int
-EISNAM = ... # type: int
-EL2HLT = ... # type: int
+ECHRNG = ... # type: int
EL2NSYNC = ... # type: int
EL3HLT = ... # type: int
EL3RST = ... # type: int
-ELIBACC = ... # type: int
-ELIBBAD = ... # type: int
-ELIBEXEC = ... # type: int
-ELIBMAX = ... # type: int
-ELIBSCN = ... # type: int
ELNRNG = ... # type: int
-ELOOP = ... # type: int
-EMFILE = ... # type: int
-EMLINK = ... # type: int
-EMSGSIZE = ... # type: int
-EMULTIHOP = ... # type: int
-ENAMETOOLONG = ... # type: int
-ENAVAIL = ... # type: int
-ENETDOWN = ... # type: int
-ENETRESET = ... # type: int
-ENETUNREACH = ... # type: int
-ENFILE = ... # type: int
-ENOANO = ... # type: int
-ENOBUFS = ... # type: int
+EUNATCH = ... # type: int
ENOCSI = ... # type: int
+EL2HLT = ... # type: int
+EBADE = ... # type: int
+EBADR = ... # type: int
+EXFULL = ... # type: int
+ENOANO = ... # type: int
+EBADRQC = ... # type: int
+EBADSLT = ... # type: int
+EDEADLOCK = ... # type: int
+EBFONT = ... # type: int
+ENOSTR = ... # type: int
ENODATA = ... # type: int
-ENODEV = ... # type: int
-ENOENT = ... # type: int
-ENOEXEC = ... # type: int
-ENOLCK = ... # type: int
-ENOLINK = ... # type: int
-ENOMEM = ... # type: int
-ENOMSG = ... # type: int
+ETIME = ... # type: int
+ENOSR = ... # type: int
ENONET = ... # type: int
ENOPKG = ... # type: int
-ENOPROTOOPT = ... # type: int
-ENOSPC = ... # type: int
-ENOSR = ... # type: int
-ENOSTR = ... # type: int
-ENOSYS = ... # type: int
-ENOTBLK = ... # type: int
-ENOTCONN = ... # type: int
-ENOTDIR = ... # type: int
-ENOTEMPTY = ... # type: int
-ENOTNAM = ... # type: int
-ENOTSOCK = ... # type: int
-ENOTSUP = ... # type: int
-ENOTTY = ... # type: int
-ENOTUNIQ = ... # type: int
-ENXIO = ... # type: int
-EOPNOTSUPP = ... # type: int
-EOVERFLOW = ... # type: int
-EPERM = ... # type: int
-EPFNOSUPPORT = ... # type: int
-EPIPE = ... # type: int
+EREMOTE = ... # type: int
+ENOLINK = ... # type: int
+EADV = ... # type: int
+ESRMNT = ... # type: int
+ECOMM = ... # type: int
EPROTO = ... # type: int
-EPROTONOSUPPORT = ... # type: int
-EPROTOTYPE = ... # type: int
-ERANGE = ... # type: int
+EMULTIHOP = ... # type: int
+EDOTDOT = ... # type: int
+EBADMSG = ... # type: int
+EOVERFLOW = ... # type: int
+ENOTUNIQ = ... # type: int
+EBADFD = ... # type: int
EREMCHG = ... # type: int
-EREMOTE = ... # type: int
-EREMOTEIO = ... # type: int
+ELIBACC = ... # type: int
+ELIBBAD = ... # type: int
+ELIBSCN = ... # type: int
+ELIBMAX = ... # type: int
+ELIBEXEC = ... # type: int
+EILSEQ = ... # type: int
ERESTART = ... # type: int
-EROFS = ... # type: int
-ESHUTDOWN = ... # type: int
-ESOCKTNOSUPPORT = ... # type: int
-ESPIPE = ... # type: int
-ESRCH = ... # type: int
-ESRMNT = ... # type: int
-ESTALE = ... # type: int
ESTRPIPE = ... # type: int
-ETIME = ... # type: int
-ETIMEDOUT = ... # type: int
+EUSERS = ... # type: int
+ENOTSOCK = ... # type: int
+EDESTADDRREQ = ... # type: int
+EMSGSIZE = ... # type: int
+EPROTOTYPE = ... # type: int
+ENOPROTOOPT = ... # type: int
+EPROTONOSUPPORT = ... # type: int
+ESOCKTNOSUPPORT = ... # type: int
+EOPNOTSUPP = ... # type: int
+EPFNOSUPPORT = ... # type: int
+EAFNOSUPPORT = ... # type: int
+EADDRINUSE = ... # type: int
+EADDRNOTAVAIL = ... # type: int
+ENETDOWN = ... # type: int
+ENETUNREACH = ... # type: int
+ENETRESET = ... # type: int
+ECONNABORTED = ... # type: int
+ECONNRESET = ... # type: int
+ENOBUFS = ... # type: int
+EISCONN = ... # type: int
+ENOTCONN = ... # type: int
+ESHUTDOWN = ... # type: int
ETOOMANYREFS = ... # type: int
-ETXTBSY = ... # type: int
+ETIMEDOUT = ... # type: int
+ECONNREFUSED = ... # type: int
+EHOSTDOWN = ... # type: int
+EHOSTUNREACH = ... # type: int
+EALREADY = ... # type: int
+EINPROGRESS = ... # type: int
+ESTALE = ... # type: int
EUCLEAN = ... # type: int
-EUNATCH = ... # type: int
-EUSERS = ... # type: int
-EWOULDBLOCK = ... # type: int
-EXDEV = ... # type: int
-EXFULL = ... # type: int
+ENOTNAM = ... # type: int
+ENAVAIL = ... # type: int
+EISNAM = ... # type: int
+EREMOTEIO = ... # type: int
+EDQUOT = ... # type: int
diff --git a/typeshed/stdlib/2and3/hmac.pyi b/typeshed/stdlib/2and3/hmac.pyi
new file mode 100644
index 0000000..59aaf36
--- /dev/null
+++ b/typeshed/stdlib/2and3/hmac.pyi
@@ -0,0 +1,35 @@
+# Stubs for hmac
+
+from typing import Any, Callable, Optional, Union, overload
+from types import ModuleType
+import sys
+
+_B = Union[bytes, bytearray]
+
+# TODO more precise type for object of hashlib
+_Hash = Any
+
+if sys.version_info >= (3, 4):
+ def new(key: _B, msg: Optional[_B] = ...,
+ digestmod: Optional[Union[str, Callable[[], _Hash], ModuleType]] = ...) -> HMAC: ...
+else:
+ def new(key: _B, msg: Optional[_B] = ...,
+ digestmod: Optional[Union[Callable[[], _Hash], ModuleType]] = ...) -> HMAC: ...
+
+class HMAC:
+ if sys.version_info >= (3,):
+ digest_size = ... # type: int
+ if sys.version_info >= (3, 4):
+ block_size = ... # type: int
+ name = ... # type: str
+ def update(self, msg: _B) -> None: ...
+ def digest(self) -> bytes: ...
+ def hexdigest(self) -> str: ...
+ def copy(self) -> HMAC: ...
+
+ at overload
+def compare_digest(a: str, b: str) -> bool: ...
+ at overload
+def compare_digest(a: bytes, b: bytes) -> bool: ...
+ at overload
+def compare_digest(a: bytearray, b: bytearray) -> bool: ...
diff --git a/typeshed/stdlib/2and3/keyword.pyi b/typeshed/stdlib/2and3/keyword.pyi
new file mode 100644
index 0000000..6e0fb5f
--- /dev/null
+++ b/typeshed/stdlib/2and3/keyword.pyi
@@ -0,0 +1,6 @@
+# Stubs for keyword
+
+from typing import Sequence, Text, Union
+
+def iskeyword(s: Union[Text, bytes]) -> bool: ...
+kwlist = ... # type: Sequence[str]
diff --git a/typeshed/stdlib/3/_locale.pyi b/typeshed/stdlib/2and3/locale.pyi
similarity index 55%
rename from typeshed/stdlib/3/_locale.pyi
rename to typeshed/stdlib/2and3/locale.pyi
index beed6c9..7a7dac7 100644
--- a/typeshed/stdlib/3/_locale.pyi
+++ b/typeshed/stdlib/2and3/locale.pyi
@@ -1,9 +1,25 @@
-# Stubs for _locale (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+# Stubs for locale
-from typing import Iterable
+from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
+import sys
+import builtins
+_str = builtins.str # TODO workaround for mypy#2010
+
+
+CODESET = ... # type: int
+D_T_FMT = ... # type: int
+D_FMT = ... # type: int
+T_FMT = ... # type: int
+T_FMT_AMPM = ... # type: int
+
+DAY_1 = ... # type: int
+DAY_2 = ... # type: int
+DAY_3 = ... # type: int
+DAY_4 = ... # type: int
+DAY_5 = ... # type: int
+DAY_6 = ... # type: int
+DAY_7 = ... # type: int
ABDAY_1 = ... # type: int
ABDAY_2 = ... # type: int
ABDAY_3 = ... # type: int
@@ -11,10 +27,20 @@ ABDAY_4 = ... # type: int
ABDAY_5 = ... # type: int
ABDAY_6 = ... # type: int
ABDAY_7 = ... # type: int
+
+MON_1 = ... # type: int
+MON_2 = ... # type: int
+MON_3 = ... # type: int
+MON_4 = ... # type: int
+MON_5 = ... # type: int
+MON_6 = ... # type: int
+MON_7 = ... # type: int
+MON_8 = ... # type: int
+MON_9 = ... # type: int
+MON_10 = ... # type: int
+MON_11 = ... # type: int
+MON_12 = ... # type: int
ABMON_1 = ... # type: int
-ABMON_10 = ... # type: int
-ABMON_11 = ... # type: int
-ABMON_12 = ... # type: int
ABMON_2 = ... # type: int
ABMON_3 = ... # type: int
ABMON_4 = ... # type: int
@@ -23,62 +49,54 @@ ABMON_6 = ... # type: int
ABMON_7 = ... # type: int
ABMON_8 = ... # type: int
ABMON_9 = ... # type: int
-ALT_DIGITS = ... # type: int
-AM_STR = ... # type: int
-CHAR_MAX = ... # type: int
-CODESET = ... # type: int
+ABMON_10 = ... # type: int
+ABMON_11 = ... # type: int
+ABMON_12 = ... # type: int
+
+RADIXCHAR = ... # type: int
+THOUSEP = ... # type: int
+YESEXPR = ... # type: int
+NOEXPR = ... # type: int
CRNCYSTR = ... # type: int
-DAY_1 = ... # type: int
-DAY_2 = ... # type: int
-DAY_3 = ... # type: int
-DAY_4 = ... # type: int
-DAY_5 = ... # type: int
-DAY_6 = ... # type: int
-DAY_7 = ... # type: int
-D_FMT = ... # type: int
-D_T_FMT = ... # type: int
+
ERA = ... # type: int
-ERA_D_FMT = ... # type: int
ERA_D_T_FMT = ... # type: int
+ERA_D_FMT = ... # type: int
ERA_T_FMT = ... # type: int
-LC_ALL = ... # type: int
-LC_COLLATE = ... # type: int
+
+ALT_DIGITS = ... # type: int
+
LC_CTYPE = ... # type: int
-LC_MESSAGES = ... # type: int
+LC_COLLATE = ... # type: int
+LC_TIME = ... # type: int
LC_MONETARY = ... # type: int
+LC_MESSAGES = ... # type: int
LC_NUMERIC = ... # type: int
-LC_TIME = ... # type: int
-MON_1 = ... # type: int
-MON_10 = ... # type: int
-MON_11 = ... # type: int
-MON_12 = ... # type: int
-MON_2 = ... # type: int
-MON_3 = ... # type: int
-MON_4 = ... # type: int
-MON_5 = ... # type: int
-MON_6 = ... # type: int
-MON_7 = ... # type: int
-MON_8 = ... # type: int
-MON_9 = ... # type: int
-NOEXPR = ... # type: int
-PM_STR = ... # type: int
-RADIXCHAR = ... # type: int
-THOUSEP = ... # type: int
-T_FMT = ... # type: int
-T_FMT_AMPM = ... # type: int
-YESEXPR = ... # type: int
-_DATE_FMT = ... # type: int
+LC_ALL = ... # type: int
-def bind_textdomain_codeset(domain, codeset): ...
-def bindtextdomain(domain, dir): ...
-def dcgettext(domain, msg, category): ...
-def dgettext(domain, msg): ...
-def gettext(msg): ...
-def localeconv(): ...
-def nl_langinfo(key): ...
-def setlocale(category: int, locale: Iterable[str] = ...) -> str: ...
-def strcoll(string1, string2) -> int: ...
-def strxfrm(string): ...
-def textdomain(domain): ...
+CHAR_MAX = ... # type: int
class Error(Exception): ...
+
+def setlocale(category: int,
+ locale: Union[_str, Iterable[_str], None] = ...) -> _str: ...
+def localeconv() -> Mapping[_str, Union[int, _str, List[int]]]: ...
+def nl_langinfo(option: int) -> _str: ...
+def getdefaultlocale(envvars: Tuple[_str] = ...) -> Tuple[Optional[_str], Optional[_str]]: ...
+def getlocale(category: int = ...) -> Sequence[_str]: ...
+def getpreferredencoding(do_setlocale: bool = ...) -> _str: ...
+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 = ...,
+ monetary: bool = ...) -> _str: ...
+def format_string(format: _str, val: Sequence[Any],
+ grouping: bool = ...) -> _str: ...
+def currency(val: int, symbol: bool = ..., grouping: bool = ...,
+ international: bool = ...) -> _str: ...
+def str(float: float) -> _str: ...
+if sys.version_info >= (3, 5):
+ def delocalize(string: _str) -> None: ...
+def atof(string: _str) -> float: ...
+def atoi(string: _str) -> int: ...
diff --git a/typeshed/stdlib/2and3/logging/__init__.pyi b/typeshed/stdlib/2and3/logging/__init__.pyi
index acc51a7..e22dfcc 100644
--- a/typeshed/stdlib/2and3/logging/__init__.pyi
+++ b/typeshed/stdlib/2and3/logging/__init__.pyi
@@ -19,7 +19,12 @@ _FilterType = Union['Filter', Callable[[LogRecord], int]]
class Logger:
+ name = ... # type: str
+ level = ... # type: int
+ parent = ... # type: Union[Logger, PlaceHolder]
propagate = ... # type: bool
+ handlers = ... # type: List[Handler]
+ disabled = ... # type: int
def setLevel(self, lvl: Union[int, str]) -> None: ...
def isEnabledFor(self, lvl: int) -> None: ...
def getEffectiveLevel(self) -> int: ...
@@ -50,28 +55,27 @@ class Logger:
stack_info: bool = ..., extra: Dict[str, Any] = ...,
**kwargs: Any) -> None: ...
else:
- def debug(self, # type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def debug(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def info(self, # type: ignore
+ def info(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def warning(self, # type: ignore
+ def warning(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def warn(self, # type: ignore
+ def warn(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def error(self, # type: ignore
+ def error(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def critical(self, # type: ignore
+ def critical(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def log(self, # type: ignore
+ def log(self,
lvl: int, msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def exception(self, # type: ignore
+ def exception(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
def addFilter(self, filt: _FilterType) -> None: ...
@@ -80,11 +84,9 @@ class Logger:
def addHandler(self, hdlr: 'Handler') -> None: ...
def removeHandler(self, hdlr: 'Handler') -> None: ...
if sys.version_info >= (3,):
- def findCaller(self, stack_info: bool = ...) \
- -> Tuple[str, int, str, Optional[str]]: ...
+ def findCaller(self, stack_info: bool = ...) -> Tuple[str, int, str, Optional[str]]: ...
else:
- def findCaller(self # type: ignore
- ) -> Tuple[str, int, str]: ...
+ def findCaller(self) -> Tuple[str, int, str]: ...
def handle(self, record: 'LogRecord') -> None: ...
if sys.version_info >= (3,):
def makeRecord(self, name: str, lvl: int, fn: str, lno: int, msg: Text,
@@ -94,7 +96,7 @@ class Logger:
extra: Optional[Mapping[str, Any]] = ...,
sinfo: Optional[str] = ...) -> None: ...
else:
- def makeRecord(self, # type: ignore
+ def makeRecord(self,
name: str, lvl: int, fn: str, lno: int, msg: Text,
args: Mapping[str, Any],
exc_info: Optional[_SysExcInfoType],
@@ -137,7 +139,7 @@ class Formatter:
datefmt: Optional[str] =...,
style: str = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
fmt: Optional[str] = ...,
datefmt: Optional[str] =...) -> None: ...
def format(self, record: LogRecord) -> str: ...
@@ -182,7 +184,7 @@ class LogRecord:
func: Optional[str] = ...,
sinfo: Optional[str] = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
name: str, level: int, pathname: str, lineno: int,
msg: Text, args: _ArgsType,
exc_info: Optional[_SysExcInfoType],
@@ -192,8 +194,7 @@ class LogRecord:
class LoggerAdapter:
def __init__(self, logger: Logger, extra: Mapping[str, Any]) -> None: ...
- def process(self, msg: Text, kwargs: MutableMapping[str, Any]) \
- -> Tuple[str, MutableMapping[str, Any]]: ...
+ def process(self, msg: Text, kwargs: MutableMapping[str, Any]) -> Tuple[str, MutableMapping[str, Any]]: ...
if sys.version_info > (3,):
def debug(self, msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
stack_info: bool = ..., extra: Dict[str, Any] = ...,
@@ -217,25 +218,25 @@ class LoggerAdapter:
stack_info: bool = ..., extra: Dict[str, Any] = ...,
**kwargs: Any) -> None: ...
else:
- def debug(self, # type: ignore
+ def debug(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def info(self, # type: ignore
+ def info(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def warning(self, # type: ignore
+ def warning(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def error(self, # type: ignore
+ def error(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def exception(self, # type: ignore
+ def exception(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def critical(self, # type: ignore
+ def critical(self,
msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def log(self, # type: ignore
+ def log(self,
lvl: int, msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
def isEnabledFor(self, lvl: int) -> None: ...
@@ -245,15 +246,13 @@ class LoggerAdapter:
def hasHandlers(self) -> bool: ...
-# TODO uncomment when mypy handle conditionals
-#if sys.version_info >= (3,):
-# def getLogger(name: Optional[str] = ...) -> Logger: ...
-#else:
-# @overload
-# def getLogger() -> Logger: ...
-# @overload
-# def getLogger(name: str) -> Logger: ...
-def getLogger(name: Optional[str] = ...) -> Logger: ...
+if sys.version_info >= (3,):
+ def getLogger(name: Optional[str] = ...) -> Logger: ...
+else:
+ @overload
+ def getLogger() -> Logger: ...
+ @overload
+ def getLogger(name: str) -> Logger: ...
def getLoggerClass() -> type: ...
if sys.version_info >= (3,):
def getLogRecordFactory() -> Callable[..., LogRecord]: ...
@@ -284,29 +283,21 @@ if sys.version_info > (3,):
stack_info: bool = ..., extra: Dict[str, Any] = ...,
**kwargs: Any) -> None: ...
else:
- def debug(# type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def debug(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def info(# type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def info(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def warning(# type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def warning(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def warn(# type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def warn(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def error(# type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def error(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def critical(# type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def critical(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def exception(# type: ignore
- msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def exception(msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
- def log(# type: ignore
- lvl: int, msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
+ def log(lvl: int, msg: Text, *args: Any, exc_info: _ExcInfoType = ...,
extra: Dict[str, Any] = ..., **kwargs: Any) -> None: ...
def disable(lvl: int) -> None: ...
@@ -315,23 +306,18 @@ def getLevelName(lvl: int) -> str: ...
def makeLogRecord(attrdict: Mapping[str, Any]) -> LogRecord: ...
-# TODO uncomment when mypy handle conditionals
-#if sys.version_info >= (3,):
-# def basicConfig(*, filename: str = ..., filemode: str = ...,
-# format: str = ..., datefmt: str = ..., style: str = ...,
-# level: int = ..., stream: IO[str] = ...,
-# handlers: Iterable[Handler]) -> None: ...
-#else:
-# @overload
-# def basicConfig() -> None: ...
-# @overload
-# def basicConfig(*, filename: str = ..., filemode: str = ...,
-# format: str = ..., datefmt: str = ...,
-# level: int = ..., stream: IO[str] = ...) -> None: ...
-def basicConfig(*, filename: str = ..., filemode: str = ...,
- format: str = ..., datefmt: str = ..., style: str = ...,
- level: int = ..., stream: IO[str] = ...,
- handlers: Iterable[Handler]) -> None: ...
+if sys.version_info >= (3,):
+ def basicConfig(*, filename: str = ..., filemode: str = ...,
+ format: str = ..., datefmt: str = ..., style: str = ...,
+ level: int = ..., stream: IO[str] = ...,
+ handlers: Iterable[Handler]) -> None: ...
+else:
+ @overload
+ def basicConfig() -> None: ...
+ @overload
+ def basicConfig(*, filename: str = ..., filemode: str = ...,
+ format: str = ..., datefmt: str = ...,
+ level: int = ..., stream: IO[str] = ...) -> None: ...
def shutdown() -> None: ...
def setLoggerClass(klass: type) -> None: ...
@@ -353,3 +339,8 @@ class FileHandler(Handler):
class NullHandler(Handler): ...
+
+
+class PlaceHolder:
+ def __init__(self, alogger: Logger) -> None: ...
+ def append(self, alogger: Logger) -> None: ...
diff --git a/typeshed/stdlib/2and3/logging/config.pyi b/typeshed/stdlib/2and3/logging/config.pyi
index b2cdf6c..d4665d7 100644
--- a/typeshed/stdlib/2and3/logging/config.pyi
+++ b/typeshed/stdlib/2and3/logging/config.pyi
@@ -2,13 +2,12 @@
from typing import Any, Callable, Dict, Optional, IO, Union
import sys
-# TODO uncomment when mypy handle conditionals
-#if sys.version_info >= (3,):
-# from configparser import RawConfigParser
-#else:
-# from ConfigParser import RawConfigParser
-# TODO add RawConfigParser to configparser stubs
-RawConfigParser = Any
+if sys.version_info >= (3,):
+ #from configparser import RawConfigParser
+ # TODO add RawConfigParser to configparser stubs
+ RawConfigParser = Any
+else:
+ from ConfigParser import RawConfigParser
def dictConfig(config: Dict[str, Any]) -> None: ...
@@ -17,13 +16,10 @@ if sys.version_info >= (3, 4):
defaults: Optional[Dict[str, str]] = ...,
disable_existing_loggers: bool = ...) -> None: ...
def listen(port: int = ...,
- verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) \
- -> None: ...
+ verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) -> None: ...
else:
- def fileConfig( # type: ignore
- fname: Union[str, IO[str]],
+ def fileConfig(fname: Union[str, IO[str]],
defaults: Optional[Dict[str, str]] = ...,
disable_existing_loggers: bool = ...) -> None: ...
- def listen( # type: ignore
- port: int = ...) -> None: ...
+ def listen(port: int = ...) -> None: ...
def stopListening() -> None: ...
diff --git a/typeshed/stdlib/2and3/logging/handlers.pyi b/typeshed/stdlib/2and3/logging/handlers.pyi
index e722354..7aedcb2 100644
--- a/typeshed/stdlib/2and3/logging/handlers.pyi
+++ b/typeshed/stdlib/2and3/logging/handlers.pyi
@@ -3,12 +3,10 @@
from typing import Any, Callable, Optional, Tuple, Union, overload
from logging import Handler, FileHandler, LogRecord
import datetime
-# TODO uncomment when mypy handle conditionals
-#if sys.version_info >= (3,):
-# from queue import Queue
-#else:
-# from Queue import Queue
-Queue = Any
+if sys.version_info >= (3,):
+ from queue import Queue
+else:
+ from Queue import Queue
from socket import SocketType
# TODO update socket stubs to add SocketKind
SocketKind = int
@@ -40,61 +38,41 @@ if sys.version_info >= (3,):
def rotate(self, source: str, dest: str) -> None: ...
-# TODO uncomment when mypy handle conditionals
-#if sys.version_info >= (3,):
-# class RotatingFileHandler(BaseRotatingHandler):
-# def __init__(self, filename: str, mode: str = ..., maxBytes: int = ...,
-# backupCount: int = ..., encoding: Optional[str] = ...,
-# delay: bool = ...) -> None: ...
-# def doRollover(self) -> None: ...
-#else:
-# class RotatingFileHandler(Handler):
-# def __init__(self, filename: str, mode: str = ..., maxBytes: int = ...,
-# backupCount: int = ..., encoding: Optional[str] = ...,
-# delay: bool = ...) -> None: ...
-# def doRollover(self) -> None: ...
-class RotatingFileHandler(BaseRotatingHandler):
- def __init__(self, filename: str, mode: str = ..., maxBytes: int = ...,
- backupCount: int = ..., encoding: Optional[str] = ...,
- delay: bool = ...) -> None: ...
- def doRollover(self) -> None: ...
-
-
-# TODO uncomment when mypy handle conditionals
-#if sys.version_info >= (3,):
-# class TimedRotatingFileHandler(BaseRotatingHandler):
-# if sys.version_info >= (3, 4):
-# def __init__(self, filename: str, when: str = ...,
-# interval: int = ...,
-# backupCount: int = ..., encoding: Optional[str] = ...,
-# delay: bool = ..., utc: bool = ...,
-# atTime: Optional[datetime.datetime] = ...) -> None: ...
-# else:
-# def __init__(self, # type: ignore
-# filename: str, when: str = ..., interval: int = ...,
-# backupCount: int = ..., encoding: Optional[str] = ...,
-# delay: bool = ..., utc: bool = ...) -> None: ...
-# def doRollover(self) -> None: ...
-#else:
-# class TimedRotatingFileHandler:
-# def __init__(self, # type: ignore
-# filename: str, when: str = ..., interval: int = ...,
-# backupCount: int = ..., encoding: Optional[str] = ...,
-# delay: bool = ..., utc: bool = ...) -> None: ...
-# def doRollover(self) -> None: ...
-class TimedRotatingFileHandler(BaseRotatingHandler):
- if sys.version_info >= (3, 4):
- def __init__(self, filename: str, when: str = ...,
- interval: int = ...,
+if sys.version_info >= (3,):
+ class RotatingFileHandler(BaseRotatingHandler):
+ def __init__(self, filename: str, mode: str = ..., maxBytes: int = ...,
backupCount: int = ..., encoding: Optional[str] = ...,
- delay: bool = ..., utc: bool = ...,
- atTime: Optional[datetime.datetime] = ...) -> None: ...
- else:
- def __init__(self, # type: ignore
+ delay: bool = ...) -> None: ...
+ def doRollover(self) -> None: ...
+else:
+ class RotatingFileHandler(Handler):
+ def __init__(self, filename: str, mode: str = ..., maxBytes: int = ...,
+ backupCount: int = ..., encoding: Optional[str] = ...,
+ delay: bool = ...) -> None: ...
+ def doRollover(self) -> None: ...
+
+
+if sys.version_info >= (3,):
+ class TimedRotatingFileHandler(BaseRotatingHandler):
+ if sys.version_info >= (3, 4):
+ def __init__(self, filename: str, when: str = ...,
+ interval: int = ...,
+ backupCount: int = ..., encoding: Optional[str] = ...,
+ delay: bool = ..., utc: bool = ...,
+ atTime: Optional[datetime.datetime] = ...) -> None: ...
+ else:
+ def __init__(self,
+ filename: str, when: str = ..., interval: int = ...,
+ backupCount: int = ..., encoding: Optional[str] = ...,
+ delay: bool = ..., utc: bool = ...) -> None: ...
+ def doRollover(self) -> None: ...
+else:
+ class TimedRotatingFileHandler:
+ def __init__(self,
filename: str, when: str = ..., interval: int = ...,
backupCount: int = ..., encoding: Optional[str] = ...,
delay: bool = ..., utc: bool = ...) -> None: ...
- def doRollover(self) -> None: ...
+ def doRollover(self) -> None: ...
class SocketHandler(Handler):
@@ -104,7 +82,7 @@ class SocketHandler(Handler):
if sys.version_info >= (3, 4):
def __init__(self, host: str, port: Optional[int]) -> None: ...
else:
- def __init__(self, host: str, port: int) -> None: ... # type: ignore
+ def __init__(self, host: str, port: int) -> None: ...
def makeSocket(self) -> SocketType: ...
def makePickle(self, record: LogRecord) -> bytes: ...
def send(self, packet: bytes) -> None: ...
@@ -168,12 +146,11 @@ class SMTPHandler(Handler):
secure: Union[Tuple[str], Tuple[str, str], None] =...,
timeout: float = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
mailhost: Union[str, Tuple[str, int]], fromaddr: str,
toaddrs: List[str], subject: str,
credentials: Optional[Tuple[str, str]] = ...,
- secure: Union[Tuple[str], Tuple[str, str], None] =...) \
- -> None: ...
+ secure: Union[Tuple[str], Tuple[str, str], None] =...) -> None: ...
def getSubject(self, record: LogRecord) -> str: ...
@@ -194,11 +171,11 @@ class HTTPHandler(Handler):
credentials: Optional[Tuple[str, str]] = ...,
context: Optional[ssl.SSLContext] = ...) -> None: ...
elif sys.version_info >= (3,):
- def __init__(self, # type: ignore
+ def __init__(self,
host: str, url: str, method: str = ..., secure: bool = ...,
credentials: Optional[Tuple[str, str]] = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
host: str, url: str, method: str = ...) -> None: ...
def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ...
@@ -214,7 +191,7 @@ if sys.version_info > (3,):
def __init__(self, queue: Queue, *handlers: Handler,
respect_handler_level: bool = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
queue: Queue, *handlers: Handler) -> None: ...
def dequeue(self, block: bool) -> LogRecord: ...
def prepare(self, record: LogRecord) -> Any: ...
diff --git a/typeshed/stdlib/2and3/math.pyi b/typeshed/stdlib/2and3/math.pyi
index 2595566..db5f6a9 100644
--- a/typeshed/stdlib/2and3/math.pyi
+++ b/typeshed/stdlib/2and3/math.pyi
@@ -29,7 +29,10 @@ def exp(x: float) -> float: ...
def expm1(x: float) -> float: ...
def fabs(x: float) -> float: ...
def factorial(x: int) -> int: ...
-def floor(x: float) -> float: ...
+if sys.version_info >= (3,):
+ def floor(x: float) -> int: ...
+else:
+ def floor(x: float) -> float: ...
def fmod(x: float, y: float) -> float: ...
def frexp(x: float) -> Tuple[float, int]: ...
def fsum(iterable: Iterable) -> float: ...
@@ -40,7 +43,7 @@ def hypot(x: float, y: float) -> float: ...
if sys.version_info >= (3, 5):
def isclose(a: float, b: float, rel_tol: float = ..., abs_tol: float = ...) -> bool: ...
def isinf(x: float) -> bool: ...
-if sys.version_info[0] >= 3:
+if sys.version_info >= (3,):
def isfinite(x: float) -> bool: ...
def isnan(x: float) -> bool: ...
def ldexp(x: float, i: int) -> float: ...
diff --git a/typeshed/stdlib/2and3/mimetypes.pyi b/typeshed/stdlib/2and3/mimetypes.pyi
new file mode 100644
index 0000000..ee1540f
--- /dev/null
+++ b/typeshed/stdlib/2and3/mimetypes.pyi
@@ -0,0 +1,38 @@
+# Stubs for mimetypes
+
+from typing import Dict, IO, Optional, Sequence, Tuple
+import sys
+
+def guess_type(url: str,
+ strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ...
+def guess_all_extensions(type: str, strict: bool = ...) -> List[str]: ...
+def guess_extension(type: str, strict: bool = ...) -> Optional[str]: ...
+
+def init(files: Optional[Sequence[str]] = ...) -> None: ...
+def read_mime_types(filename: str) -> Optional[Dict[str, str]]: ...
+def add_type(type: str, ext: str, strict: bool = ...) -> None: ...
+
+inited = ... # type: bool
+knownfiles = ... # type: List[str]
+suffix_map = ... # type: Dict[str, str]
+encodings_map = ... # type: Dict[str, str]
+types_map = ... # type: Dict[str, str]
+common_types = ... # type: Dict[str, str]
+
+class MimeTypes:
+ suffix_map = ... # type: Dict[str, str]
+ encodings_map = ... # type: Dict[str, str]
+ types_map = ... # type: Tuple[Dict[str, str], Dict[str, str]]
+ types_map_inv = ... # type: Tuple[Dict[str, str], Dict[str, str]]
+ def __init__(self, filenames: Tuple[str, ...] = ...,
+ strict: bool = ...) -> None: ...
+ def guess_extension(self, type: str,
+ strict: bool = ...) -> Optional[str]: ...
+ def guess_type(self, url: str,
+ strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ...
+ def guess_all_extensions(self, type: str,
+ strict: bool = ...) -> List[str]: ...
+ def read(self, filename: str, strict: bool = ...) -> None: ...
+ def readfp(self, fp: IO[str], strict: bool = ...) -> None: ...
+ if sys.platform == 'win32':
+ def read_windows_registry(self, strict: bool = ...) -> None: ...
diff --git a/typeshed/stdlib/2and3/mmap.pyi b/typeshed/stdlib/2and3/mmap.pyi
new file mode 100644
index 0000000..2f4978f
--- /dev/null
+++ b/typeshed/stdlib/2and3/mmap.pyi
@@ -0,0 +1,80 @@
+# Stubs for mmap
+
+from typing import (Optional, Sequence, Union, Generic, TypeVar, overload,
+ Iterable, Container, Sized, Reversible)
+import sys
+
+
+_T = TypeVar('_T', str, bytes)
+
+# TODO already in PEP, have to get added to mypy
+from typing import Type
+from types import TracebackType
+_C = TypeVar('_C')
+class _ContextManager(Generic[_C]):
+ def __enter__(self) -> _C: ...
+ def __exit__(self, exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[TracebackType]) -> bool: ...
+
+
+ACCESS_READ = ... # type: int
+ACCESS_WRITE = ... # type: int
+ACCESS_COPY = ... # type: int
+
+ALLOCATIONGRANULARITY = ... # type: int
+
+if sys.platform != 'win32':
+ MAP_PRIVATE = ... # type: int
+ MAP_SHARED = ... # type: int
+ PROT_READ = ... # type: int
+ PROT_WRITE = ... # type: int
+
+ PAGESIZE = ... # type: int
+
+class _mmap(Generic[_T]):
+ if sys.platform == 'win32':
+ def __init__(self, fileno: int, length: int,
+ tagname: Optional[str] = ..., access: int = ...,
+ offset: int = ...) -> None: ...
+ else:
+ def __init__(self,
+ fileno: int, length: int, flags: int = ...,
+ prot: int = ..., access: int = ...,
+ offset: int = ...) -> None: ...
+ def close(self) -> None: ...
+ def find(self, sub: _T,
+ start: int = ..., end: int = ...) -> int: ...
+ def flush(self, offset: int = ..., size: int = ...) -> int: ...
+ def move(self, dest: int, src: int, count: int) -> None: ...
+ def read(self, n: int = ...) -> _T: ...
+ def read_byte(self) -> _T: ...
+ def readline(self) -> _T: ...
+ def resize(self, newsize: int) -> None: ...
+ def seek(self, pos: int, whence: int = ...) -> None: ...
+ def size(self) -> int: ...
+ def tell(self) -> int: ...
+ def write(self, bytes: _T) -> None: ...
+ def write_byte(self, byte: _T) -> None: ...
+ def __len__(self) -> int: ...
+
+if sys.version_info >= (3,):
+ class mmap(_mmap, _ContextManager[mmap], Iterable[bytes], Container[bytes],
+ Sized, Reversible[bytes]):
+ closed = ... # type: bool
+ def rfind(self, sub: bytes, start: int = ..., stop: int = ...) -> int: ...
+ @overload
+ def __getitem__(self, index: int) -> int: ...
+ @overload
+ def __getitem__(self, index: slice) -> bytes: ...
+ def __delitem__(self, index: Union[int, slice]) -> None: ...
+ @overload
+ def __setitem__(self, index: int, object: int) -> None: ...
+ @overload
+ def __setitem__(self, index: slice, object: bytes) -> None: ...
+else:
+ class mmap(_mmap, Sequence[str]):
+ def rfind(self, string: str, start: int = ..., stop: int = ...) -> int: ...
+ def __getitem__(self, index: Union[int, slice]) -> str: ...
+ def __delitem__(self, index: Union[int, slice]) -> None: ...
+ def __setitem__(self, index: Union[int, slice], object: str) -> None: ...
diff --git a/typeshed/stdlib/2and3/operator.pyi b/typeshed/stdlib/2and3/operator.pyi
index 125ec67..a45a79d 100644
--- a/typeshed/stdlib/2and3/operator.pyi
+++ b/typeshed/stdlib/2and3/operator.pyi
@@ -1,135 +1,227 @@
# Stubs for operator
-from typing import Any, Callable, overload, Tuple
+from typing import (
+ Any, Callable, Container, Mapping, MutableMapping, MutableSequence, Sequence, SupportsAbs, Tuple,
+ TypeVar, overload,
+)
+import sys
-def __abs__(a: Any) -> Any: ...
-def __add__(a: Any, b: Any) -> Any: ...
-def __and__(a: Any, b: Any) -> Any: ...
-def __concat__(a: Any, b: Any) -> Any: ...
-def __contains__(container: Any, item: Any) -> bool: ...
-def __delitem__(container: Any, item: Any) -> None: ...
-def __delslice__(container: Any, b: int, c: int) -> None: ...
-def __div__(a: Any, b: Any) -> Any: ...
+
+_T = TypeVar('_T')
+_K = TypeVar('_K')
+_V = TypeVar('_V')
+
+
+def lt(a: Any, b: Any) -> Any: ...
+def le(a: Any, b: Any) -> Any: ...
+def eq(a: Any, b: Any) -> Any: ...
+def ne(a: Any, b: Any) -> Any: ...
+def ge(a: Any, b: Any) -> Any: ...
+def gt(a: Any, b: Any) -> Any: ...
+def __lt__(a: Any, b: Any) -> Any: ...
+def __le__(a: Any, b: Any) -> Any: ...
def __eq__(a: Any, b: Any) -> Any: ...
-def __floordiv__(a: Any, b: Any) -> Any: ...
+def __ne__(a: Any, b: Any) -> Any: ...
def __ge__(a: Any, b: Any) -> Any: ...
-def __getitem__(container: Any, key: Any) -> Any: ...
-def __getslice__(container, b: int, c: int) -> Any: ...
def __gt__(a: Any, b: Any) -> Any: ...
-def __iadd__(a: Any, b: Any) -> Any: ...
-def __iand__(a: Any, b: Any) -> Any: ...
-def __iconcat__(a: Any, b: Any) -> Any: ...
-def __idiv__(a: Any, b: Any) -> Any: ...
-def __ifloordiv__(a: Any, b: Any) -> Any: ...
-def __ilshift__(a: Any, b: Any) -> Any: ...
-def __imod__(a: Any, b: Any) -> Any: ...
-def __imul__(a: Any, b: Any) -> Any: ...
-def __index__(x: Any) -> Any: ...
-def __inv__(x: Any) -> Any: ...
-def __invert__(x: Any) -> Any: ...
-def __ior__(a: Any, b: Any) -> Any: ...
-def __ipow__(a: Any, b: Any) -> Any: ...
-def __irepeat__(a: Any, b: int) -> Any: ...
-def __irshift__(a: Any, b: Any) -> Any: ...
-def __isub__(a: Any, b: Any) -> Any: ...
-def __itruediv__(a: Any, b: Any) -> Any: ...
-def __ixor__(a: Any, b: Any) -> Any: ...
-def __le__(a: Any, b: Any) -> Any: ...
+
+def not_(obj: Any) -> bool: ...
+def __not__(obj: Any) -> bool: ...
+
+def truth(x: Any) -> bool: ...
+
+def is_(a: Any, b: Any) -> bool: ...
+
+def is_not(a: Any, b: Any) -> bool: ...
+
+def abs(x: SupportsAbs) -> Any: ...
+def __abs__(a: SupportsAbs) -> Any: ...
+
+def add(a: Any, b: Any) -> Any: ...
+def __add__(a: Any, b: Any) -> Any: ...
+
+def and_(a: Any, b: Any) -> Any: ...
+def __and__(a: Any, b: Any) -> Any: ...
+
+if sys.version_info < (3,):
+ def div(a: Any, b: Any) -> Any: ...
+ def __div__(a: Any, b: Any) -> Any: ...
+
+def floordiv(a: Any, b: Any) -> Any: ...
+def __floordiv__(a: Any, b: Any) -> Any: ...
+
+def index(a: Any) -> int: ...
+def __index__(a: Any) -> int: ...
+
+def inv(obj: Any) -> Any: ...
+def invert(obj: Any) -> Any: ...
+def __inv__(obj: Any) -> Any: ...
+def __invert__(obj: Any) -> Any: ...
+
+def lshift(a: Any, b: Any) -> Any: ...
def __lshift__(a: Any, b: Any) -> Any: ...
-def __lt__(a: Any, b: Any) -> Any: ...
+
+def mod(a: Any, b: Any) -> Any: ...
def __mod__(a: Any, b: Any) -> Any: ...
+
+def mul(a: Any, b: Any) -> Any: ...
def __mul__(a: Any, b: Any) -> Any: ...
-def __ne__(a: Any, b: Any) -> Any: ...
-def __neg__(x: Any) -> Any: ...
-def __not__(x: Any) -> bool: ...
+
+if sys.version_info >= (3,5):
+ def matmul(a: Any, b: Any) -> Any: ...
+ def __matmul__(a: Any, b: Any) -> Any: ...
+
+def neg(obj: Any) -> Any: ...
+def __neg__(obj: Any) -> Any: ...
+
+def or_(a: Any, b: Any) -> Any: ...
def __or__(a: Any, b: Any) -> Any: ...
-def __pos__(x: Any) -> Any: ...
+
+def pos(obj: Any) -> Any: ...
+def __pos__(obj: Any) -> Any: ...
+
+def pow(a: Any, b: Any) -> Any: ...
def __pow__(a: Any, b: Any) -> Any: ...
-def __repeat__(a, b: int) -> Any: ...
+
+def rshift(a: Any, b: Any) -> Any: ...
def __rshift__(a: Any, b: Any) -> Any: ...
-def __setitem__(container: Any, b: Any) -> None: ...
-def __setslice__(container: Any, b: int, c: int, item: Any) -> None: ...
+
+def sub(a: Any, b: Any) -> Any: ...
def __sub__(a: Any, b: Any) -> Any: ...
+
+def truediv(a: Any, b: Any) -> Any: ...
def __truediv__(a: Any, b: Any) -> Any: ...
+
+def xor(a: Any, b: Any) -> Any: ...
def __xor__(a: Any, b: Any) -> Any: ...
-def abs(x: Any) -> Any: ...
-def add(a: Any, b: Any) -> Any: ...
-def and_(a: Any, b: Any) -> Any: ...
-def concat(a: Any, b: Any) -> Any: ...
-def contains(container: Any, item: Any) -> bool: ...
-def countOf(container: Any, item: Any) -> int: ...
-def delitem(container: Any, item: Any) -> None: ...
-def delslice(container: Any, b: int, c: int) -> None: ...
-def div(a: Any, b: Any) -> Any: ...
-def eq(a: Any, b: Any) -> Any: ...
-def floordiv(a: Any, b: Any) -> Any: ...
-def ge(a: Any, b: Any) -> Any: ...
-def getitem(a: Any, b: Any) -> Any: ...
-def getslice(container: Any, b: int, c: int) -> Any: ...
-def gt(a: Any, b: Any) -> Any: ...
+def concat(a: Sequence[_T], b: Sequence[_T]) -> Sequence[_T]: ...
+def __concat__(a: Sequence[_T], b: Sequence[_T]) -> Sequence[_T]: ...
+
+def contains(a: Container[Any], b: Any) -> bool: ...
+def __contains__(a: Container[Any], b: Any) -> bool: ...
+
+def countOf(a: Container[Any], b: Any) -> int: ...
+
+ at overload
+def delitem(a: MutableSequence[_T], b: int) -> None: ...
+ at overload
+def delitem(a: MutableMapping[_K, _V], b: _K) -> None: ...
+ at overload
+def __delitem__(a: MutableSequence[_T], b: int) -> None: ...
+ at overload
+def __delitem__(a: MutableMapping[_K, _V], b: _K) -> None: ...
+
+if sys.version_info < (3,):
+ def delslice(a: MutableSequence[Any], b: int, c: int) -> None: ...
+ def __delslice__(a: MutableSequence[Any], b: int, c: int) -> None: ...
+
+ at overload
+def getitem(a: Sequence[_T], b: int) -> _T: ...
+ at overload
+def getitem(a: Mapping[_K, _V], b: _K) -> _V: ...
+ at overload
+def __getitem__(a: Sequence[_T], b: int) -> _T: ...
+ at overload
+def __getitem__(a: Mapping[_K, _V], b: _K) -> _V: ...
+
+if sys.version_info < (3,):
+ def getslice(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ...
+ def __getslice__(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ...
+
+def indexOf(a: Sequence[_T], b: _T) -> int: ...
+
+if sys.version_info < (3,):
+ def repeat(a: Any, b: int) -> Any: ...
+ def __repeat__(a: Any, b: int) -> Any: ...
+
+if sys.version_info < (3,):
+ def sequenceIncludes(a: Container[Any], b: Any) -> bool: ...
+
+ at overload
+def setitem(a: MutableSequence[_T], b: int, c: _T) -> None: ...
+ at overload
+def setitem(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ...
+ at overload
+def __setitem__(a: MutableSequence[_T], b: int, c: _T) -> None: ...
+ at overload
+def __setitem__(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ...
+
+if sys.version_info < (3,):
+ def setslice(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ...
+ def __setslice__(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ...
+
+
+if sys.version_info >= (3, 4):
+ def length_hint(obj: Any, default: int = ...) -> int: ...
+
+ at overload
+def attrgetter(attr: str) -> Callable[[Any], Any]: ...
+ at overload
+def attrgetter(*attrs: str) -> Callable[[Any], Tuple[Any, ...]]: ...
+
+ at overload
+def itemgetter(item: int) -> Callable[[Any], Any]: ...
+ at overload
+def itemgetter(*items: int) -> Callable[[Any], Tuple[Any, ...]]: ...
+
+def methodcaller(name: str, *args: Any, **kwargs: Any) -> Callable[..., Any]: ...
+
+
def iadd(a: Any, b: Any) -> Any: ...
+def __iadd__(a: Any, b: Any) -> Any: ...
+
def iand(a: Any, b: Any) -> Any: ...
+def __iand__(a: Any, b: Any) -> Any: ...
+
def iconcat(a: Any, b: Any) -> Any: ...
-def idiv(a: Any, b: Any) -> Any: ...
+def __iconcat__(a: Any, b: Any) -> Any: ...
+
+if sys.version_info < (3,):
+ def idiv(a: Any, b: Any) -> Any: ...
+ def __idiv__(a: Any, b: Any) -> Any: ...
+
def ifloordiv(a: Any, b: Any) -> Any: ...
+def __ifloordiv__(a: Any, b: Any) -> Any: ...
+
def ilshift(a: Any, b: Any) -> Any: ...
+def __ilshift__(a: Any, b: Any) -> Any: ...
+
def imod(a: Any, b: Any) -> Any: ...
+def __imod__(a: Any, b: Any) -> Any: ...
+
def imul(a: Any, b: Any) -> Any: ...
-def index(x: Any) -> Any: ...
-def indexOf(container: Any, item: Any) -> int: ...
-def inv(x: Any) -> Any: ...
-def invert(x: Any) -> Any: ...
+def __imul__(a: Any, b: Any) -> Any: ...
+
+if sys.version_info >= (3,5):
+ def imatmul(a: Any, b: Any) -> Any: ...
+ def __imatmul__(a: Any, b: Any) -> Any: ...
+
def ior(a: Any, b: Any) -> Any: ...
+def __ior__(a: Any, b: Any) -> Any: ...
+
def ipow(a: Any, b: Any) -> Any: ...
-def irepeat(a, b: int) -> Any: ...
+def __ipow__(a: Any, b: Any) -> Any: ...
+
+if sys.version_info < (3,):
+ def irepeat(a: Any, b: int) -> Any: ...
+ def __irepeat__(a: Any, b: int) -> Any: ...
+
def irshift(a: Any, b: Any) -> Any: ...
-def isCallable(x: Any) -> bool: ...
-def isMappingType(x: Any) -> bool: ...
-def isNumberType(x: Any) -> bool: ...
-def isSequenceType(x: Any) -> bool: ...
-def is_(a: Any, b: Any) -> bool: ...
-def is_not(a: Any, b: Any) -> bool: ...
+def __irshift__(a: Any, b: Any) -> Any: ...
+
def isub(a: Any, b: Any) -> Any: ...
+def __isub__(a: Any, b: Any) -> Any: ...
+
def itruediv(a: Any, b: Any) -> Any: ...
-def ixor(a: Any, b: Any) -> Any: ...
-def le(a: Any, b: Any) -> Any: ...
-def lshift(a: Any, b: Any) -> Any: ...
-def lt(a: Any, b: Any) -> Any: ...
-def mod(a: Any, b: Any) -> Any: ...
-def mul(a: Any, b: Any) -> Any: ...
-def ne(a: Any, b: Any) -> Any: ...
-def neg(x: Any) -> Any: ...
-def not_(x: Any) -> bool: ...
-def or_(a: Any, b: Any) -> Any: ...
-def pos(x: Any) -> Any: ...
-def pow(a: Any, b: Any) -> Any: ...
-def repeat(a, b: int) -> Any: ...
-def rshift(a: Any, b: Any) -> Any: ...
-def sequenceIncludes(seq1: Any, seq2: Any) -> bool: ...
-def setitem(container: Any, key: Any, item: Any) -> None: ...
-def setslice(container: Any, b: int, c: int, slice: Any) -> None: ...
-def sub(a: Any, b: Any) -> Any: ...
-def truediv(a: Any, b: Any) -> Any: ...
-def truth(x: Any) -> bool: ...
-def xor(a: Any, b: Any) -> Any: ...
+def __itruediv__(a: Any, b: Any) -> Any: ...
-# Unsupported: more than 3 attributes.
-# Unsupported: on Python 2 the parameter type should be `basestring`.
- at overload
-def attrgetter(attr1: str) -> Callable[[Any], Any]: ...
- at overload
-def attrgetter(attr1: str, attr2: str) -> Callable[[Any], Tuple[Any, Any]]: ...
- at overload
-def attrgetter(attr1: str, attr2: str, attr3: str) -> Callable[[Any], Tuple[Any, Any, Any]]: ...
+def ixor(a: Any, b: Any) -> Any: ...
+def __ixor__(a: Any, b: Any) -> Any: ...
-# Unsupported: more than 3 items.
- at overload
-def itemgetter(item1: Any) -> Callable[[Any], Any]: ...
- at overload
-def itemgetter(item1: Any, item2: Any) -> Callable[[Any], Tuple[Any, Any]]: ...
- at overload
-def itemgetter(item1: Any, item2: Any, item3: Any) -> Callable[[Any], Tuple[Any, Any, Any]]: ...
-# Unsupported: on Python 2 the parameter type should be `basestring`.
-def methodcaller(name: str, *args, **kwargs) -> Callable[[Any], Any]: ...
+if sys.version_info < (3,):
+ def isCallable(x: Any) -> bool: ...
+ def isMappingType(x: Any) -> bool: ...
+ def isNumberType(x: Any) -> bool: ...
+ def isSequenceType(x: Any) -> bool: ...
diff --git a/typeshed/stdlib/2and3/pkgutil.pyi b/typeshed/stdlib/2and3/pkgutil.pyi
new file mode 100644
index 0000000..d7767eb
--- /dev/null
+++ b/typeshed/stdlib/2and3/pkgutil.pyi
@@ -0,0 +1,31 @@
+# Stubs for pkgutil
+
+from typing import Any, Callable, Generator, IO, Iterable, Optional, Tuple
+import sys
+
+if sys.version_info >= (3,):
+ from importlib.abc import Loader
+else:
+ Loader = Any
+
+_YMFNI = Generator[Tuple[Any, str, bool], None, None]
+
+
+def extend_path(path: Iterable[str], name: str) -> Iterable[str]: ...
+
+class ImpImporter:
+ def __init__(self, dirname: Optional[str] = ...) -> None: ...
+
+class ImpLoader:
+ def __init__(self, fullname: str, file: IO[str], filename: str,
+ etc: Tuple[str, str, int]) -> None: ...
+
+def find_loader(fullname: str) -> Loader: ...
+def get_importer(path_item: str) -> Any: ... # TODO precise type
+def get_loader(module_or_name: str) -> Loader: ...
+def iter_importers(fullname: str = ...) -> Generator[Any, None, None]: ... # TODO precise type
+def iter_modules(path: Optional[str] = ...,
+ prefix: str = ...) -> _YMFNI: ... # TODO precise type
+def walk_packages(path: Optional[str] = ..., prefix: str = ...,
+ onerror: Optional[Callable[[str], None]] = ...) -> _YMFNI: ...
+def get_data(package: str, resource: str) -> bytes: ...
diff --git a/typeshed/stdlib/2and3/plistlib.pyi b/typeshed/stdlib/2and3/plistlib.pyi
new file mode 100644
index 0000000..a367c7a
--- /dev/null
+++ b/typeshed/stdlib/2and3/plistlib.pyi
@@ -0,0 +1,60 @@
+# Stubs for plistlib
+
+from typing import (
+ Any, IO, Mapping, MutableMapping, Optional, Union,
+ Type, TypeVar,
+)
+from typing import Dict as DictT
+from enum import Enum
+import sys
+
+mm = MutableMapping[str, Any]
+_D = TypeVar('_D', mm)
+if sys.version_info >= (3,):
+ _Path = str
+else:
+ _Path = Union[str, unicode]
+
+
+if sys.version_info >= (3,):
+ class PlistFormat(Enum):
+ FMT_XML = ... # type: PlistFormat
+ FMT_BINARY = ... # type: PlistFormat
+
+if sys.version_info >= (3, 4):
+ def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ...,
+ use_builtin_types: bool, dict_type: Type[_D] =...) -> _D: ...
+ def loads(data: bytes, *, fmt: Optional[PlistFormat] = ...,
+ use_builtin_types: bool = ..., dict_type: Type[_D] = ...) -> _D: ...
+ def dump(value: Mapping[str, Any], fp: IO[bytes], *,
+ fmt: PlistFormat =..., sort_keys: bool = ...,
+ skipkeys: bool = ...) -> None: ...
+ def dumps(value: Mapping[str, Any], *, fmt: PlistFormat = ...,
+ skipkeys: bool = ..., sort_keys: bool = ...) -> bytes: ...
+
+def readPlist(pathOrFile: Union[_Path, IO[bytes]]) -> DictT[str, Any]: ...
+def writePlist(value: Mapping[str, Any], pathOrFile: Union[_Path, IO[bytes]]) -> None: ...
+def readPlistFromBytes(data: bytes) -> DictT[str, Any]: ...
+def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ...
+if sys.version_info < (3,) and sys.platform == 'darwin':
+ def readPlistFromResource(path: _Path, restype: str = ...,
+ resid: int = ...) -> DictT[str, Any]: ...
+ def writePlistToResource(rootObject: Mapping[str, Any], path: _Path,
+ restype: str = ...,
+ resid: int = ...) -> None: ...
+ def readPlistFromString(data: str) -> DictT[str, Any]: ...
+ def writePlistToString(rootObject: Mapping[str, Any]) -> str: ...
+
+if sys.version_info >= (3,):
+ class Dict(dict):
+ def __getattr__(self, attr: str) -> Any: ...
+ def __setattr__(self, attr: str, value: Any) -> None: ...
+ def __delattr__(self, attr: str) -> None: ...
+
+class Data:
+ data = ... # type: bytes
+ def __init__(self, data: bytes) -> None: ...
+
+if sys.version_info >= (3,):
+ FMT_XML = PlistFormat.FMT_XML
+ FMT_BINARY = PlistFormat.FMT_BINARY
diff --git a/typeshed/stdlib/2and3/readline.pyi b/typeshed/stdlib/2and3/readline.pyi
new file mode 100644
index 0000000..aff2deb
--- /dev/null
+++ b/typeshed/stdlib/2and3/readline.pyi
@@ -0,0 +1,41 @@
+# Stubs for readline
+
+from typing import Callable, Optional, Sequence
+import sys
+
+_CompleterT = Optional[Callable[[str, int], Optional[str]]]
+_CompDispT = Optional[Callable[[str, Sequence[str], int], None]]
+
+
+def parse_and_bind(string: str) -> None: ...
+def read_init_file(filename: str = ...) -> None: ...
+
+def get_line_buffer() -> str: ...
+def insert_text(string: str) -> None: ...
+def redisplay() -> None: ...
+
+def read_history_file(filename: str = ...) -> None: ...
+def write_history_file(filename: str = ...) -> None: ...
+if sys.version_info >= (3, 5):
+ def append_history_file(nelements: int, filename: str = ...) -> None: ...
+def get_history_length() -> int: ...
+def set_history_length(length: int) -> None: ...
+
+def clear_history() -> None: ...
+def get_current_history_length() -> int: ...
+def get_history_item(index: int) -> str: ...
+def remove_history_item(pos: int) -> None: ...
+def replace_history_item(pos: int, line: str) -> None: ...
+def add_history(string: str) -> None: ...
+
+def set_startup_hook(function: Optional[Callable[[], None]] = ...) -> None: ...
+def set_pre_input_hook(function: Optional[Callable[[], None]] = ...) -> None: ...
+
+def set_completer(function: _CompleterT = ...) -> None: ...
+def get_completer() -> _CompleterT: ...
+def get_completion_type() -> int: ...
+def get_begidx() -> int: ...
+def get_endidx() -> int: ...
+def set_completer_delims(string: str) -> None: ...
+def get_completer_delims() -> str: ...
+def set_completion_display_matches_hook(function: _CompDispT = ...) -> None: ...
diff --git a/typeshed/stdlib/2and3/rlcompleter.pyi b/typeshed/stdlib/2and3/rlcompleter.pyi
new file mode 100644
index 0000000..17e98c6
--- /dev/null
+++ b/typeshed/stdlib/2and3/rlcompleter.pyi
@@ -0,0 +1,13 @@
+# Stubs for rlcompleter
+
+from typing import Optional, Union
+import sys
+
+if sys.version_info >= (3,):
+ _Text = str
+else:
+ _Text = Union[str, unicode]
+
+
+class Completer:
+ def complete(self, text: _Text, state: int) -> Optional[str]: ...
diff --git a/typeshed/stdlib/2and3/site.pyi b/typeshed/stdlib/2and3/site.pyi
new file mode 100644
index 0000000..411677a
--- /dev/null
+++ b/typeshed/stdlib/2and3/site.pyi
@@ -0,0 +1,17 @@
+# Stubs for site
+
+from typing import List, Iterable, Optional
+import sys
+
+PREFIXES = ... # type: List[str]
+ENABLE_USER_SITE = ... # type: Optional[bool]
+USER_SITE = ... # type: Optional[str]
+USER_BASE = ... # type: Optional[str]
+
+if sys.version_info < (3,):
+ def main() -> None: ...
+def addsitedir(sitedir: str,
+ known_paths: Optional[Iterable[str]] = ...) -> None: ...
+def getsitepackages(prefixes: Optional[Iterable[str]] = ...) -> List[str]: ...
+def getuserbase() -> str: ...
+def getusersitepackages() -> str: ...
diff --git a/typeshed/stdlib/2and3/termios.pyi b/typeshed/stdlib/2and3/termios.pyi
new file mode 100644
index 0000000..aff13b5
--- /dev/null
+++ b/typeshed/stdlib/2and3/termios.pyi
@@ -0,0 +1,246 @@
+# Stubs for termios
+
+from typing import IO, List, Union
+
+_FD = Union[int, IO[str]]
+_Attr = List[Union[int, List[bytes]]]
+
+# TODO constants not really documented
+B0 = ... # type: int
+B1000000 = ... # type: int
+B110 = ... # type: int
+B115200 = ... # type: int
+B1152000 = ... # type: int
+B1200 = ... # type: int
+B134 = ... # type: int
+B150 = ... # type: int
+B1500000 = ... # type: int
+B1800 = ... # type: int
+B19200 = ... # type: int
+B200 = ... # type: int
+B2000000 = ... # type: int
+B230400 = ... # type: int
+B2400 = ... # type: int
+B2500000 = ... # type: int
+B300 = ... # type: int
+B3000000 = ... # type: int
+B3500000 = ... # type: int
+B38400 = ... # type: int
+B4000000 = ... # type: int
+B460800 = ... # type: int
+B4800 = ... # type: int
+B50 = ... # type: int
+B500000 = ... # type: int
+B57600 = ... # type: int
+B576000 = ... # type: int
+B600 = ... # type: int
+B75 = ... # type: int
+B921600 = ... # type: int
+B9600 = ... # type: int
+BRKINT = ... # type: int
+BS0 = ... # type: int
+BS1 = ... # type: int
+BSDLY = ... # type: int
+CBAUD = ... # type: int
+CBAUDEX = ... # type: int
+CDSUSP = ... # type: int
+CEOF = ... # type: int
+CEOL = ... # type: int
+CEOT = ... # type: int
+CERASE = ... # type: int
+CFLUSH = ... # type: int
+CIBAUD = ... # type: int
+CINTR = ... # type: int
+CKILL = ... # type: int
+CLNEXT = ... # type: int
+CLOCAL = ... # type: int
+CQUIT = ... # type: int
+CR0 = ... # type: int
+CR1 = ... # type: int
+CR2 = ... # type: int
+CR3 = ... # type: int
+CRDLY = ... # type: int
+CREAD = ... # type: int
+CRPRNT = ... # type: int
+CRTSCTS = ... # type: int
+CS5 = ... # type: int
+CS6 = ... # type: int
+CS7 = ... # type: int
+CS8 = ... # type: int
+CSIZE = ... # type: int
+CSTART = ... # type: int
+CSTOP = ... # type: int
+CSTOPB = ... # type: int
+CSUSP = ... # type: int
+CWERASE = ... # type: int
+ECHO = ... # type: int
+ECHOCTL = ... # type: int
+ECHOE = ... # type: int
+ECHOK = ... # type: int
+ECHOKE = ... # type: int
+ECHONL = ... # type: int
+ECHOPRT = ... # type: int
+EXTA = ... # type: int
+EXTB = ... # type: int
+FF0 = ... # type: int
+FF1 = ... # type: int
+FFDLY = ... # type: int
+FIOASYNC = ... # type: int
+FIOCLEX = ... # type: int
+FIONBIO = ... # type: int
+FIONCLEX = ... # type: int
+FIONREAD = ... # type: int
+FLUSHO = ... # type: int
+HUPCL = ... # type: int
+ICANON = ... # type: int
+ICRNL = ... # type: int
+IEXTEN = ... # type: int
+IGNBRK = ... # type: int
+IGNCR = ... # type: int
+IGNPAR = ... # type: int
+IMAXBEL = ... # type: int
+INLCR = ... # type: int
+INPCK = ... # type: int
+IOCSIZE_MASK = ... # type: int
+IOCSIZE_SHIFT = ... # type: int
+ISIG = ... # type: int
+ISTRIP = ... # type: int
+IUCLC = ... # type: int
+IXANY = ... # type: int
+IXOFF = ... # type: int
+IXON = ... # type: int
+NCC = ... # type: int
+NCCS = ... # type: int
+NL0 = ... # type: int
+NL1 = ... # type: int
+NLDLY = ... # type: int
+NOFLSH = ... # type: int
+N_MOUSE = ... # type: int
+N_PPP = ... # type: int
+N_SLIP = ... # type: int
+N_STRIP = ... # type: int
+N_TTY = ... # type: int
+OCRNL = ... # type: int
+OFDEL = ... # type: int
+OFILL = ... # type: int
+OLCUC = ... # type: int
+ONLCR = ... # type: int
+ONLRET = ... # type: int
+ONOCR = ... # type: int
+OPOST = ... # type: int
+PARENB = ... # type: int
+PARMRK = ... # type: int
+PARODD = ... # type: int
+PENDIN = ... # type: int
+TAB0 = ... # type: int
+TAB1 = ... # type: int
+TAB2 = ... # type: int
+TAB3 = ... # type: int
+TABDLY = ... # type: int
+TCFLSH = ... # type: int
+TCGETA = ... # type: int
+TCGETS = ... # type: int
+TCIFLUSH = ... # type: int
+TCIOFF = ... # type: int
+TCIOFLUSH = ... # type: int
+TCION = ... # type: int
+TCOFLUSH = ... # type: int
+TCOOFF = ... # type: int
+TCOON = ... # type: int
+TCSADRAIN = ... # type: int
+TCSAFLUSH = ... # type: int
+TCSANOW = ... # type: int
+TCSBRK = ... # type: int
+TCSBRKP = ... # type: int
+TCSETA = ... # type: int
+TCSETAF = ... # type: int
+TCSETAW = ... # type: int
+TCSETS = ... # type: int
+TCSETSF = ... # type: int
+TCSETSW = ... # type: int
+TCXONC = ... # type: int
+TIOCCONS = ... # type: int
+TIOCEXCL = ... # type: int
+TIOCGETD = ... # type: int
+TIOCGICOUNT = ... # type: int
+TIOCGLCKTRMIOS = ... # type: int
+TIOCGPGRP = ... # type: int
+TIOCGSERIAL = ... # type: int
+TIOCGSOFTCAR = ... # type: int
+TIOCGWINSZ = ... # type: int
+TIOCINQ = ... # type: int
+TIOCLINUX = ... # type: int
+TIOCMBIC = ... # type: int
+TIOCMBIS = ... # type: int
+TIOCMGET = ... # type: int
+TIOCMIWAIT = ... # type: int
+TIOCMSET = ... # type: int
+TIOCM_CAR = ... # type: int
+TIOCM_CD = ... # type: int
+TIOCM_CTS = ... # type: int
+TIOCM_DSR = ... # type: int
+TIOCM_DTR = ... # type: int
+TIOCM_LE = ... # type: int
+TIOCM_RI = ... # type: int
+TIOCM_RNG = ... # type: int
+TIOCM_RTS = ... # type: int
+TIOCM_SR = ... # type: int
+TIOCM_ST = ... # type: int
+TIOCNOTTY = ... # type: int
+TIOCNXCL = ... # type: int
+TIOCOUTQ = ... # type: int
+TIOCPKT = ... # type: int
+TIOCPKT_DATA = ... # type: int
+TIOCPKT_DOSTOP = ... # type: int
+TIOCPKT_FLUSHREAD = ... # type: int
+TIOCPKT_FLUSHWRITE = ... # type: int
+TIOCPKT_NOSTOP = ... # type: int
+TIOCPKT_START = ... # type: int
+TIOCPKT_STOP = ... # type: int
+TIOCSCTTY = ... # type: int
+TIOCSERCONFIG = ... # type: int
+TIOCSERGETLSR = ... # type: int
+TIOCSERGETMULTI = ... # type: int
+TIOCSERGSTRUCT = ... # type: int
+TIOCSERGWILD = ... # type: int
+TIOCSERSETMULTI = ... # type: int
+TIOCSERSWILD = ... # type: int
+TIOCSER_TEMT = ... # type: int
+TIOCSETD = ... # type: int
+TIOCSLCKTRMIOS = ... # type: int
+TIOCSPGRP = ... # type: int
+TIOCSSERIAL = ... # type: int
+TIOCSSOFTCAR = ... # type: int
+TIOCSTI = ... # type: int
+TIOCSWINSZ = ... # type: int
+TOSTOP = ... # type: int
+VDISCARD = ... # type: int
+VEOF = ... # type: int
+VEOL = ... # type: int
+VEOL2 = ... # type: int
+VERASE = ... # type: int
+VINTR = ... # type: int
+VKILL = ... # type: int
+VLNEXT = ... # type: int
+VMIN = ... # type: int
+VQUIT = ... # type: int
+VREPRINT = ... # type: int
+VSTART = ... # type: int
+VSTOP = ... # type: int
+VSUSP = ... # type: int
+VSWTC = ... # type: int
+VSWTCH = ... # type: int
+VT0 = ... # type: int
+VT1 = ... # type: int
+VTDLY = ... # type: int
+VTIME = ... # type: int
+VWERASE = ... # type: int
+XCASE = ... # type: int
+XTABS = ... # type: int
+
+def tcgetattr(fd: _FD) -> _Attr: ...
+def tcsetattr(fd: _FD, when: int, attributes: _Attr) -> None: ...
+def tcsendbreak(fd: _FD, duration: int) -> None: ...
+def tcdrain(fd: _FD) -> None: ...
+def tcflush(fd: _FD, queue: int) -> None: ...
+def tcflow(fd: _FD, action: int) -> None: ...
diff --git a/typeshed/stdlib/2and3/threading.pyi b/typeshed/stdlib/2and3/threading.pyi
new file mode 100644
index 0000000..f81b708
--- /dev/null
+++ b/typeshed/stdlib/2and3/threading.pyi
@@ -0,0 +1,182 @@
+# Stubs for threading
+
+from typing import (
+ Any, Callable, Iterable, List, Mapping, Optional, Tuple, Type, Union,
+ TypeVar,
+)
+from types import FrameType, TracebackType
+import sys
+
+# TODO recursive type
+_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]]
+
+_PF = Callable[[FrameType, str, Any], None]
+_T = TypeVar('_T')
+
+
+def active_count() -> int: ...
+if sys.version_info < (3,):
+ def activeCount() -> int: ...
+
+def current_thread() -> Thread: ...
+if sys.version_info < (3,):
+ def currentThread() -> Thread: ...
+
+if sys.version_info >= (3,):
+ def get_ident() -> int: ...
+
+def enumerate() -> List[Thread]: ...
+
+if sys.version_info >= (3, 4):
+ def main_thread() -> Thread: ...
+
+def settrace(func: _TF) -> None: ...
+def setprofile(func: _PF) -> None: ...
+def stack_size(size: int = ...) -> int: ...
+
+if sys.version_info >= (3,):
+ TIMEOUT_MAX = ... # type: int
+
+if sys.version_info < (3,):
+ class ThreadError(Exception): ...
+
+
+# TODO: Change to a class with __getattr__ and __setattr__
+# once mypy supports universal __setattr__.
+# See https://github.com/python/mypy/issues/521
+local = ... # type: Any
+
+
+class Thread:
+ name = ... # type: str
+ ident = ... # type: Optional[int]
+ daemon = ... # type: bool
+ if sys.version_info >= (3,):
+ def __init__(self, group: None = ...,
+ target: Optional[Callable[..., None]] = ...,
+ name: Optional[str] = ...,
+ args: Tuple[Any, ...] = ...,
+ kwargs: Mapping[str, Any] = ...,
+ *, daemon: Optional[bool] = ...) -> None: ...
+ else:
+ def __init__(self, group: None = ...,
+ target: Optional[Callable[..., None]] = ...,
+ name: Optional[str] = ...,
+ args: Tuple[Any, ...] = ...,
+ kwargs: Mapping[str, Any] = ...) -> None: ...
+ def start(self) -> None: ...
+ def run(self) -> None: ...
+ def join(self, timeout: Optional[float] = ...) -> None: ...
+ def getName(self) -> str: ...
+ def setName(self, name: str) -> None: ...
+ def is_alive(self) -> bool: ...
+ if sys.version_info < (3,):
+ def isAlive(self) -> bool: ...
+ def isDaemon(self) -> bool: ...
+ def setDaemon(self, daemonic: bool) -> None: ...
+
+
+class Lock:
+ def __init__(self) -> None: ...
+ def __enter__(self) -> bool: ...
+ def __exit__(self, exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[TracebackType]) -> bool: ...
+ if sys.version_info >= (3,):
+ def acquire(self, blocking: bool = ..., timeout: int = ...) -> bool: ...
+ else:
+ def acquire(self, blocking: bool = ...) -> bool: ...
+ def release(self) -> None: ...
+
+
+class RLock:
+ def __init__(self) -> None: ...
+ def __enter__(self) -> bool: ...
+ def __exit__(self, exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[TracebackType]) -> bool: ...
+ if sys.version_info >= (3,):
+ def acquire(self, blocking: bool = ..., timeout: int = ...) -> bool: ...
+ else:
+ def acquire(self, blocking: bool = ...) -> bool: ...
+ def release(self) -> None: ...
+
+
+class Condition:
+ def __init__(self, lock: Union[Lock, RLock, None] = ...) -> None: ...
+ def __enter__(self) -> bool: ...
+ def __exit__(self, exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[TracebackType]) -> bool: ...
+ if sys.version_info >= (3,):
+ def acquire(self, blocking: bool = ..., timeout: int = ...) -> bool: ...
+ else:
+ def acquire(self, blocking: bool = ...) -> bool: ...
+ def release(self) -> None: ...
+ def wait(self, timeout: Optional[float] = ...) -> bool: ...
+ if sys.version_info >= (3,):
+ def wait_for(self, predicate: Callable[[], _T],
+ timeout: Optional[float]) -> _T: ...
+ def notify(self, n: int = ...) -> None: ...
+ def notify_all(self) -> None: ...
+
+
+class Semaphore:
+ def __init__(self, value: int = ...) -> None: ...
+ def __enter__(self) -> bool: ...
+ def __exit__(self, exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[TracebackType]) -> bool: ...
+ if sys.version_info >= (3,):
+ def acquire(self, blocking: bool = ..., timeout: int = ...) -> bool: ...
+ else:
+ def acquire(self, blocking: bool = ...) -> bool: ...
+ def release(self) -> None: ...
+
+class BoundedSemaphore:
+ def __init__(self, value: int = ...) -> None: ...
+ def __enter__(self) -> bool: ...
+ def __exit__(self, exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[TracebackType]) -> bool: ...
+ if sys.version_info >= (3,):
+ def acquire(self, blocking: bool = ..., timeout: int = ...) -> bool: ...
+ else:
+ def acquire(self, blocking: bool = ...) -> bool: ...
+ def release(self) -> None: ...
+
+
+class Event:
+ def __init__(self) -> None: ...
+ def is_set(self) -> bool: ...
+ if sys.version_info < (3,):
+ def isSet(self) -> bool: ...
+ def set(self) -> None: ...
+ def clear(self) -> None: ...
+ def wait(self, timeout: Optional[float] = ...) -> bool: ...
+
+
+class Timer(Thread):
+ if sys.version_info >= (3,):
+ def __init__(self, interval: float, function: Callable[..., None],
+ args: Optional[List[Any]] = ...,
+ kwargs: Optional[Mapping[str, Any]] = ...) -> None: ...
+ else:
+ def __init__(self, interval: float, function: Callable[..., None],
+ args: List[Any] = ...,
+ kwargs: Mapping[str, Any] = ...) -> None: ...
+ def cancel(self) -> None: ...
+
+
+if sys.version_info >= (3,):
+ class Barrier:
+ parties = ... # type: int
+ n_waiting = ... # type: int
+ broken = ... # type: bool
+ def __init__(self, parties: int, action: Optional[Callable[[], None]] = ...,
+ timeout: Optional[float] = ...) -> None: ...
+ def wait(self, timeout: Optional[float] = ...) -> int: ...
+ def reset(self) -> None: ...
+ def abort(self) -> None: ...
+
+ class BrokenBarrierError(RuntimeError): ...
diff --git a/typeshed/stdlib/2and3/traceback.pyi b/typeshed/stdlib/2and3/traceback.pyi
new file mode 100644
index 0000000..1bd8ff1
--- /dev/null
+++ b/typeshed/stdlib/2and3/traceback.pyi
@@ -0,0 +1,100 @@
+# Stubs for traceback
+
+from typing import Generator, IO, Iterator, Mapping, Optional, Tuple, Type
+from types import FrameType, TracebackType
+import sys
+
+_PT = Tuple[str, int, str, Optional[str]]
+
+
+def print_tb(tb: TracebackType, limit: Optional[int] = ...,
+ file: Optional[IO[str]] = ...) -> None: ...
+if sys.version_info >= (3,):
+ def print_exception(etype: Type[BaseException], value: BaseException,
+ tb: Optional[TracebackType], limit: Optional[int] = ...,
+ file: Optional[IO[str]] = ...,
+ chain: bool = ...) -> None: ...
+ def print_exc(limit: Optional[int] = ..., file: Optional[IO[str]] = ...,
+ chain: bool = ...) -> None: ...
+ def print_last(limit: Optional[int] = ..., file: Optional[IO[str]] = ...,
+ chain: bool = ...) -> None: ...
+else:
+ def print_exception(etype: Type[BaseException], value: BaseException,
+ tb: Optional[TracebackType], limit: Optional[int] = ...,
+ file: Optional[IO[str]] = ...) -> None: ...
+ def print_exc(limit: Optional[int] = ...,
+ file: Optional[IO[str]] = ...) -> None: ...
+ def print_last(limit: Optional[int] = ...,
+ file: Optional[IO[str]] = ...) -> None: ...
+def print_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...,
+ file: Optional[IO[str]] = ...) -> None: ...
+def extract_tb(tb: TracebackType, limit: Optional[int] = ...) -> List[_PT]: ...
+def extract_stack(f: Optional[FrameType] = ...,
+ limit: Optional[int] = ...) -> List[_PT]: ...
+def format_list(extracted_list: List[_PT]) -> List[str]: ...
+def format_exception_only(etype: Type[BaseException],
+ value: BaseException) -> List[str]: ...
+if sys.version_info >= (3,):
+ def format_exception(etype: Type[BaseException], value: BaseException,
+ tb: TracebackType, limit: Optional[int] = ...,
+ chain: bool = ...) -> List[str]: ...
+ def format_exc(limit: Optional[int] = ..., chain: bool = ...) -> str: ...
+else:
+ def format_exception(etype: Type[BaseException], value: BaseException,
+ tb: TracebackType,
+ limit: Optional[int] = ...) -> List[str]: ...
+ def format_exc(limit: Optional[int] = ...) -> str: ...
+def format_tb(tb: TracebackType, limit: Optional[int] = ...) -> List[str]: ...
+def format_stack(f: Optional[FrameType] = ...,
+ limit: Optional[int] = ...) -> List[str]: ...
+if sys.version_info >= (3, 4):
+ def clear_frames(tb: TracebackType) -> None: ...
+if sys.version_info >= (3, 5):
+ def walk_stack(f: Optional[FrameType]) -> Iterator[Tuple[FrameType, int]]: ...
+ def walk_tb(tb: TracebackType) -> Iterator[Tuple[FrameType, int]]: ...
+if sys.version_info < (3,):
+ def tb_lineno(tb: TracebackType) -> int: ...
+
+
+if sys.version_info >= (3, 5):
+ class TracebackException:
+ __cause__ = ... # type:TracebackException
+ __context__ = ... # type:TracebackException
+ __suppress_context__ = ... # type: bool
+ stack = ... # type: StackSummary
+ exc_type = ... # type: Type[BaseException]
+ filename = ... # type: str
+ lineno = ... # type: int
+ text = ... # type: str
+ offset = ... # type: int
+ msg = ... # type: str
+ def __init__(self, exc_type: Type[BaseException],
+ exc_value: BaseException, exc_traceback: TracebackType,
+ *, limit: Optional[int] = ..., lookup_lines: bool = ...,
+ capture_locals: bool = ...) -> None: ...
+ @classmethod
+ def from_exception(cls, exc: BaseException,
+ *, limit: Optional[int] = ...,
+ lookup_lines: bool = ...,
+ capture_locals: bool = ...) -> TracebackException: ...
+ def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ...
+ def format_exception_only(self) -> Generator[str, None, None]: ...
+
+
+if sys.version_info >= (3, 5):
+ class StackSummary:
+ @classmethod
+ def extract(cls,
+ frame_gen: Generator[Tuple[FrameType, int], None, None],
+ *, limit: Optional[int] = ..., lookup_lines: bool = ...,
+ capture_locals: bool = ...) -> StackSummary: ...
+ @classmethod
+ def from_list(cls, a_list: List[_PT]) -> StackSummary: ...
+
+
+if sys.version_info >= (3, 5):
+ class FrameSummary:
+ def __init__(self, filename: str, lineno: int, name: str,
+ lookup_line: bool = ...,
+ locals: Optional[Mapping[str, str]] = ...,
+ line: Optional[int] = ...) -> None: ...
diff --git a/typeshed/stdlib/2and3/zipfile.pyi b/typeshed/stdlib/2and3/zipfile.pyi
new file mode 100644
index 0000000..455ca0d
--- /dev/null
+++ b/typeshed/stdlib/2and3/zipfile.pyi
@@ -0,0 +1,94 @@
+# Stubs for zipfile
+
+from typing import Callable, IO, Optional, Tuple, Type, Union
+from types import TracebackType
+import sys
+
+
+_SZI = Union[str, ZipInfo]
+_DT = Tuple[int, int, int, int, int, int]
+
+
+if sys.version_info >= (3,):
+ class BadZipFile(Exception): ...
+ BadZipfile = BadZipFile
+else:
+ class BadZipfile(Exception): ...
+
+class LargeZipFile(Exception): ...
+
+class ZipFile:
+ debug = ... # type: int
+ comment = ... # type: bytes
+ def __init__(self, file: Union[str, IO[bytes]], mode: str = ..., compression: int = ...,
+ allowZip64: bool = ...) -> None: ...
+ def __enter__(self) -> ZipFile: ...
+ def __exit__(self, exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[TracebackType]) -> bool: ...
+ def close(self) -> None: ...
+ def getinfo(self, name: str) -> None: ...
+ def infolist(self) -> List[ZipInfo]: ...
+ def namelist(self) -> List[str]: ...
+ def open(self, name: _SZI, mode: str = ...,
+ pwd: Optional[bytes] = ...) -> IO[bytes]: ...
+ def extract(self, member: _SZI, path: Optional[_SZI] = ...,
+ pwd: bytes = ...) -> str: ...
+ def extractall(self, path: Optional[str] = ...,
+ members: Optional[List[str]] = ...,
+ pwd: Optional[bytes] = ...) -> None: ...
+ def printdir(self) -> None: ...
+ def setpassword(self, pwd: bytes) -> None: ...
+ def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ...
+ def testzip(self) -> Optional[str]: ...
+ def write(self, filename: str, arcname: Optional[str] = ...,
+ compress_type: Optional[int] = ...) -> None: ...
+ if sys.version_info >= (3,):
+ def writestr(self, zinfo_or_arcname: _SZI, data: Union[bytes, str],
+ compress_type: Optional[int] = ...) -> None: ...
+ else:
+ def writestr(self,
+ zinfo_or_arcname: _SZI, bytes: bytes,
+ compress_type: Optional[int] = ...) -> None: ...
+
+class PyZipFile(ZipFile):
+ if sys.version_info >= (3,):
+ def __init__(self, file: Union[str, IO[bytes]], mode: str = ...,
+ compression: int = ..., allowZip64: bool = ...,
+ opimize: int = ...) -> None: ...
+ def writepy(self, pathname: str, basename: str = ...,
+ filterfunc: Optional[Callable[[str], bool]] = ...) -> None: ...
+ else:
+ def writepy(self,
+ pathname: str, basename: str = ...) -> None: ...
+
+class ZipInfo:
+ filename = ... # type: str
+ date_time = ... # type: _DT
+ compress_type = ... # type: int
+ comment = ... # type: bytes
+ extra = ... # type: bytes
+ create_system = ... # type: int
+ create_version = ... # type: int
+ extract_version = ... # type: int
+ reserved = ... # type: int
+ flag_bits = ... # type: int
+ volume = ... # type: int
+ internal_attr = ... # type: int
+ external_attr = ... # type: int
+ header_offset = ... # type: int
+ CRC = ... # type: int
+ compress_size = ... # type: int
+ file_size = ... # type: int
+ if sys.version_info < (3,):
+ def __init__(self, filename: Optional[str] = ...,
+ date_time: Optional[_DT] = ...) -> None: ...
+
+
+def is_zipfile(filename: Union[str, IO[bytes]]) -> bool: ...
+
+ZIP_STORED = ... # type: int
+ZIP_DEFLATED = ... # type: int
+if sys.version_info >= (3, 3):
+ ZIP_BZIP2 = ... # type: int
+ ZIP_LZMA = ... # type: int
diff --git a/typeshed/stdlib/2.7/zipimport.pyi b/typeshed/stdlib/2and3/zipimport.pyi
similarity index 54%
rename from typeshed/stdlib/2.7/zipimport.pyi
rename to typeshed/stdlib/2and3/zipimport.pyi
index b972a37..2408d10 100644
--- a/typeshed/stdlib/2.7/zipimport.pyi
+++ b/typeshed/stdlib/2and3/zipimport.pyi
@@ -1,25 +1,19 @@
"""Stub file for the 'zipimport' module."""
-from typing import Dict, Optional
+from typing import Optional
from types import CodeType, ModuleType
-class ZipImportError(ImportError):
- pass
-
-_zip_directory_cache = ... # type: Dict[str, dict]
+class ZipImportError(ImportError): ...
class zipimporter(object):
archive = ... # type: str
prefix = ... # type: str
- _files = ... # type: Dict[str, tuple]
- def __init__(self, path: str) -> None:
- raise ZipImportError
- def find_module(self, fullname: str, path: str = ...) -> Optional['zipimporter']: ...
+ def __init__(self, archivepath: str) -> None: ...
+ def find_module(self, fullname: str, path: str = ...) -> Optional[zipimporter]: ...
def get_code(self, fullname: str) -> CodeType: ...
- def get_data(self, fullname: str) -> str:
- raise IOError
+ def get_data(self, pathname: str) -> str: ...
def get_filename(self, fullname: str) -> str: ...
- def get_source(self, fullname: str) -> str: ...
+ def get_source(self, fullname: str) -> Optional[str]: ...
def is_package(self, fullname: str) -> bool: ...
def load_module(self, fullname: str) -> ModuleType: ...
diff --git a/typeshed/stdlib/3.4/_operator.pyi b/typeshed/stdlib/3.4/_operator.pyi
deleted file mode 100644
index bb5e94f..0000000
--- a/typeshed/stdlib/3.4/_operator.pyi
+++ /dev/null
@@ -1,108 +0,0 @@
-"""Stub file for the '_operator' module."""
-# This is an autogenerated file. It serves as a starting point
-# for a more precise manual annotation of this module.
-# Feel free to edit the source below, but remove this header when you do.
-
-from typing import Any, List, Tuple, Dict, Generic
-
-def _compare_digest(a, b) -> bool:
- raise BufferError()
- raise TypeError()
-
-def abs(*args, **kwargs) -> Any: ...
-
-def add(*args, **kwargs) -> Any: ...
-
-def and_(*args, **kwargs) -> Any: ...
-
-def concat(*args, **kwargs) -> Any: ...
-
-def contains(*args, **kwargs) -> bool: ...
-
-def countOf(*args, **kwargs) -> int: ...
-
-def delitem(*args, **kwargs) -> None: ...
-
-def eq(*args, **kwargs) -> Any: ...
-
-def floordiv(*args, **kwargs) -> Any: ...
-
-def ge(*args, **kwargs) -> Any: ...
-
-def getitem(*args, **kwargs) -> Any: ...
-
-def gt(*args, **kwargs) -> Any: ...
-
-def iadd(*args, **kwargs) -> Any: ...
-
-def iand(*args, **kwargs) -> Any: ...
-
-def iconcat(*args, **kwargs) -> Any: ...
-
-def ifloordiv(*args, **kwargs) -> Any: ...
-
-def ilshift(*args, **kwargs) -> Any: ...
-
-def imod(*args, **kwargs) -> Any: ...
-
-def imul(*args, **kwargs) -> Any: ...
-
-def index(*args, **kwargs) -> Any: ...
-
-def indexOf(*args, **kwargs) -> int: ...
-
-def inv(*args, **kwargs) -> Any: ...
-
-def invert(*args, **kwargs) -> Any: ...
-
-def ior(*args, **kwargs) -> Any: ...
-
-def ipow(*args, **kwargs) -> Any: ...
-
-def irshift(*args, **kwargs) -> Any: ...
-
-def is_(*args, **kwargs) -> bool: ...
-
-def is_not(*args, **kwargs) -> bool: ...
-
-def isub(*args, **kwargs) -> Any: ...
-
-def itruediv(*args, **kwargs) -> Any: ...
-
-def ixor(*args, **kwargs) -> Any: ...
-
-def le(*args, **kwargs) -> Any: ...
-
-def length_hint(a, *args, **kwargs) -> int: ...
-
-def lshift(*args, **kwargs) -> Any: ...
-
-def lt(*args, **kwargs) -> Any: ...
-
-def mod(*args, **kwargs) -> Any: ...
-
-def mul(*args, **kwargs) -> Any: ...
-
-def ne(*args, **kwargs) -> Any: ...
-
-def neg(*args, **kwargs) -> Any: ...
-
-def not_(*args, **kwargs) -> bool: ...
-
-def or_(*args, **kwargs) -> Any: ...
-
-def pos(*args, **kwargs) -> Any: ...
-
-def pow(*args, **kwargs) -> Any: ...
-
-def rshift(*args, **kwargs) -> Any: ...
-
-def setitem(*args, **kwargs) -> None: ...
-
-def sub(*args, **kwargs) -> Any: ...
-
-def truediv(*args, **kwargs) -> Any: ...
-
-def truth(*args, **kwargs) -> bool: ...
-
-def xor(*args, **kwargs) -> Any: ...
diff --git a/typeshed/stdlib/3.4/asyncio/__init__.pyi b/typeshed/stdlib/3.4/asyncio/__init__.pyi
index 171ab01..b10a25e 100644
--- a/typeshed/stdlib/3.4/asyncio/__init__.pyi
+++ b/typeshed/stdlib/3.4/asyncio/__init__.pyi
@@ -1,4 +1,8 @@
"""The asyncio package, tracking PEP 3156."""
+
+import sys
+from typing import Type
+
from asyncio.coroutines import (
coroutine as coroutine,
iscoroutinefunction as iscoroutinefunction,
@@ -48,7 +52,13 @@ from asyncio.events import (
AbstractEventLoop as AbstractEventLoop,
AbstractServer as AbstractServer,
Handle as Handle,
+ 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,
+ set_event_loop as set_event_loop,
+ new_event_loop as new_event_loop,
+ get_child_watcher as get_child_watcher,
+ set_child_watcher as set_child_watcher,
)
from asyncio.queues import (
Queue as Queue,
@@ -58,5 +68,22 @@ from asyncio.queues import (
QueueFull as QueueFull,
QueueEmpty as QueueEmpty,
)
+from asyncio.locks import (
+ Lock as Lock,
+ Event as Event,
+ Condition as Condition,
+ Semaphore as Semaphore,
+ BoundedSemaphore as BoundedSemaphore,
+)
+
+# TODO: It should be possible to instantiate these classes, but mypy
+# currently disallows this.
+# See https://github.com/python/mypy/issues/1843
+SelectorEventLoop = ... # type: Type[AbstractEventLoop]
+if sys.platform == 'win32':
+ ProactorEventLoop = ... # type: Type[AbstractEventLoop]
+DefaultEventLoopPolicy = ... # type: Type[AbstractEventLoopPolicy]
+
+# TODO: AbstractChildWatcher (UNIX only)
__all__ = ... # type: str
diff --git a/typeshed/stdlib/3.4/asyncio/coroutines.pyi b/typeshed/stdlib/3.4/asyncio/coroutines.pyi
index 455e36d..668c83b 100644
--- a/typeshed/stdlib/3.4/asyncio/coroutines.pyi
+++ b/typeshed/stdlib/3.4/asyncio/coroutines.pyi
@@ -1,9 +1,9 @@
-from typing import Callable, Any, TypeVar
+from typing import Any, Callable, Generator, TypeVar
__all__ = ... # type: str
-_T = TypeVar('_T')
+_F = TypeVar('_F', bound=Callable[..., Any])
-def coroutine(func: _T) -> _T: ...
+def coroutine(func: _F) -> _F: ...
def iscoroutinefunction(func: Callable[..., Any]) -> bool: ...
def iscoroutine(obj: Any) -> bool: ...
diff --git a/typeshed/stdlib/3.4/asyncio/events.pyi b/typeshed/stdlib/3.4/asyncio/events.pyi
index 6b4f11a..262758f 100644
--- a/typeshed/stdlib/3.4/asyncio/events.pyi
+++ b/typeshed/stdlib/3.4/asyncio/events.pyi
@@ -1,4 +1,4 @@
-from typing import Any, Awaitable, TypeVar, List, Callable, Tuple, Union, Dict, Generator
+from typing import Any, Awaitable, TypeVar, List, Callable, Tuple, Union, Dict, Generator, overload
from abc import ABCMeta, abstractmethod
from asyncio.futures import Future
from asyncio.coroutines import coroutine
@@ -25,13 +25,20 @@ class Handle:
class AbstractServer:
def close(self) -> None: ...
@coroutine
- def wait_closed(self) -> None: ...
+ def wait_closed(self) -> Generator[Any, Any, None]: ...
class AbstractEventLoop(metaclass=ABCMeta):
@abstractmethod
def run_forever(self) -> None: ...
+
+ # Can't use a union, see mypy issue #1873.
+ @overload
+ @abstractmethod
+ def run_until_complete(self, future: Generator[Any, Any, _T]) -> _T: ...
+ @overload
@abstractmethod
- def run_until_complete(self, future: Union[Awaitable[_T], Future[_T], Generator[Any, Any, _T]]) -> _T: ...
+ def run_until_complete(self, future: Awaitable[_T]) -> _T: ...
+
@abstractmethod
def stop(self) -> None: ...
@abstractmethod
@@ -58,9 +65,9 @@ class AbstractEventLoop(metaclass=ABCMeta):
# Network I/O methods returning Futures.
@abstractmethod
def getaddrinfo(self, host: str, port: int, *,
- family: int = ..., type: int = ..., proto: int = ..., flags: int = ...) -> List[Tuple[int, int, int, str, tuple]]: ...
+ family: int = ..., type: int = ..., proto: int = ..., flags: int = ...) -> Future[List[Tuple[int, int, int, str, tuple]]]: ...
@abstractmethod
- def getnameinfo(self, sockaddr: tuple, flags: int = ...) -> Tuple[str, int]: ...
+ def getnameinfo(self, sockaddr: tuple, flags: int = ...) -> Future[Tuple[str, int]]: ...
@abstractmethod
def create_connection(self, protocol_factory: Any, host: str = ..., port: int = ..., *,
ssl: Any = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: Any = ...,
@@ -152,18 +159,25 @@ class AbstractEventLoopPolicy(metaclass=ABCMeta):
@abstractmethod
def set_event_loop(self, loop: AbstractEventLoop): ...
@abstractmethod
- def new_event_loop(self) -> Any: ... # return selector_events.BaseSelectorEventLoop
+ def new_event_loop(self) -> AbstractEventLoop: ...
# Child processes handling (Unix only).
@abstractmethod
- def get_child_watcher(self) -> Any: ... # return unix_events.AbstractChildWatcher
+ def get_child_watcher(self) -> Any: ... # TODO: unix_events.AbstractChildWatcher
@abstractmethod
- def set_child_watcher(self, watcher: Any) -> None: ... # gen unix_events.AbstractChildWatcher
+ def set_child_watcher(self, watcher: Any) -> None: ... # TODO: unix_events.AbstractChildWatcher
class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
def __init__(self) -> None: ...
def get_event_loop(self) -> AbstractEventLoop: ...
def set_event_loop(self, loop: AbstractEventLoop): ...
- def new_event_loop(self) -> Any: ... # Same return than AbstractEventLoop
+ def new_event_loop(self) -> AbstractEventLoop: ...
+def get_event_loop_policy() -> AbstractEventLoopPolicy: ...
+def set_event_loop_policy(policy: AbstractEventLoopPolicy) -> None: ...
def get_event_loop() -> AbstractEventLoop: ...
+def set_event_loop(loop: AbstractEventLoop) -> None: ...
+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
diff --git a/typeshed/stdlib/3.4/asyncio/futures.pyi b/typeshed/stdlib/3.4/asyncio/futures.pyi
index a3de8a8..eab1d4c 100644
--- a/typeshed/stdlib/3.4/asyncio/futures.pyi
+++ b/typeshed/stdlib/3.4/asyncio/futures.pyi
@@ -1,4 +1,4 @@
-from typing import Any, Union, Callable, TypeVar, List, Generic, Iterable, Generator
+from typing import Any, Union, Callable, TypeVar, List, Generic, Iterable, Generator, Awaitable
from .events import AbstractEventLoop
__all__ = ... # type: str
@@ -14,7 +14,7 @@ class _TracebackLogger:
def clear(self) -> None: ...
def __del__(self) -> None: ...
-class Future(Iterable[_T], Generic[_T]):
+class Future(Iterable[_T], Awaitable[_T], Generic[_T]):
_state = ... # type: str
_exception = ... # type: BaseException
_blocking = False
@@ -35,3 +35,4 @@ class Future(Iterable[_T], Generic[_T]):
def set_exception(self, exception: Union[type, BaseException]) -> None: ...
def _copy_state(self, other: Any) -> None: ...
def __iter__(self) -> Generator[Any, None, _T]: ...
+ def __await__(self) -> Generator[Any, None, _T]: ...
diff --git a/typeshed/stdlib/3.4/asyncio/locks.pyi b/typeshed/stdlib/3.4/asyncio/locks.pyi
new file mode 100644
index 0000000..4d665ae
--- /dev/null
+++ b/typeshed/stdlib/3.4/asyncio/locks.pyi
@@ -0,0 +1,59 @@
+from typing import Any, Callable, Generator, Iterable, Iterator, TypeVar, Union
+
+from .coroutines import coroutine
+from .events import AbstractEventLoop
+from .futures import Future
+
+T = TypeVar('T')
+
+__all__ = ... # type: str
+
+class _ContextManager:
+ def __init__(self, lock: Union[Lock, Semaphore]) -> None: ...
+ def __enter__(self) -> object: ...
+ def __exit__(self, *args: Any) -> None: ...
+
+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): ...
+
+class Lock(_ContextManagerMixin):
+ def __init__(self, *, loop: AbstractEventLoop = None) -> None: ...
+ def locked(self) -> bool: ...
+ @coroutine
+ def acquire(self) -> Future[bool]: ...
+ def release(self) -> None: ...
+
+class Event:
+ def __init__(self, *, loop: AbstractEventLoop = None) -> None: ...
+ def is_set(self) -> bool: ...
+ def set(self) -> None: ...
+ def clear(self) -> None: ...
+
+ def wait(self) -> bool: ...
+
+class Condition(_ContextManagerMixin):
+ def __init__(self, lock: Lock = None, *, loop: AbstractEventLoop = None) -> None: ...
+ def locked(self) -> bool: ...
+ @coroutine
+ def acquire(self) -> Future[bool]: ...
+ def release(self) -> None: ...
+ @coroutine
+ def wait(self) -> Future[bool]: ...
+ @coroutine
+ def wait_for(self, predicate: Callable[[], T]) -> Future[T]: ...
+ def notify(self, n: int = 1) -> None: ...
+ def notify_all(self) -> None: ...
+
+class Semaphore(_ContextManagerMixin):
+ def __init__(self, value: int = 1, *, loop: AbstractEventLoop = None) -> None: ...
+ def locked(self) -> bool: ...
+ @coroutine
+ def acquire(self) -> Future[bool]: ...
+ def release(self) -> None: ...
+
+class BoundedSemaphore(Semaphore):
+ def __init__(self, value=1, *, loop: AbstractEventLoop = None) -> None: ...
diff --git a/typeshed/stdlib/3.4/asyncio/protocols.pyi b/typeshed/stdlib/3.4/asyncio/protocols.pyi
index 8cae805..9ad7e4e 100644
--- a/typeshed/stdlib/3.4/asyncio/protocols.pyi
+++ b/typeshed/stdlib/3.4/asyncio/protocols.pyi
@@ -11,7 +11,7 @@ class BaseProtocol:
def resume_writing(self) -> None: ...
class Protocol(BaseProtocol):
- def data_received(self, data: AnyStr) -> None: ...
+ def data_received(self, data: bytes) -> None: ...
def eof_received(self) -> bool: ...
class DatagramProtocol(BaseProtocol):
diff --git a/typeshed/stdlib/3.4/asyncio/streams.pyi b/typeshed/stdlib/3.4/asyncio/streams.pyi
index a30a950..00fe38e 100644
--- a/typeshed/stdlib/3.4/asyncio/streams.pyi
+++ b/typeshed/stdlib/3.4/asyncio/streams.pyi
@@ -1,4 +1,4 @@
-from typing import Iterable, Tuple, Callable, Any, AnyStr
+from typing import Any, Callable, Generator, Iterable, Tuple
ClientConnectedCallback = Callable[[Tuple[StreamReader, StreamWriter]], None]
import socket
@@ -23,7 +23,7 @@ def open_connection(
*,
loop: events.AbstractEventLoop = ...,
limit: int = ...,
- **kwds: Any) -> Tuple[StreamReader, StreamWriter]: ...
+ **kwds: Any) -> Generator[Any, None, Tuple[StreamReader, StreamWriter]]: ...
@coroutines.coroutine
def start_server(
@@ -33,7 +33,7 @@ def start_server(
*,
loop: events.AbstractEventLoop = ...,
limit: int = ...,
- **kwds: Any) -> events.AbstractServer: ...
+ **kwds: Any) -> Generator[Any, None, events.AbstractServer]: ...
if hasattr(socket, 'AF_UNIX'):
@coroutines.coroutine
@@ -42,7 +42,7 @@ if hasattr(socket, 'AF_UNIX'):
*,
loop: events.AbstractEventLoop = ...,
limit: int = ...,
- **kwds: Any): ...
+ **kwds: Any)-> Generator[Any, None, Tuple[StreamReader, StreamWriter]]: ...
@coroutines.coroutine
def start_unix_server(
@@ -51,7 +51,7 @@ if hasattr(socket, 'AF_UNIX'):
*,
loop: int = ...,
limit: int = ...,
- **kwds: Any) -> events.AbstractServer: ...
+ **kwds: Any) -> Generator[Any, None, events.AbstractServer]: ...
class FlowControlMixin(protocols.Protocol): ...
@@ -62,7 +62,7 @@ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
loop: events.AbstractEventLoop = ...) -> None: ...
def connection_made(self, transport: transports.BaseTransport) -> None: ...
def connection_lost(self, exc: Exception) -> None: ...
- def data_received(self, data: AnyStr) -> None: ...
+ def data_received(self, data: bytes) -> None: ...
def eof_received(self) -> bool: ...
class StreamWriter:
@@ -73,12 +73,12 @@ class StreamWriter:
loop: events.AbstractEventLoop) -> None: ...
@property
def transport(self) -> transports.BaseTransport: ...
- def write(self, data: AnyStr) -> None: ...
- def writelines(self, data: Iterable[str]) -> None: ...
+ def write(self, data: bytes) -> None: ...
+ def writelines(self, data: Iterable[bytes]) -> None: ...
def write_eof(self) -> None: ...
def can_write_eof(self) -> bool: ...
def close(self) -> None: ...
- def get_extra_info(self, name: Any, default: Any = ...) -> Any: ...
+ def get_extra_info(self, name: str, default: Any = ...) -> Any: ...
def drain(self) -> None: ...
class StreamReader:
@@ -90,12 +90,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: AnyStr): ...
+ def feed_data(self, data: bytes): ...
@coroutines.coroutine
- def readline(self) -> str: ...
+ def readline(self) -> Generator[Any, None, bytes]: ...
@coroutines.coroutine
- def readuntil(self, separator=b'\n') -> str: ...
+ def readuntil(self, separator=b'\n') -> Generator[Any, None, bytes]: ...
@coroutines.coroutine
- def read(self, n=-1) -> str: ...
+ def read(self, n=-1) -> Generator[Any, None, bytes]: ...
@coroutines.coroutine
- def readexactly(self, n) -> str: ...
+ def readexactly(self, n) -> Generator[Any, None, bytes]: ...
diff --git a/typeshed/stdlib/3.4/asyncio/tasks.pyi b/typeshed/stdlib/3.4/asyncio/tasks.pyi
index 66abd00..69a4ac3 100644
--- a/typeshed/stdlib/3.4/asyncio/tasks.pyi
+++ b/typeshed/stdlib/3.4/asyncio/tasks.pyi
@@ -1,4 +1,4 @@
-from typing import Any, Iterable, TypeVar, Set, Dict, List, TextIO, Union, Tuple, Generic, Callable, Generator
+from typing import Any, TypeVar, Set, Dict, List, TextIO, Union, Tuple, Generic, Callable, Generator, Iterable, Awaitable, overload
__all__ = ... # type: str
@@ -22,7 +22,13 @@ class Task(Future[_T], Generic[_T]):
def current_task(cls, loop: AbstractEventLoop = ...) -> Task: ...
@classmethod
def all_tasks(cls, loop: AbstractEventLoop = ...) -> Set[Task]: ...
- def __init__(self, coro: Union[Future[_T], Generator[Any, None, _T]], *, loop: AbstractEventLoop = ...) -> None: ...
+
+ # Can't use a union, see mypy issue #1873.
+ @overload
+ def __init__(self, coro: Generator[Any, None, _T], *, loop: AbstractEventLoop = ...) -> None: ...
+ @overload
+ def __init__(self, coro: Awaitable[_T], *, loop: AbstractEventLoop = ...) -> None: ...
+
def __repr__(self) -> str: ...
def get_stack(self, *, limit: int = ...) -> List[Any]: ... # return List[stackframe]
def print_stack(self, *, limit: int = ..., file: TextIO = ...) -> None: ...
diff --git a/typeshed/stdlib/3.4/pathlib.pyi b/typeshed/stdlib/3.4/pathlib.pyi
index dc0aeb3..b66e628 100644
--- a/typeshed/stdlib/3.4/pathlib.pyi
+++ b/typeshed/stdlib/3.4/pathlib.pyi
@@ -1,164 +1,72 @@
# Stubs for pathlib (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-from typing import Any
-from collections import Sequence
-
-class _Flavour:
- join = ... # type: Any
- def __init__(self) -> None: ...
- def parse_parts(self, parts): ...
- def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2): ...
-
-class _WindowsFlavour(_Flavour):
- sep = ... # type: Any
- altsep = ... # type: Any
- has_drv = ... # type: Any
- pathmod = ... # type: Any
- is_supported = ... # type: Any
- drive_letters = ... # type: Any
- ext_namespace_prefix = ... # type: Any
- reserved_names = ... # type: Any
- def splitroot(self, part, sep=...): ...
- def casefold(self, s): ...
- def casefold_parts(self, parts): ...
- def resolve(self, path): ...
- def is_reserved(self, parts): ...
- def make_uri(self, path): ...
-
-class _PosixFlavour(_Flavour):
- sep = ... # type: Any
- altsep = ... # type: Any
- has_drv = ... # type: Any
- pathmod = ... # type: Any
- is_supported = ... # type: Any
- def splitroot(self, part, sep=...): ...
- def casefold(self, s): ...
- def casefold_parts(self, parts): ...
- def resolve(self, path): ...
- def is_reserved(self, parts): ...
- def make_uri(self, path): ...
-
-class _Accessor: ...
-
-class _NormalAccessor(_Accessor):
- stat = ... # type: Any
- lstat = ... # type: Any
- open = ... # type: Any
- listdir = ... # type: Any
- chmod = ... # type: Any
- lchmod = ... # type: Any
- mkdir = ... # type: Any
- unlink = ... # type: Any
- rmdir = ... # type: Any
- rename = ... # type: Any
- replace = ... # type: Any
- def symlink(a, b, target_is_directory): ...
- utime = ... # type: Any
- def readlink(self, path): ...
-
-class _Selector:
- child_parts = ... # type: Any
- successor = ... # type: Any
- def __init__(self, child_parts) -> None: ...
- def select_from(self, parent_path): ...
-
-class _TerminatingSelector: ...
-
-class _PreciseSelector(_Selector):
- name = ... # type: Any
- def __init__(self, name, child_parts) -> None: ...
-
-class _WildcardSelector(_Selector):
- pat = ... # type: Any
- def __init__(self, pat, child_parts) -> None: ...
-
-class _RecursiveWildcardSelector(_Selector):
- def __init__(self, pat, child_parts) -> None: ...
-
-class _PathParents(Sequence):
- def __init__(self, path) -> None: ...
- def __len__(self): ...
- def __getitem__(self, idx): ...
+from typing import Any, Generator, IO, Optional, Sequence, Tuple, Union
+import os
class PurePath:
- def __init__(self, *args) -> None: ...
- def __reduce__(self): ...
- def as_posix(self): ...
- def __bytes__(self): ...
- def as_uri(self): ...
- def __eq__(self, other): ...
- def __ne__(self, other): ...
- def __hash__(self): ...
- def __lt__(self, other): ...
- def __le__(self, other): ...
- def __gt__(self, other): ...
- def __ge__(self, other): ...
- drive = ... # type: Any
- root = ... # type: Any
- @property
- def anchor(self): ...
- @property
- def name(self): ...
- @property
- def suffix(self): ...
- @property
- def suffixes(self): ...
- @property
- def stem(self): ...
- def with_name(self, name): ...
- def with_suffix(self, suffix): ...
- def relative_to(self, *other): ...
- @property
- def parts(self): ...
- def joinpath(self, *args): ...
- def __truediv__(self, key): ...
- def __rtruediv__(self, key): ...
- @property
- def parent(self): ...
- @property
- def parents(self): ...
- def is_absolute(self): ...
- def is_reserved(self): ...
- def match(self, path_pattern): ...
+ parts = ... # type: Tuple[str, ...]
+ drive = ... # type: str
+ root = ... # type: str
+ anchor = ... # type: str
+ parents = ... # type: Sequence[PurePath]
+ parent = ... # type: PurePath
+ name = ... # type: str
+ suffix = ... # type: str
+ suffixes = ... # type: List[str]
+ stem = ... # type: str
+ def __init__(self, *pathsegments: str) -> None: ...
+ def __hash__(self) -> int: ...
+ def __lt__(self, other: PurePath) -> bool: ...
+ def __le__(self, other: PurePath) -> bool: ...
+ def __gt__(self, other: PurePath) -> bool: ...
+ def __ge__(self, other: PurePath) -> bool: ...
+ def __truediv__(self, key: Union[str, PurePath]) -> PurePath: ...
+ def __bytes__(self) -> bytes: ...
+ def as_posix(self) -> str: ...
+ def as_uri(self) -> str: ...
+ def is_absolute(self) -> bool: ...
+ def is_reserved(self) -> bool: ...
+ def match(self, path_pattern: str) -> bool: ...
+ def relative_to(self, *other: str) -> PurePath: ...
+ def with_name(self, name: str) -> PurePath: ...
+ def with_suffix(self, suffix: str) -> PurePath: ...
+ def joinpath(self, *other: Union[str, PurePath]) -> PurePath: ...
class PurePosixPath(PurePath): ...
class PureWindowsPath(PurePath): ...
class Path(PurePath):
- def __init__(self, *args, **kwargs) -> None: ...
- def __enter__(self): ...
- def __exit__(self, t, v, tb): ...
@classmethod
- def cwd(cls): ...
- def iterdir(self): ...
- def glob(self, pattern): ...
- def rglob(self, pattern): ...
- def absolute(self): ...
- def resolve(self): ...
- def stat(self): ...
- def owner(self): ...
- def group(self): ...
- def open(self, mode=..., buffering=..., encoding=..., errors=..., newline=...): ...
- def touch(self, mode=..., exist_ok=...): ...
- def mkdir(self, mode=..., parents=...): ...
- def chmod(self, mode): ...
- def lchmod(self, mode): ...
- def unlink(self): ...
- def rmdir(self): ...
- def lstat(self): ...
- def rename(self, target): ...
- def replace(self, target): ...
- def symlink_to(self, target, target_is_directory=...): ...
- def exists(self): ...
- def is_dir(self): ...
- def is_file(self): ...
- def is_symlink(self): ...
- def is_block_device(self): ...
- def is_char_device(self): ...
- def is_fifo(self): ...
- def is_socket(self): ...
+ def cwd(cls) -> Path: ...
+ def stat(self) -> os.stat_result: ...
+ def chmod(self, mode: int) -> None: ...
+ def exists(self) -> bool: ...
+ def glob(self, pattern: str) -> Generator[Path, None, None]: ...
+ def group(self) -> str: ...
+ def is_dir(self) -> bool: ...
+ def is_file(self) -> bool: ...
+ def is_symlink(self) -> bool: ...
+ def is_socket(self) -> bool: ...
+ def is_fifo(self) -> bool: ...
+ def is_block_device(self) -> bool: ...
+ def is_char_device(self) -> bool: ...
+ def iterdir(self) -> Generator[Path, None, None]: ...
+ def lchmod(self, mode: int) -> None: ...
+ def lstat(self) -> os.stat_result: ...
+ def mkdir(self, mode: int = ..., parents: bool = ...) -> None: ...
+ def open(self, mode: str = ..., buffering: int = ...,
+ encoding: Optional[str] = ..., errors: Optional[str] = ...,
+ newline: Optional[str] = ...) -> IO[Any]: ...
+ def owner(self) -> str: ...
+ def rename(self, target: Union[str, Path]) -> None: ...
+ def replace(self, target: Union[str, Path]) -> None: ...
+ def resolve(self) -> Path: ...
+ def rglob(self, pattern: str) -> Generator[Path, None, None]: ...
+ def rmdir(self) -> None: ...
+ def symlink_to(self, target: Union[str, Path],
+ target_is_directory: bool = ...) -> None: ...
+ def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ...
+ def unlink(self) -> None: ...
class PosixPath(Path, PurePosixPath): ...
class WindowsPath(Path, PureWindowsPath): ...
diff --git a/typeshed/stdlib/3.4/selectors.pyi b/typeshed/stdlib/3.4/selectors.pyi
new file mode 100644
index 0000000..832212b
--- /dev/null
+++ b/typeshed/stdlib/3.4/selectors.pyi
@@ -0,0 +1,90 @@
+# Stubs for selector
+# See https://docs.python.org/3/library/selectors.html
+
+from typing import Any, List, NamedTuple, Mapping, Tuple, Optional, Union
+from abc import ABCMeta, abstractmethod
+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
+
+
+EVENT_READ = ... # type: EventMask
+EVENT_WRITE = ... # type: EventMask
+
+
+SelectorKey = NamedTuple('SelectorKey', [
+ ('fileobj', FileObject),
+ ('fd', FileDescriptor),
+ ('events', EventMask),
+ ('data', Any)
+])
+
+
+class BaseSelector(metaclass=ABCMeta):
+ @abstractmethod
+ def register(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
+
+ @abstractmethod
+ def unregister(self, fileobj: FileObject) -> SelectorKey: ...
+
+ def modify(self, fileobj: FileObject, events: EventMask, data: Any = None) -> SelectorKey: ...
+
+ @abstractmethod
+ def select(self, timeout: Optional[int] = None) -> List[Tuple[SelectorKey, EventMask]]: ...
+
+ def close(self) -> None: ...
+
+ def get_key(self, fileobj: FileObject) -> SelectorKey: ...
+
+ @abstractmethod
+ 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]: ...
+
+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]: ...
+
+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]: ...
+
+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]: ...
+
+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]: ...
+
+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]: ...
diff --git a/typeshed/stdlib/3.5/pathlib.pyi b/typeshed/stdlib/3.5/pathlib.pyi
new file mode 100644
index 0000000..7b4fdb9
--- /dev/null
+++ b/typeshed/stdlib/3.5/pathlib.pyi
@@ -0,0 +1,83 @@
+# Stubs for pathlib (Python 3.4)
+
+from typing import Any, Generator, IO, Optional, Sequence, Tuple, Union
+import os
+
+class PurePath:
+ parts = ... # type: Tuple[str, ...]
+ drive = ... # type: str
+ root = ... # type: str
+ anchor = ... # type: str
+ parents = ... # type: Sequence[PurePath]
+ parent = ... # type: PurePath
+ name = ... # type: str
+ suffix = ... # type: str
+ suffixes = ... # type: List[str]
+ stem = ... # type: str
+ def __init__(self, *pathsegments: str) -> None: ...
+ def __hash__(self) -> int: ...
+ def __lt__(self, other: PurePath) -> bool: ...
+ def __le__(self, other: PurePath) -> bool: ...
+ def __gt__(self, other: PurePath) -> bool: ...
+ def __ge__(self, other: PurePath) -> bool: ...
+ def __truediv__(self, key: Union[str, PurePath]) -> PurePath: ...
+ def __bytes__(self) -> bytes: ...
+ def as_posix(self) -> str: ...
+ def as_uri(self) -> str: ...
+ def is_absolute(self) -> bool: ...
+ def is_reserved(self) -> bool: ...
+ def match(self, path_pattern: str) -> bool: ...
+ def relative_to(self, *other: str) -> PurePath: ...
+ def with_name(self, name: str) -> PurePath: ...
+ def with_suffix(self, suffix: str) -> PurePath: ...
+ def joinpath(self, *other: Union[str, PurePath]) -> PurePath: ...
+
+class PurePosixPath(PurePath): ...
+class PureWindowsPath(PurePath): ...
+
+class Path(PurePath):
+ @classmethod
+ def cwd(cls) -> Path: ...
+ @classmethod
+ def home(cls) -> Path: ...
+ def stat(self) -> os.stat_result: ...
+ def chmod(self, mode: int) -> None: ...
+ def exists(self) -> bool: ...
+ def expanduser(self) -> Path: ...
+ def glob(self, pattern: str) -> Generator[Path, None, None]: ...
+ def group(self) -> str: ...
+ def is_dir(self) -> bool: ...
+ def is_file(self) -> bool: ...
+ def is_symlink(self) -> bool: ...
+ def is_socket(self) -> bool: ...
+ def is_fifo(self) -> bool: ...
+ def is_block_device(self) -> bool: ...
+ def is_char_device(self) -> bool: ...
+ def iterdir(self) -> Generator[Path, None, None]: ...
+ def lchmod(self, mode: int) -> None: ...
+ def lstat(self) -> os.stat_result: ...
+ def mkdir(self, mode: int = ..., parents: bool = ...,
+ exist_ok: bool = ...) -> None: ...
+ def open(self, mode: str = ..., buffering: int = ...,
+ encoding: Optional[str] = ..., errors: Optional[str] = ...,
+ newline: Optional[str] = ...) -> IO[Any]: ...
+ def owner(self) -> str: ...
+ def read_bytes(self) -> bytes: ...
+ def read_text(self, encoding: Optional[str] = ...,
+ errors: Optional[str] = ...) -> bytes: ...
+ def rename(self, target: Union[str, Path]) -> None: ...
+ def replace(self, target: Union[str, Path]) -> None: ...
+ def resolve(self) -> Path: ...
+ def rglob(self, pattern: str) -> Generator[Path, None, None]: ...
+ def rmdir(self) -> None: ...
+ def samefile(self, other_path: Union[str, Path]) -> bool: ...
+ def symlink_to(self, target: Union[str, Path],
+ target_is_directory: bool = ...) -> None: ...
+ def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ...
+ def unlink(self) -> None: ...
+ def write_bytes(self, data: bytes) -> int: ...
+ def write_text(self, data: str, encoding: Optional[str] = ...,
+ errors: Optional[str] = ...) -> int: ...
+
+class PosixPath(Path, PurePosixPath): ...
+class WindowsPath(Path, PureWindowsPath): ...
diff --git a/typeshed/stdlib/3/bisect.pyi b/typeshed/stdlib/3/bisect.pyi
deleted file mode 100644
index 954cd70..0000000
--- a/typeshed/stdlib/3/bisect.pyi
+++ /dev/null
@@ -1,12 +0,0 @@
-from typing import Sequence, TypeVar
-
-_T = TypeVar('_T')
-
-def insort_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...): pass
-def insort_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...): pass
-
-def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...): pass
-def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...): pass
-
-insort = insort_right
-bisect = bisect_right
diff --git a/typeshed/stdlib/3/builtins.pyi b/typeshed/stdlib/3/builtins.pyi
index 291296a..ae113be 100644
--- a/typeshed/stdlib/3/builtins.pyi
+++ b/typeshed/stdlib/3/builtins.pyi
@@ -7,6 +7,8 @@ from typing import (
SupportsAbs, SupportsRound, IO, Union, ItemsView, KeysView, ValuesView, ByteString
)
from abc import abstractmethod, ABCMeta
+from types import TracebackType
+import sys
# Note that names imported above are not automatically made visible via the
# implicit builtins import.
@@ -304,7 +306,7 @@ class bytes(ByteString):
def strip(self, chars: bytes = None) -> bytes: ...
def swapcase(self) -> bytes: ...
def title(self) -> bytes: ...
- def translate(self, table: bytes) -> bytes: ...
+ def translate(self, table: bytes, delete: bytes = None) -> bytes: ...
def upper(self) -> bytes: ...
def zfill(self, width: int) -> bytes: ...
@classmethod
@@ -377,7 +379,7 @@ class bytearray(MutableSequence[int], ByteString):
def strip(self, chars: bytes = None) -> bytearray: ...
def swapcase(self) -> bytearray: ...
def title(self) -> bytearray: ...
- def translate(self, table: bytes) -> bytearray: ...
+ def translate(self, table: bytes, delete: bytes = None) -> bytearray: ...
def upper(self) -> bytearray: ...
def zfill(self, width: int) -> bytearray: ...
@classmethod
@@ -399,11 +401,10 @@ class bytearray(MutableSequence[int], ByteString):
@overload
def __setitem__(self, i: int, x: int) -> None: ...
@overload
- def __setitem__(self, s: slice, x: Sequence[int]) -> None: ...
+ def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ...
def __delitem__(self, i: Union[int, slice]) -> None: ...
def __add__(self, s: bytes) -> bytearray: ...
- # TODO: Mypy complains about __add__ and __iadd__ having different signatures.
- def __iadd__(self, s: Iterable[int]) -> bytearray: ... # type: ignore
+ def __iadd__(self, s: Iterable[int]) -> bytearray: ...
def __mul__(self, n: int) -> bytearray: ...
def __rmul__(self, n: int) -> bytearray: ...
def __imul__(self, n: int) -> bytearray: ...
@@ -445,7 +446,10 @@ class tuple(Sequence[_T_co], Generic[_T_co]):
def __mul__(self, n: int) -> Tuple[_T_co, ...]: ...
def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ...
def count(self, x: Any) -> int: ...
- def index(self, x: Any) -> int: ...
+ if sys.version_info >= (3, 5):
+ def index(self, x: Any, start: int = 0, end: int = 0) -> int: ...
+ else:
+ def index(self, x: Any) -> int: ...
class function:
# TODO not defined in builtins!
@@ -482,7 +486,7 @@ class list(MutableSequence[_T], Generic[_T]):
@overload
def __setitem__(self, i: int, o: _T) -> None: ...
@overload
- def __setitem__(self, s: slice, o: Sequence[_T]) -> None: ...
+ def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ...
def __delitem__(self, i: Union[int, slice]) -> None: ...
def __add__(self, x: List[_T]) -> List[_T]: ...
def __iadd__(self, x: Iterable[_T]) -> List[_T]: ...
@@ -542,9 +546,9 @@ class set(MutableSet[_T], Generic[_T]):
def discard(self, element: _T) -> None: ...
def intersection(self, *s: Iterable[Any]) -> set[_T]: ...
def intersection_update(self, *s: Iterable[Any]) -> None: ...
- def isdisjoint(self, s: AbstractSet[Any]) -> bool: ...
- def issubset(self, s: AbstractSet[Any]) -> bool: ...
- def issuperset(self, s: AbstractSet[Any]) -> bool: ...
+ def isdisjoint(self, s: Iterable[Any]) -> bool: ...
+ def issubset(self, s: Iterable[Any]) -> bool: ...
+ def issuperset(self, s: Iterable[Any]) -> bool: ...
def pop(self) -> _T: ...
def remove(self, element: _T) -> None: ...
def symmetric_difference(self, s: Iterable[_T]) -> set[_T]: ...
@@ -572,13 +576,13 @@ class set(MutableSet[_T], Generic[_T]):
class frozenset(AbstractSet[_T], Generic[_T]):
def __init__(self, iterable: Iterable[_T]=None) -> None: ...
def copy(self) -> frozenset[_T]: ...
- def difference(self, *s: AbstractSet[Any]) -> frozenset[_T]: ...
- def intersection(self, *s: AbstractSet[Any]) -> frozenset[_T]: ...
- def isdisjoint(self, s: AbstractSet[_T]) -> bool: ...
- def issubset(self, s: AbstractSet[Any]) -> bool: ...
- def issuperset(self, s: AbstractSet[Any]) -> bool: ...
- def symmetric_difference(self, s: AbstractSet[_T]) -> frozenset[_T]: ...
- def union(self, *s: AbstractSet[_T]) -> frozenset[_T]: ...
+ def difference(self, *s: Iterable[Any]) -> frozenset[_T]: ...
+ def intersection(self, *s: Iterable[Any]) -> frozenset[_T]: ...
+ def isdisjoint(self, s: Iterable[_T]) -> bool: ...
+ def issubset(self, s: Iterable[Any]) -> bool: ...
+ def issuperset(self, s: Iterable[Any]) -> bool: ...
+ def symmetric_difference(self, s: Iterable[_T]) -> frozenset[_T]: ...
+ def union(self, *s: Iterable[_T]) -> frozenset[_T]: ...
def __len__(self) -> int: ...
def __contains__(self, o: object) -> bool: ...
def __iter__(self) -> Iterator[_T]: ...
@@ -669,9 +673,7 @@ def iter(iterable: Iterable[_T]) -> Iterator[_T]: ...
@overload
def iter(function: Callable[[], _T], sentinel: _T) -> Iterator[_T]: ...
def isinstance(o: object, t: Union[type, Tuple[type, ...]]) -> bool: ...
-def issubclass(cls: type, classinfo: type) -> bool: ...
-# TODO support this
-#def issubclass(type cld, classinfo: Sequence[type]) -> bool: ...
+def issubclass(cls: type, classinfo: Union[type, Tuple[type, ...]]) -> bool: ...
def len(o: Sized) -> int: ...
def license() -> None: ...
def locals() -> Dict[str, Any]: ...
@@ -751,6 +753,9 @@ Ellipsis = ... # type: ellipsis
class BaseException:
args = ... # type: Any
+ __cause__ = ... # type: BaseException
+ __context__ = ... # type: BaseException
+ __traceback__ = ... # type: TracebackType
def __init__(self, *args: Any) -> None: ...
def with_traceback(self, tb: Any) -> BaseException: ...
@@ -797,10 +802,15 @@ class NotADirectoryError(OSError): ...
class PermissionError(OSError): ...
class ProcessLookupError(OSError): ...
class TimeoutError(OSError): ...
-class WindowsError(OSError): ...
+class WindowsError(OSError):
+ winerror = ... # type: int
class OverflowError(ArithmeticError): ...
class ReferenceError(Exception): ...
-class StopIteration(Exception): ...
+class StopIteration(Exception):
+ value = ... # type: Any
+if sys.version_info >= (3, 5):
+ class StopAsyncIteration(Exception):
+ value = ... # type: Any
class SyntaxError(Exception):
msg = ... # type: str
lineno = ... # type: int
@@ -820,7 +830,14 @@ class UnicodeDecodeError(UnicodeError):
reason = ... # type: str
def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int,
__reason: str) -> None: ...
-class UnicodeEncodeError(UnicodeError): ...
+class UnicodeEncodeError(UnicodeError):
+ encoding = ... # type: str
+ object = ... # type: str
+ start = ... # type: int
+ end = ... # type: int
+ reason = ... # type: str
+ def __init__(self, __encoding: str, __object: str, __start: int, __end: int,
+ __reason: str) -> None: ...
class UnicodeTranslateError(UnicodeError): ...
class ZeroDivisionError(ArithmeticError): ...
diff --git a/typeshed/stdlib/3/cgi.pyi b/typeshed/stdlib/3/cgi.pyi
index f251f31..1e8f31f 100644
--- a/typeshed/stdlib/3/cgi.pyi
+++ b/typeshed/stdlib/3/cgi.pyi
@@ -1 +1,4 @@
+from typing import Tuple
+
def escape(s: str, quote: bool = ...) -> str: ...
+def parse_header(s: str) -> Tuple[str, Dict[str, str]]: ...
diff --git a/typeshed/stdlib/3/collections/__init__.pyi b/typeshed/stdlib/3/collections/__init__.pyi
index 6e74100..0dc340e 100644
--- a/typeshed/stdlib/3/collections/__init__.pyi
+++ b/typeshed/stdlib/3/collections/__init__.pyi
@@ -65,7 +65,7 @@ class deque(MutableSequence[_T], Generic[_T]):
@overload
def __setitem__(self, i: int, x: _T) -> None: ...
@overload
- def __setitem__(self, s: slice, o: Sequence[_T]) -> None: raise TypeError
+ def __setitem__(self, s: slice, o: Iterable[_T]) -> None: raise TypeError
@overload
def __delitem__(self, i: int) -> None: ...
@overload
diff --git a/typeshed/stdlib/3/concurrent/futures/_base.pyi b/typeshed/stdlib/3/concurrent/futures/_base.pyi
index 84d10a0..98ffaf3 100644
--- a/typeshed/stdlib/3/concurrent/futures/_base.pyi
+++ b/typeshed/stdlib/3/concurrent/futures/_base.pyi
@@ -2,7 +2,7 @@
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
-from typing import Any
+from typing import TypeVar, Generic, Any, Iterable, Iterator, Callable, Tuple
from collections import namedtuple
FIRST_COMPLETED = ... # type: Any
@@ -54,28 +54,30 @@ class _AcquireFutures:
def __enter__(self): ...
def __exit__(self, *args): ...
-def as_completed(fs, timeout=None): ...
-
DoneAndNotDoneFutures = namedtuple('DoneAndNotDoneFutures', 'done not_done')
-def wait(fs, timeout=None, return_when=...): ...
+_T = TypeVar('_T')
-class Future:
- def __init__(self): ...
- def cancel(self): ...
- def cancelled(self): ...
- def running(self): ...
- def done(self): ...
- def add_done_callback(self, fn): ...
- def result(self, timeout=None): ...
- def exception(self, timeout=None): ...
- def set_running_or_notify_cancel(self): ...
- def set_result(self, result): ...
- def set_exception(self, exception): ...
+class Future(Generic[_T]):
+ def __init__(self) -> None: ...
+ def cancel(self) -> bool: ...
+ def cancelled(self) -> bool: ...
+ def running(self) -> bool: ...
+ def done(self) -> bool: ...
+ def add_done_callback(self, fn: Callable[[Future], Any]) -> None: ...
+ def result(self, timeout: float = ...) -> _T: ...
+ def exception(self, timeout: float = ...) -> Exception: ...
+ def set_running_or_notify_cancel(self) -> None: ...
+ def set_result(self, result: _T) -> None: ...
+ def set_exception(self, exception: Exception) -> None: ...
class Executor:
- def submit(self, fn, *args, **kwargs): ...
- def map(self, fn, *iterables, timeout=None, chunksize=1): ...
- def shutdown(self, wait=True): ...
- def __enter__(self): ...
- def __exit__(self, exc_type, exc_val, exc_tb): ...
+ 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 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: float = ...) -> Iterator[Future]: ...
+
+def wait(fs: Iterable[Future], timeout: float = ..., return_when: str = ...) -> Tuple[Iterable[Future], Iterable[Future]]: ...
diff --git a/typeshed/stdlib/3/contextlib.pyi b/typeshed/stdlib/3/contextlib.pyi
deleted file mode 100644
index 4400098..0000000
--- a/typeshed/stdlib/3/contextlib.pyi
+++ /dev/null
@@ -1,17 +0,0 @@
-# Stubs for contextlib
-
-# NOTE: These are incomplete!
-
-from typing import Callable, Generic, Iterator, TypeVar
-
-_T = TypeVar('_T')
-
-class ContextManager(Generic[_T]):
- def __enter__(self) -> _T: ...
- def __exit__(self, *exc_info) -> None: ...
-
-# TODO this doesn't capture the relationship that the returned function's args are the same as func's.
-def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
-
-class closing(ContextManager[_T], Generic[_T]):
- def __init__(self, thing: _T) -> None: ...
diff --git a/typeshed/stdlib/3/datetime.pyi b/typeshed/stdlib/3/datetime.pyi
index 6e0294f..382a587 100644
--- a/typeshed/stdlib/3/datetime.pyi
+++ b/typeshed/stdlib/3/datetime.pyi
@@ -2,15 +2,15 @@
# NOTE: These are incomplete!
-from typing import Optional, SupportsAbs, Tuple, Union, overload
+from typing import Optional, SupportsAbs, Tuple, overload
MINYEAR = 0
MAXYEAR = 0
class tzinfo:
def tzname(self, dt: Optional[datetime]) -> str: ...
- def utcoffset(self, dt: Optional[datetime]) -> int: ...
- def dst(self, dt: Optional[datetime]) -> int: ...
+ def utcoffset(self, dt: Optional[datetime]) -> Optional[timedelta]: ...
+ def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ...
def fromutc(self, dt: datetime) -> datetime: ...
class timezone(tzinfo):
@@ -97,7 +97,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: _tzinfo = None) -> time: ...
_date = date
_time = time
@@ -197,7 +197,7 @@ class datetime:
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: ...
+ _tzinfo = None) -> datetime: ...
def astimezone(self, tz: _tzinfo = ...) -> datetime: ...
def ctime(self) -> str: ...
def isoformat(self, sep: str = ...) -> str: ...
diff --git a/typeshed/stdlib/3/dis.pyi b/typeshed/stdlib/3/dis.pyi
index 8c08946..4777614 100644
--- a/typeshed/stdlib/3/dis.pyi
+++ b/typeshed/stdlib/3/dis.pyi
@@ -1,5 +1,4 @@
-from typing import (List, Union, Iterator, Iterable, Tuple, Optional, Dict,
- Any, IO, NamedTuple)
+from typing import List, Union, Iterator, Tuple, Optional, Any, IO, NamedTuple
from opcode import (hasconst, hasname, hasjrel, hasjabs, haslocal, hascompare,
hasfree, hasnargs, cmp_op, opname , opmap , HAVE_ARGUMENT,
@@ -11,7 +10,7 @@ _have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type]
_have_code_or_string = Union[_have_code, str, bytes]
-class Instruction(NamedTuple("Instruction", [
+Instruction = NamedTuple("Instruction", [
('opname', str),
('opcode', int),
('arg', Optional[int]),
@@ -20,18 +19,7 @@ class Instruction(NamedTuple("Instruction", [
('offset', int),
('starts_line', Optional[int]),
('is_jump_target', bool)
- ])):
- # ad-hoc - seems to be an error in the NamedTuple type hint
- # TODO: mypy issue #1076
- _fields = ... # type: List[str]
- _source = ... # type: str
- def _replace(self, *, opname: str = ..., opcode: int = ...,
- arg: Optional[int] = ..., argval: Any = ..., argrepr: str = ...,
- offset: int = ..., starts_line: Optional[int] = ...,
- is_jump_target: bool = ...) -> Instruction: ...
- def _asdict(self) -> Dict[str, Any]: ...
- @staticmethod
- def _make(iterable: Iterable[Any]) -> Instruction: ...
+ ])
# if sys.version_info >= (3, 4):
diff --git a/typeshed/stdlib/3/distutils/errors.pyi b/typeshed/stdlib/3/distutils/errors.pyi
deleted file mode 100644
index e5578f9..0000000
--- a/typeshed/stdlib/3/distutils/errors.pyi
+++ /dev/null
@@ -1,4 +0,0 @@
-import typing
-
-class DistutilsError(Exception): ...
-class DistutilsExecError(DistutilsError): ...
diff --git a/typeshed/stdlib/3/distutils/spawn.pyi b/typeshed/stdlib/3/distutils/spawn.pyi
deleted file mode 100644
index ac6eaf3..0000000
--- a/typeshed/stdlib/3/distutils/spawn.pyi
+++ /dev/null
@@ -1,6 +0,0 @@
-from typing import List
-
-# In Python, arguments have integer default values
-def spawn(cmd: List[str], search_path: bool = ..., verbose: bool = ...,
- dry_run: bool = ...) -> None: ...
-def find_executable(executable: str, path: str = ...) -> str: ...
diff --git a/typeshed/stdlib/3/email/__init__.pyi b/typeshed/stdlib/3/email/__init__.pyi
index 4d50f09..d42a901 100644
--- a/typeshed/stdlib/3/email/__init__.pyi
+++ b/typeshed/stdlib/3/email/__init__.pyi
@@ -2,7 +2,9 @@
from typing import Callable, Optional, IO
import sys
-from email.message import Message, Policy
+from email.message import Message
+if sys.version_info >= (3, 3):
+ from email.policy import Policy
if sys.version_info >= (3, 3):
def message_from_string(s: str, _class: Callable[[], Message] = ..., *,
@@ -15,16 +17,16 @@ if sys.version_info >= (3, 3):
_class: Callable[[], Message] = ..., *,
policy: Policy = ...) -> Message: ...
elif sys.version_info >= (3, 2):
- def message_from_string(s: str, # type: ignore
+ def message_from_string(s: str,
_class: Callable[[], Message] = ..., *,
strict: Optional[bool] = ...) -> Message: ...
- def message_from_bytes(s: bytes, # type: ignore
+ def message_from_bytes(s: bytes,
_class: Callable[[], Message] = ..., *,
strict: Optional[bool] = ...) -> Message: ...
- def message_from_file(fp: IO[str], # type: ignore
+ def message_from_file(fp: IO[str],
_class: Callable[[], Message] = ..., *,
strict: Optional[bool] = ...) -> Message: ...
- def message_from_binary_file(fp: IO[bytes], # type: ignore
+ def message_from_binary_file(fp: IO[bytes],
_class: Callable[[], Message] = ..., *,
strict: Optional[bool] = ...) -> Message: ...
diff --git a/typeshed/stdlib/3/email/_header_value_parser.pyi b/typeshed/stdlib/3/email/_header_value_parser.pyi
deleted file mode 100644
index 9101d67..0000000
--- a/typeshed/stdlib/3/email/_header_value_parser.pyi
+++ /dev/null
@@ -1,397 +0,0 @@
-# Stubs for email._header_value_parser (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-WSP = ... # type: Any
-CFWS_LEADER = ... # type: Any
-SPECIALS = ... # type: Any
-ATOM_ENDS = ... # type: Any
-DOT_ATOM_ENDS = ... # type: Any
-PHRASE_ENDS = ... # type: Any
-TSPECIALS = ... # type: Any
-TOKEN_ENDS = ... # type: Any
-ASPECIALS = ... # type: Any
-ATTRIBUTE_ENDS = ... # type: Any
-EXTENDED_ATTRIBUTE_ENDS = ... # type: Any
-
-def quote_string(value): ...
-
-class _Folded:
- maxlen = ... # type: Any
- policy = ... # type: Any
- lastlen = ... # type: Any
- stickyspace = ... # type: Any
- firstline = ... # type: Any
- done = ... # type: Any
- current = ... # type: Any
- def __init__(self, maxlen, policy) -> None: ...
- def newline(self): ...
- def finalize(self): ...
- def append(self, stoken): ...
- def append_if_fits(self, token, stoken=...): ...
-
-class TokenList(list):
- token_type = ... # type: Any
- defects = ... # type: Any
- def __init__(self, *args, **kw) -> None: ...
- @property
- def value(self): ...
- @property
- def all_defects(self): ...
- @property
- def parts(self): ...
- def startswith_fws(self): ...
- def pop_leading_fws(self): ...
- def pop_trailing_ws(self): ...
- @property
- def has_fws(self): ...
- def has_leading_comment(self): ...
- @property
- def comments(self): ...
- def fold(self, policy): ...
- def as_encoded_word(self, charset): ...
- def cte_encode(self, charset, policy): ...
- def pprint(self, indent=...): ...
- def ppstr(self, indent=...): ...
-
-class WhiteSpaceTokenList(TokenList):
- @property
- def value(self): ...
- @property
- def comments(self): ...
-
-class UnstructuredTokenList(TokenList):
- token_type = ... # type: Any
- def cte_encode(self, charset, policy): ...
-
-class Phrase(TokenList):
- token_type = ... # type: Any
- def cte_encode(self, charset, policy): ...
-
-class Word(TokenList):
- token_type = ... # type: Any
-
-class CFWSList(WhiteSpaceTokenList):
- token_type = ... # type: Any
- def has_leading_comment(self): ...
-
-class Atom(TokenList):
- token_type = ... # type: Any
-
-class Token(TokenList):
- token_type = ... # type: Any
-
-class EncodedWord(TokenList):
- token_type = ... # type: Any
- cte = ... # type: Any
- charset = ... # type: Any
- lang = ... # type: Any
- @property
- def encoded(self): ...
-
-class QuotedString(TokenList):
- token_type = ... # type: Any
- @property
- def content(self): ...
- @property
- def quoted_value(self): ...
- @property
- def stripped_value(self): ...
-
-class BareQuotedString(QuotedString):
- token_type = ... # type: Any
- @property
- def value(self): ...
-
-class Comment(WhiteSpaceTokenList):
- token_type = ... # type: Any
- def quote(self, value): ...
- @property
- def content(self): ...
- @property
- def comments(self): ...
-
-class AddressList(TokenList):
- token_type = ... # type: Any
- @property
- def addresses(self): ...
- @property
- def mailboxes(self): ...
- @property
- def all_mailboxes(self): ...
-
-class Address(TokenList):
- token_type = ... # type: Any
- @property
- def display_name(self): ...
- @property
- def mailboxes(self): ...
- @property
- def all_mailboxes(self): ...
-
-class MailboxList(TokenList):
- token_type = ... # type: Any
- @property
- def mailboxes(self): ...
- @property
- def all_mailboxes(self): ...
-
-class GroupList(TokenList):
- token_type = ... # type: Any
- @property
- def mailboxes(self): ...
- @property
- def all_mailboxes(self): ...
-
-class Group(TokenList):
- token_type = ... # type: Any
- @property
- def mailboxes(self): ...
- @property
- def all_mailboxes(self): ...
- @property
- def display_name(self): ...
-
-class NameAddr(TokenList):
- token_type = ... # type: Any
- @property
- def display_name(self): ...
- @property
- def local_part(self): ...
- @property
- def domain(self): ...
- @property
- def route(self): ...
- @property
- def addr_spec(self): ...
-
-class AngleAddr(TokenList):
- token_type = ... # type: Any
- @property
- def local_part(self): ...
- @property
- def domain(self): ...
- @property
- def route(self): ...
- @property
- def addr_spec(self): ...
-
-class ObsRoute(TokenList):
- token_type = ... # type: Any
- @property
- def domains(self): ...
-
-class Mailbox(TokenList):
- token_type = ... # type: Any
- @property
- def display_name(self): ...
- @property
- def local_part(self): ...
- @property
- def domain(self): ...
- @property
- def route(self): ...
- @property
- def addr_spec(self): ...
-
-class InvalidMailbox(TokenList):
- token_type = ... # type: Any
- @property
- def display_name(self): ...
- local_part = ... # type: Any
-
-class Domain(TokenList):
- token_type = ... # type: Any
- @property
- def domain(self): ...
-
-class DotAtom(TokenList):
- token_type = ... # type: Any
-
-class DotAtomText(TokenList):
- token_type = ... # type: Any
-
-class AddrSpec(TokenList):
- token_type = ... # type: Any
- @property
- def local_part(self): ...
- @property
- def domain(self): ...
- @property
- def value(self): ...
- @property
- def addr_spec(self): ...
-
-class ObsLocalPart(TokenList):
- token_type = ... # type: Any
-
-class DisplayName(Phrase):
- token_type = ... # type: Any
- @property
- def display_name(self): ...
- @property
- def value(self): ...
-
-class LocalPart(TokenList):
- token_type = ... # type: Any
- @property
- def value(self): ...
- @property
- def local_part(self): ...
-
-class DomainLiteral(TokenList):
- token_type = ... # type: Any
- @property
- def domain(self): ...
- @property
- def ip(self): ...
-
-class MIMEVersion(TokenList):
- token_type = ... # type: Any
- major = ... # type: Any
- minor = ... # type: Any
-
-class Parameter(TokenList):
- token_type = ... # type: Any
- sectioned = ... # type: Any
- extended = ... # type: Any
- charset = ... # type: Any
- @property
- def section_number(self): ...
- @property
- def param_value(self): ...
-
-class InvalidParameter(Parameter):
- token_type = ... # type: Any
-
-class Attribute(TokenList):
- token_type = ... # type: Any
- @property
- def stripped_value(self): ...
-
-class Section(TokenList):
- token_type = ... # type: Any
- number = ... # type: Any
-
-class Value(TokenList):
- token_type = ... # type: Any
- @property
- def stripped_value(self): ...
-
-class MimeParameters(TokenList):
- token_type = ... # type: Any
- @property
- def params(self): ...
-
-class ParameterizedHeaderValue(TokenList):
- @property
- def params(self): ...
- @property
- def parts(self): ...
-
-class ContentType(ParameterizedHeaderValue):
- token_type = ... # type: Any
- maintype = ... # type: Any
- subtype = ... # type: Any
-
-class ContentDisposition(ParameterizedHeaderValue):
- token_type = ... # type: Any
- content_disposition = ... # type: Any
-
-class ContentTransferEncoding(TokenList):
- token_type = ... # type: Any
- cte = ... # type: Any
-
-class HeaderLabel(TokenList):
- token_type = ... # type: Any
-
-class Header(TokenList):
- token_type = ... # type: Any
-
-class Terminal(str):
- token_type = ... # type: Any
- defects = ... # type: Any
- def __new__(cls, value, token_type): ...
- @property
- def all_defects(self): ...
- def cte_encode(self, charset, policy): ...
- def pop_trailing_ws(self): ...
- def pop_leading_fws(self): ...
- @property
- def comments(self): ...
- def has_leading_comment(self): ...
- def __getnewargs__(self): ...
-
-class WhiteSpaceTerminal(Terminal):
- @property
- def value(self): ...
- def startswith_fws(self): ...
- has_fws = ... # type: Any
-
-class ValueTerminal(Terminal):
- @property
- def value(self): ...
- def startswith_fws(self): ...
- has_fws = ... # type: Any
- def as_encoded_word(self, charset): ...
-
-class EWWhiteSpaceTerminal(WhiteSpaceTerminal):
- @property
- def value(self): ...
- @property
- def encoded(self): ...
- has_fws = ... # type: Any
-
-DOT = ... # type: Any
-ListSeparator = ... # type: Any
-RouteComponentMarker = ... # type: Any
-
-def get_fws(value): ...
-def get_encoded_word(value): ...
-def get_unstructured(value): ...
-def get_qp_ctext(value): ...
-def get_qcontent(value): ...
-def get_atext(value): ...
-def get_bare_quoted_string(value): ...
-def get_comment(value): ...
-def get_cfws(value): ...
-def get_quoted_string(value): ...
-def get_atom(value): ...
-def get_dot_atom_text(value): ...
-def get_dot_atom(value): ...
-def get_word(value): ...
-def get_phrase(value): ...
-def get_local_part(value): ...
-def get_obs_local_part(value): ...
-def get_dtext(value): ...
-def get_domain_literal(value): ...
-def get_domain(value): ...
-def get_addr_spec(value): ...
-def get_obs_route(value): ...
-def get_angle_addr(value): ...
-def get_display_name(value): ...
-def get_name_addr(value): ...
-def get_mailbox(value): ...
-def get_invalid_mailbox(value, endchars): ...
-def get_mailbox_list(value): ...
-def get_group_list(value): ...
-def get_group(value): ...
-def get_address(value): ...
-def get_address_list(value): ...
-def parse_mime_version(value): ...
-def get_invalid_parameter(value): ...
-def get_ttext(value): ...
-def get_token(value): ...
-def get_attrtext(value): ...
-def get_attribute(value): ...
-def get_extended_attrtext(value): ...
-def get_extended_attribute(value): ...
-def get_section(value): ...
-def get_value(value): ...
-def get_parameter(value): ...
-def parse_mime_parameters(value): ...
-def parse_content_type_header(value): ...
-def parse_content_disposition_header(value): ...
-def parse_content_transfer_encoding_header(value): ...
diff --git a/typeshed/stdlib/3/email/_parseaddr.pyi b/typeshed/stdlib/3/email/_parseaddr.pyi
deleted file mode 100644
index f5b34d4..0000000
--- a/typeshed/stdlib/3/email/_parseaddr.pyi
+++ /dev/null
@@ -1,44 +0,0 @@
-# Stubs for email._parseaddr (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-def parsedate_tz(data): ...
-def parsedate(data): ...
-def mktime_tz(data): ...
-def quote(str): ...
-
-class AddrlistClass:
- specials = ... # type: Any
- pos = ... # type: Any
- LWS = ... # type: Any
- CR = ... # type: Any
- FWS = ... # type: Any
- atomends = ... # type: Any
- phraseends = ... # type: Any
- field = ... # type: Any
- commentlist = ... # type: Any
- def __init__(self, field) -> None: ...
- def gotonext(self): ...
- def getaddrlist(self): ...
- def getaddress(self): ...
- def getrouteaddr(self): ...
- def getaddrspec(self): ...
- def getdomain(self): ...
- def getdelimited(self, beginchar, endchars, allowcomments=...): ...
- def getquote(self): ...
- def getcomment(self): ...
- def getdomainliteral(self): ...
- def getatom(self, atomends=...): ...
- def getphraselist(self): ...
-
-class AddressList(AddrlistClass):
- addresslist = ... # type: Any
- def __init__(self, field) -> None: ...
- def __len__(self): ...
- def __add__(self, other): ...
- def __iadd__(self, other): ...
- def __sub__(self, other): ...
- def __isub__(self, other): ...
- def __getitem__(self, index): ...
diff --git a/typeshed/stdlib/3/email/base64mime.pyi b/typeshed/stdlib/3/email/base64mime.pyi
deleted file mode 100644
index e94af9a..0000000
--- a/typeshed/stdlib/3/email/base64mime.pyi
+++ /dev/null
@@ -1,13 +0,0 @@
-# Stubs for email.base64mime (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-def header_length(bytearray): ...
-def header_encode(header_bytes, charset=...): ...
-def body_encode(s, maxlinelen=..., eol=...): ...
-def decode(string): ...
-
-body_decode = ... # type: Any
-decodestring = ... # type: Any
diff --git a/typeshed/stdlib/3/email/encoders.pyi b/typeshed/stdlib/3/email/encoders.pyi
index f9f111a..bb5c84c 100644
--- a/typeshed/stdlib/3/email/encoders.pyi
+++ b/typeshed/stdlib/3/email/encoders.pyi
@@ -1,8 +1,8 @@
# Stubs for email.encoders (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-def encode_base64(msg): ...
-def encode_quopri(msg): ...
-def encode_7or8bit(msg): ...
-def encode_noop(msg): ...
+from email.message import Message
+
+def encode_base64(msg: Message) -> None: ...
+def encode_quopri(msg: Message) -> None: ...
+def encode_7or8bit(msg: Message) -> None: ...
+def encode_noop(msg: Message) -> None: ...
diff --git a/typeshed/stdlib/3/email/feedparser.pyi b/typeshed/stdlib/3/email/feedparser.pyi
index 4950fa8..a86032d 100644
--- a/typeshed/stdlib/3/email/feedparser.pyi
+++ b/typeshed/stdlib/3/email/feedparser.pyi
@@ -3,14 +3,15 @@
from typing import Callable
import sys
from email.message import Message
-from email.policy import Policy
+if sys.version_info >= (3, 3):
+ from email.policy import Policy
class FeedParser:
if sys.version_info >= (3, 3):
def __init__(self, _factory: Callable[[], Message] = ..., *,
policy: Policy = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
_factory: Callable[[], Message] = ...) -> None: ...
def feed(self, data: str) -> None: ...
def close(self) -> Message: ...
@@ -21,7 +22,7 @@ if sys.version_info >= (3, 2):
def __init__(self, _factory: Callable[[], Message] = ..., *,
policy: Policy = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
_factory: Callable[[], Message] = ...) -> None: ...
def feed(self, data: str) -> None: ...
def close(self) -> Message: ...
diff --git a/typeshed/stdlib/3/email/generator.pyi b/typeshed/stdlib/3/email/generator.pyi
index eb8552c..4be36d1 100644
--- a/typeshed/stdlib/3/email/generator.pyi
+++ b/typeshed/stdlib/3/email/generator.pyi
@@ -2,8 +2,9 @@
from typing import TextIO, Optional
import sys
-from email.policy import Policy
from email.message import Message
+if sys.version_info >= (3, 3):
+ from email.policy import Policy
class Generator:
def clone(self, fp: TextIO) -> 'Generator': ...
@@ -13,14 +14,14 @@ class Generator:
maxheaderlen: int = ..., *,
policy: Policy = ...) -> None: ...
else:
- def __init__(self, outfp: TextIO, # type: ignore
+ def __init__(self, outfp: TextIO,
mangle_from_: bool = ...,
maxheaderlen: int = ...) -> None: ...
if sys.version_info >= (3, 2):
def flatten(self, msg: Message, unixfrom: bool = ...,
linesep: Optional[str] =...) -> None: ...
else:
- def flatten(self, msg: Message, # type: ignore
+ def flatten(self, msg: Message,
unixfrom: bool = ...) -> None: ...
if sys.version_info >= (3, 2):
@@ -32,7 +33,7 @@ if sys.version_info >= (3, 2):
maxheaderlen: int = ..., *,
policy: Policy = ...) -> None: ...
else:
- def __init__(self, outfp: TextIO, # type: ignore
+ def __init__(self, outfp: TextIO,
mangle_from_: bool = ...,
maxheaderlen: int = ...) -> None: ...
def flatten(self, msg: Message, unixfrom: bool = ...,
diff --git a/typeshed/stdlib/3/email/headerregistry.pyi b/typeshed/stdlib/3/email/headerregistry.pyi
index 078c65d..40b57d4 100644
--- a/typeshed/stdlib/3/email/headerregistry.pyi
+++ b/typeshed/stdlib/3/email/headerregistry.pyi
@@ -1,10 +1,11 @@
# Stubs for email.headerregistry (Python 3.4)
-from typing import Tuple, Optional, Any, Union, Mapping
+import datetime as dt
import sys
+from typing import Tuple, Optional, Any, Union, Mapping
from email.errors import MessageDefect
-from email.policy import Policy
-import datetime as dt
+if sys.version_info >= (3, 3):
+ from email.policy import Policy
if sys.version_info >= (3, 3):
diff --git a/typeshed/stdlib/3/email/iterators.pyi b/typeshed/stdlib/3/email/iterators.pyi
index c1bfb2f..6a69f39 100644
--- a/typeshed/stdlib/3/email/iterators.pyi
+++ b/typeshed/stdlib/3/email/iterators.pyi
@@ -1,7 +1,8 @@
# Stubs for email.iterators (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-def walk(self): ...
-def body_line_iterator(msg, decode=...): ...
-def typed_subpart_iterator(msg, maintype=..., subtype=...): ...
+from typing import Iterator, Optional
+from email.message import Message
+
+def body_line_iterator(msg: Message, decode: bool = ...) -> Iterator[str]: ...
+def typed_subpart_iterator(msg: Message, maintype: str = ...,
+ subtype: Optional[str] = ...) -> Iterator[str]: ...
diff --git a/typeshed/stdlib/3/email/message.pyi b/typeshed/stdlib/3/email/message.pyi
index 4bf3ca3..3162c03 100644
--- a/typeshed/stdlib/3/email/message.pyi
+++ b/typeshed/stdlib/3/email/message.pyi
@@ -6,8 +6,12 @@ from typing import (
import sys
from email.charset import Charset
from email.errors import MessageDefect
-from email.policy import Policy
-from email.contentmanager import ContentManager
+if sys.version_info >= (3, 3):
+ from email.policy import Policy
+if sys.version_info >= (3, 4):
+ from email.contentmanager import ContentManager
+else:
+ ContentManager = object # Hack so we can reference it in argument types.
_T = TypeVar('_T')
@@ -75,18 +79,21 @@ class Message:
requote: bool = ..., charset: str = ...,
language: str = ..., replace: bool = ...) -> None: ...
else:
- def as_string(self, unixfrom: bool = ..., # type: ignore
+ def as_string(self, unixfrom: bool = ...,
maxheaderlen: int = ...) -> str: ...
- def set_param(self, param: str, value: str, # type: ignore
+ def set_param(self, param: str, value: str,
header: str = ..., requote: bool = ...,
charset: str = ..., language: str = ...) -> None: ...
if sys.version_info >= (3, 3):
def __init__(self, policy: Policy = ...) -> None: ...
else:
- def __init__(self) -> None: ... # type: ignore
+ def __init__(self) -> None: ...
-class EmailMessage:
- def __init__(self, policy: Policy = ...) -> None: ...
+class MIMEPart:
+ if sys.version_info >= (3, 3):
+ def __init__(self, policy: Policy = ...) -> None: ...
+ else:
+ def __init__(self) -> None: ...
def get_body(self,
preferencelist: Sequence[str] = ...) -> Optional[Message]: ...
def iter_attachments(self) -> Iterator[Message]: ...
@@ -117,34 +124,7 @@ class EmailMessage:
@property
def is_attachment(self) -> bool: ...
-class MIMEPart:
- def __init__(self, policy: Policy = ...) -> None: ...
- def get_body(self,
- preferencelist: Sequence[str] = ...) -> Optional[Message]: ...
- def iter_attachments(self) -> Iterator[Message]: ...
- def iter_parts(self) -> Iterator[Message]: ...
- def get_content(self, *args: Any,
- content_manager: Optional[ContentManager] = ...,
- **kw: Any) -> Any: ...
+class EmailMessage(MIMEPart):
def set_content(self, *args: Any,
content_manager: Optional[ContentManager] = ...,
**kw: Any) -> None: ...
- def make_related(self, boundary: Optional[str] = ...) -> None: ...
- def make_alternative(self, boundary: Optional[str] = ...) -> None: ...
- def make_mixed(self, boundary: Optional[str] = ...) -> None: ...
- def add_related(self, *args: Any,
- content_manager: Optional[ContentManager] = ...,
- **kw: Any) -> None: ...
- def add_alternative(self, *args: Any,
- content_manager: Optional[ContentManager] = ...,
- **kw: Any) -> None: ...
- def add_attachement(self, *args: Any,
- content_manager: Optional[ContentManager] = ...,
- **kw: Any) -> None: ...
- def clear(self) -> None: ...
- def clear_content(self) -> None: ...
- if sys.version_info >= (3, 4, 2):
- def is_attachment(self) -> bool: ...
- else:
- @property
- def is_attachment(self) -> bool: ...
diff --git a/typeshed/third_party/3/pkg_resources/_vendor/__init__.py b/typeshed/stdlib/3/email/mime/__init__.py
similarity index 100%
rename from typeshed/third_party/3/pkg_resources/_vendor/__init__.py
rename to typeshed/stdlib/3/email/mime/__init__.py
diff --git a/typeshed/stdlib/3/email/mime/__init__.pyi b/typeshed/stdlib/3/email/mime/__init__.pyi
deleted file mode 100644
index 6c1b10c..0000000
--- a/typeshed/stdlib/3/email/mime/__init__.pyi
+++ /dev/null
@@ -1,4 +0,0 @@
-# Stubs for email.mime (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
diff --git a/typeshed/stdlib/3/email/mime/application.pyi b/typeshed/stdlib/3/email/mime/application.pyi
index bccbcb8..1aa0580 100644
--- a/typeshed/stdlib/3/email/mime/application.pyi
+++ b/typeshed/stdlib/3/email/mime/application.pyi
@@ -1,8 +1,11 @@
# Stubs for email.mime.application (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Callable, Optional, Tuple, Union
from email.mime.nonmultipart import MIMENonMultipart
+_ParamsType = Union[str, None, Tuple[str, Optional[str], str]]
+
class MIMEApplication(MIMENonMultipart):
- def __init__(self, _data, _subtype=..., _encoder=..., **_params) -> None: ...
+ def __init__(self, _data: bytes, _subtype: str = ...,
+ _encoder: Callable[[MIMEApplication], None] = ...,
+ **_params: _ParamsType) -> None: ...
diff --git a/typeshed/stdlib/3/email/mime/audio.pyi b/typeshed/stdlib/3/email/mime/audio.pyi
index b153cda..2d2c90c 100644
--- a/typeshed/stdlib/3/email/mime/audio.pyi
+++ b/typeshed/stdlib/3/email/mime/audio.pyi
@@ -1,8 +1,11 @@
# Stubs for email.mime.audio (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Callable, Optional, Tuple, Union
from email.mime.nonmultipart import MIMENonMultipart
+_ParamsType = Union[str, None, Tuple[str, Optional[str], str]]
+
class MIMEAudio(MIMENonMultipart):
- def __init__(self, _audiodata, _subtype=..., _encoder=..., **_params) -> None: ...
+ def __init__(self, _audiodata: bytes, _subtype: Optional[str] = ...,
+ _encoder: Callable[[MIMEAudio], None] = ...,
+ **_params: _ParamsType) -> None: ...
diff --git a/typeshed/stdlib/3/email/mime/base.pyi b/typeshed/stdlib/3/email/mime/base.pyi
index 3fe87d5..448d34b 100644
--- a/typeshed/stdlib/3/email/mime/base.pyi
+++ b/typeshed/stdlib/3/email/mime/base.pyi
@@ -1,8 +1,10 @@
# Stubs for email.mime.base (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-from email import message
+from typing import Optional, Tuple, Union
+import email.message
-class MIMEBase(message.Message):
- def __init__(self, _maintype, _subtype, **_params) -> None: ...
+_ParamsType = Union[str, None, Tuple[str, Optional[str], str]]
+
+class MIMEBase(email.message.Message):
+ def __init__(self, _maintype: str, _subtype: str,
+ **_params: _ParamsType) -> None: ...
diff --git a/typeshed/stdlib/3/email/mime/image.pyi b/typeshed/stdlib/3/email/mime/image.pyi
index 629c61f..9ec5deb 100644
--- a/typeshed/stdlib/3/email/mime/image.pyi
+++ b/typeshed/stdlib/3/email/mime/image.pyi
@@ -1,8 +1,11 @@
# Stubs for email.mime.image (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Callable, Optional, Tuple, Union
from email.mime.nonmultipart import MIMENonMultipart
+_ParamsType = Union[str, None, Tuple[str, Optional[str], str]]
+
class MIMEImage(MIMENonMultipart):
- def __init__(self, _imagedata, _subtype=..., _encoder=..., **_params) -> None: ...
+ def __init__(self, _imagedata: bytes, _subtype: Optional[str] = ...,
+ _encoder: Callable[[MIMEImage], None] = ...,
+ **_params: _ParamsType) -> None: ...
diff --git a/typeshed/stdlib/3/email/mime/message.pyi b/typeshed/stdlib/3/email/mime/message.pyi
index d4ff7d5..561e8c3 100644
--- a/typeshed/stdlib/3/email/mime/message.pyi
+++ b/typeshed/stdlib/3/email/mime/message.pyi
@@ -1,8 +1,7 @@
# Stubs for email.mime.message (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from email.message import Message
from email.mime.nonmultipart import MIMENonMultipart
class MIMEMessage(MIMENonMultipart):
- def __init__(self, _msg, _subtype=...) -> None: ...
+ def __init__(self, _msg: Message, _subtype: str = ...) -> None: ...
diff --git a/typeshed/stdlib/3/email/mime/multipart.pyi b/typeshed/stdlib/3/email/mime/multipart.pyi
index f998d94..ea5eba1 100644
--- a/typeshed/stdlib/3/email/mime/multipart.pyi
+++ b/typeshed/stdlib/3/email/mime/multipart.pyi
@@ -1,8 +1,12 @@
# Stubs for email.mime.multipart (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Optional, Sequence, Tuple, Union
+from email.message import Message
from email.mime.base import MIMEBase
+_ParamsType = Union[str, None, Tuple[str, Optional[str], str]]
+
class MIMEMultipart(MIMEBase):
- def __init__(self, _subtype=..., boundary=..., _subparts=..., **_params) -> None: ...
+ def __init__(self, _subtype: str = ..., boundary: Optional[str] = ...,
+ _subparts: Optional[Sequence[Message]] = ...,
+ **_params: _ParamsType) -> None: ...
diff --git a/typeshed/stdlib/3/email/mime/nonmultipart.pyi b/typeshed/stdlib/3/email/mime/nonmultipart.pyi
index 4e17cf9..1fd3ea9 100644
--- a/typeshed/stdlib/3/email/mime/nonmultipart.pyi
+++ b/typeshed/stdlib/3/email/mime/nonmultipart.pyi
@@ -1,8 +1,5 @@
# Stubs for email.mime.nonmultipart (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
from email.mime.base import MIMEBase
-class MIMENonMultipart(MIMEBase):
- def attach(self, payload): ...
+class MIMENonMultipart(MIMEBase): ...
diff --git a/typeshed/stdlib/3/email/mime/text.pyi b/typeshed/stdlib/3/email/mime/text.pyi
index 71c86ac..73adaf5 100644
--- a/typeshed/stdlib/3/email/mime/text.pyi
+++ b/typeshed/stdlib/3/email/mime/text.pyi
@@ -1,8 +1,8 @@
# Stubs for email.mime.text (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
+from typing import Optional
from email.mime.nonmultipart import MIMENonMultipart
class MIMEText(MIMENonMultipart):
- def __init__(self, _text, _subtype=..., _charset=...) -> None: ...
+ def __init__(self, _text: str, _subtype: str = ...,
+ _charset: Optional[str] = ...) -> None: ...
diff --git a/typeshed/stdlib/3/email/parser.pyi b/typeshed/stdlib/3/email/parser.pyi
index d5e7348..02c4ab6 100644
--- a/typeshed/stdlib/3/email/parser.pyi
+++ b/typeshed/stdlib/3/email/parser.pyi
@@ -3,7 +3,8 @@
from typing import Callable, Optional, TextIO, BinaryIO
import email.feedparser
from email.message import Message
-from email.policy import Policy
+if sys.version_info >= (3, 3):
+ from email.policy import Policy
import sys
FeedParser = email.feedparser.FeedParser
@@ -15,7 +16,7 @@ class Parser:
policy: Policy = ...) -> None: ...
else:
# TODO `strict` is positional
- def __init__(self, # type: ignore
+ def __init__(self,
_class: Callable[[], Message] = ..., *,
strict: Optional[bool]) -> None: ...
def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ...
@@ -27,7 +28,7 @@ class HeaderParser(Parser):
policy: Policy = ...) -> None: ...
else:
# TODO `strict` is positional
- def __init__(self, # type: ignore
+ def __init__(self,
_class: Callable[[], Message] = ..., *,
strict: Optional[bool]) -> None: ...
def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ...
@@ -40,7 +41,7 @@ if sys.version_info >= (3, 3):
policy: Policy = ...) -> None: ...
else:
# TODO `strict` is positional
- def __init__(self, # type: ignore
+ def __init__(self,
_class: Callable[[], Message] = ..., *,
strict: Optional[bool]) -> None: ...
def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ...
@@ -53,7 +54,7 @@ if sys.version_info >= (3, 2):
policy: Policy = ...) -> None: ...
else:
# TODO `strict` is positional
- def __init__(self, # type: ignore
+ def __init__(self,
_class: Callable[[], Message] = ..., *,
strict: Optional[bool]) -> None: ...
def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ...
diff --git a/typeshed/stdlib/3/email/policy.pyi b/typeshed/stdlib/3/email/policy.pyi
index 28f72bd..c34ee58 100644
--- a/typeshed/stdlib/3/email/policy.pyi
+++ b/typeshed/stdlib/3/email/policy.pyi
@@ -5,7 +5,8 @@ import sys
from email.message import Message
from email.errors import MessageDefect
from email.header import Header
-from email.contentmanager import ContentManager
+if sys.version_info >= (3, 4):
+ from email.contentmanager import ContentManager
from abc import abstractmethod
if sys.version_info >= (3, 3):
diff --git a/typeshed/stdlib/3/email/quoprimime.pyi b/typeshed/stdlib/3/email/quoprimime.pyi
deleted file mode 100644
index 558e8ff..0000000
--- a/typeshed/stdlib/3/email/quoprimime.pyi
+++ /dev/null
@@ -1,18 +0,0 @@
-# Stubs for email.quoprimime (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-def header_length(bytearray): ...
-def body_length(bytearray): ...
-def unquote(s): ...
-def quote(c): ...
-def header_encode(header_bytes, charset=...): ...
-def body_encode(body, maxlinelen=..., eol=...): ...
-def decode(encoded, eol=...): ...
-
-body_decode = ... # type: Any
-decodestring = ... # type: Any
-
-def header_decode(s): ...
diff --git a/typeshed/stdlib/3/email/utils.pyi b/typeshed/stdlib/3/email/utils.pyi
index 6a2ac27..9292500 100644
--- a/typeshed/stdlib/3/email/utils.pyi
+++ b/typeshed/stdlib/3/email/utils.pyi
@@ -1,22 +1,32 @@
# Stubs for email.utils (Python 3.4)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-import email._parseaddr
+from typing import List, Optional, Tuple, Union
+from email.charset import Charset
+import datetime
-mktime_tz = email._parseaddr.mktime_tz
-parsedate = email._parseaddr.parsedate
-parsedate_tz = email._parseaddr.parsedate_tz
+_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]]
+_PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]]
-def formataddr(pair, charset=...): ...
-def getaddresses(fieldvalues): ...
-def formatdate(timeval=..., localtime=..., usegmt=...): ...
-def format_datetime(dt, usegmt=...): ...
-def make_msgid(idstring=..., domain=...): ...
-def parsedate_to_datetime(data): ...
-def parseaddr(addr): ...
-def unquote(str): ...
-def decode_rfc2231(s): ...
-def encode_rfc2231(s, charset=..., language=...): ...
-def decode_params(params): ...
-def collapse_rfc2231_value(value, errors=..., fallback_charset=...): ...
+def quote(str: str) -> str: ...
+def unquote(str: str) -> str: ...
+def parseaddr(address: str) -> Tuple[str, str]: ...
+def formataddr(pair: Tuple[str, str],
+ charset: Union[str, Charset] = ...) -> str: ...
+def getaddresses(fieldvalues: List[str]) -> List[Tuple[str, str]]: ...
+def parsedate(date: str) -> Optional[Tuple[int, int, int, int, int, int, int, int, int]]: ...
+def parsedate_tz(date: str) -> Optional[_PDTZ]: ...
+def parsedate_to_datetime(date: str) -> datetime.datetime: ...
+def mktime_tz(tuple: _PDTZ) -> int: ...
+def formatdate(timeval: Optional[float] = ..., localtime: bool = ...,
+ usegmt: bool = ...) -> str: ...
+def format_datetime(dt: datetime.datetime, usegmt: bool = ...) -> str: ...
+def localtime(dt: Optional[datetime.datetime] = ...) -> datetime.datetime: ...
+def make_msgid(idstring: Optional[str] = ...,
+ domain: Optional[str] = ...) -> str: ...
+def decode_rfc2231(s: str) -> Tuple[Optional[str], Optional[str], str]: ...
+def encode_rfc2231(s: str, charset: Optional[str] = ...,
+ language: Optional[str] = ...) -> str: ...
+def collapse_rfc2231_value(value: _ParamType, errors: str = ...,
+ fallback_charset: str = ...) -> str: ...
+def decode_params(params: List[Tuple[str, str]]) \
+ -> List[Tuple[str, _ParamType]]: ...
diff --git a/typeshed/stdlib/3/errno.pyi b/typeshed/stdlib/3/errno.pyi
deleted file mode 100644
index e1f2ee3..0000000
--- a/typeshed/stdlib/3/errno.pyi
+++ /dev/null
@@ -1,132 +0,0 @@
-# Stubs for errno
-
-# Based on http://docs.python.org/3.2/library/errno.html
-
-from typing import Dict
-
-errorcode = ... # type: Dict[int, str]
-
-# TODO some of the names below are platform specific
-
-EPERM = 0
-ENOENT = 0
-ESRCH = 0
-EINTR = 0
-EIO = 0
-ENXIO = 0
-E2BIG = 0
-ENOEXEC = 0
-EBADF = 0
-ECHILD = 0
-EAGAIN = 0
-ENOMEM = 0
-EACCES = 0
-EFAULT = 0
-ENOTBLK = 0
-EBUSY = 0
-EEXIST = 0
-EXDEV = 0
-ENODEV = 0
-ENOTDIR = 0
-EISDIR = 0
-EINVAL = 0
-ENFILE = 0
-EMFILE = 0
-ENOTTY = 0
-ETXTBSY = 0
-EFBIG = 0
-ENOSPC = 0
-ESPIPE = 0
-EROFS = 0
-EMLINK = 0
-EPIPE = 0
-EDOM = 0
-ERANGE = 0
-EDEADLK = 0
-ENAMETOOLONG = 0
-ENOLCK = 0
-ENOSYS = 0
-ENOTEMPTY = 0
-ELOOP = 0
-EWOULDBLOCK = 0
-ENOMSG = 0
-EIDRM = 0
-ECHRNG = 0
-EL2NSYNC = 0
-EL3HLT = 0
-EL3RST = 0
-ELNRNG = 0
-EUNATCH = 0
-ENOCSI = 0
-EL2HLT = 0
-EBADE = 0
-EBADR = 0
-EXFULL = 0
-ENOANO = 0
-EBADRQC = 0
-EBADSLT = 0
-EDEADLOCK = 0
-EBFONT = 0
-ENOSTR = 0
-ENODATA = 0
-ETIME = 0
-ENOSR = 0
-ENONET = 0
-ENOPKG = 0
-EREMOTE = 0
-ENOLINK = 0
-EADV = 0
-ESRMNT = 0
-ECOMM = 0
-EPROTO = 0
-EMULTIHOP = 0
-EDOTDOT = 0
-EBADMSG = 0
-EOVERFLOW = 0
-ENOTUNIQ = 0
-EBADFD = 0
-EREMCHG = 0
-ELIBACC = 0
-ELIBBAD = 0
-ELIBSCN = 0
-ELIBMAX = 0
-ELIBEXEC = 0
-EILSEQ = 0
-ERESTART = 0
-ESTRPIPE = 0
-EUSERS = 0
-ENOTSOCK = 0
-EDESTADDRREQ = 0
-EMSGSIZE = 0
-EPROTOTYPE = 0
-ENOPROTOOPT = 0
-EPROTONOSUPPORT = 0
-ESOCKTNOSUPPORT = 0
-EOPNOTSUPP = 0
-EPFNOSUPPORT = 0
-EAFNOSUPPORT = 0
-EADDRINUSE = 0
-EADDRNOTAVAIL = 0
-ENETDOWN = 0
-ENETUNREACH = 0
-ENETRESET = 0
-ECONNABORTED = 0
-ECONNRESET = 0
-ENOBUFS = 0
-EISCONN = 0
-ENOTCONN = 0
-ESHUTDOWN = 0
-ETOOMANYREFS = 0
-ETIMEDOUT = 0
-ECONNREFUSED = 0
-EHOSTDOWN = 0
-EHOSTUNREACH = 0
-EALREADY = 0
-EINPROGRESS = 0
-ESTALE = 0
-EUCLEAN = 0
-ENOTNAM = 0
-ENAVAIL = 0
-EISNAM = 0
-EREMOTEIO = 0
-EDQUOT = 0
diff --git a/typeshed/stdlib/3/functools.pyi b/typeshed/stdlib/3/functools.pyi
index 0982cfe..2bd79ef 100644
--- a/typeshed/stdlib/3/functools.pyi
+++ b/typeshed/stdlib/3/functools.pyi
@@ -40,7 +40,7 @@ def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Seque
updated: Sequence[str] = ...) -> None: ...
def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ...
def total_ordering(cls: type) -> type: ...
-def cmp_to_key(mycmp: Callable[[_T, _T], bool]) -> Callable[[_T], Any]: ...
+def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ...
class partial(Generic[_T]):
func = ... # Callable[..., _T]
diff --git a/typeshed/stdlib/3/glob.pyi b/typeshed/stdlib/3/glob.pyi
index 71ab366..ab58e9a 100644
--- a/typeshed/stdlib/3/glob.pyi
+++ b/typeshed/stdlib/3/glob.pyi
@@ -1,8 +1,15 @@
# Stubs for glob
-
-# Based on http://docs.python.org/3.2/library/glob.html
+# Based on http://docs.python.org/3/library/glob.html
from typing import List, Iterator, AnyStr
+import sys
+
+if sys.version_info >= (3, 5):
+ def glob(pathname: AnyStr, *, recursive: bool = ...) -> List[AnyStr]: ...
+ def iglob(pathname: AnyStr, *, recursive: bool = ...) -> Iterator[AnyStr]: ...
+else:
+ def glob(pathname: AnyStr) -> List[AnyStr]: ...
+ def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ...
-def glob(pathname: AnyStr) -> List[AnyStr]: ...
-def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ...
+if sys.version_info >= (3, 4):
+ def escape(pathname: AnyStr) -> AnyStr: ...
diff --git a/typeshed/stdlib/3/heapq.pyi b/typeshed/stdlib/3/heapq.pyi
index 81b6135..f56ae72 100644
--- a/typeshed/stdlib/3/heapq.pyi
+++ b/typeshed/stdlib/3/heapq.pyi
@@ -16,7 +16,7 @@ if sys.version_info >= (3, 5):
def merge(*iterables: Iterable[_T], key: Callable[[_T], Any] = ...,
reverse: bool = ...) -> Iterable[_T]: ...
else:
- def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... # type: ignore
+ def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ...
def nlargest(n: int, iterable: Iterable[_T],
key: Callable[[_T], Any] = ...) -> List[_T]: ...
def nsmallest(n: int, iterable: Iterable[_T],
diff --git a/typeshed/stdlib/3/hmac.pyi b/typeshed/stdlib/3/hmac.pyi
deleted file mode 100644
index 4c7972b..0000000
--- a/typeshed/stdlib/3/hmac.pyi
+++ /dev/null
@@ -1,27 +0,0 @@
-# Stubs for hmac (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-from _operator import _compare_digest as compare_digest
-
-trans_5C = ... # type: Any
-trans_36 = ... # type: Any
-digest_size = ... # type: Any
-
-class HMAC:
- blocksize = ... # type: Any
- digest_cons = ... # type: Any
- outer = ... # type: Any
- inner = ... # type: Any
- digest_size = ... # type: Any
- block_size = ... # type: Any
- def __init__(self, key, msg=None, digestmod=None): ...
- @property
- def name(self): ...
- def update(self, msg): ...
- def copy(self): ...
- def digest(self): ...
- def hexdigest(self): ...
-
-def new(key, msg=None, digestmod=None): ...
diff --git a/typeshed/stdlib/3/html/parser.pyi b/typeshed/stdlib/3/html/parser.pyi
index f49627d..a72d194 100644
--- a/typeshed/stdlib/3/html/parser.pyi
+++ b/typeshed/stdlib/3/html/parser.pyi
@@ -6,10 +6,10 @@ class HTMLParser(ParserBase):
if sys.version_info >= (3, 5):
def __init__(self, *, convert_charrefs: bool = ...) -> None: ...
elif sys.version_info >= (3, 4):
- def __init__(self, strict: bool = ..., *, # type: ignore
+ def __init__(self, strict: bool = ..., *,
convert_charrefs: bool = ...) -> None: ...
else:
- def __init__(self, strict: bool = ...) -> None: ... # type: ignore
+ def __init__(self, strict: bool = ...) -> None: ...
def feed(self, feed: str) -> None: ...
def close(self) -> None: ...
def reset(self) -> None: ...
diff --git a/typeshed/stdlib/3/http/client.pyi b/typeshed/stdlib/3/http/client.pyi
index c9b92d6..f11ab99 100644
--- a/typeshed/stdlib/3/http/client.pyi
+++ b/typeshed/stdlib/3/http/client.pyi
@@ -79,80 +79,59 @@ responses = ... # type: Dict[int, str]
class HTTPMessage(email.message.Message): ...
-# TODO uncomment when mypy handle conditionals
-#if sys.version_info >= (3, 5):
-# class HTTPResponse(io.BufferedIOBase):
-# msg = ... # type: HTTPMessage
-# version = ... # type: int
-# debuglevel = ... # type: int
-# closed = ... # type: bool
-# status = ... # type: int
-# reason = ... # type: str
-# def read(self, amt: Optional[int] = ...) -> bytes: ...
-# def readinto(self, b: bytearray) -> int: ...
-# @overload
-# def getheader(self, name: str) -> Optional[str]: ...
-# @overload
-# def getheader(self, name: str, default: _T) -> Union[str, _T]: ...
-# def getheaders(self) -> List[Tuple[str, str]]: ...
-# def fileno(self) -> int: ...
-# def __iter__(self) -> Iterator[bytes]: ...
-# def __enter__(self) -> 'HTTPResponse': ...
-# def __exit__(self, exc_type: Optional[type],
-# exc_val: Optional[Exception],
-# exc_tb: Optional[types.TracebackType]) -> bool: ...
-#else:
-# class HTTPResponse:
-# msg = ... # type: HTTPMessage
-# version = ... # type: int
-# debuglevel = ... # type: int
-# closed = ... # type: bool
-# status = ... # type: int
-# reason = ... # type: str
-# def read(self, amt: Optional[int] = ...) -> bytes: ...
-# if sys.version_info >= (3, 3):
-# def readinto(self, b: bytearray) -> int: ...
-# @overload
-# def getheader(self, name: str) -> Optional[str]: ...
-# @overload
-# def getheader(self, name: str, default: _T) -> Union[str, _T]: ...
-# def getheaders(self) -> List[Tuple[str, str]]: ...
-# def fileno(self) -> int: ...
-# def __iter__(self) -> Iterator[bytes]: ...
-# def __enter__(self) -> 'HTTPResponse': ...
-# def __exit__(self, exc_type: Optional[type],
-# exc_val: Optional[Exception],
-# exc_tb: Optional[types.TracebackType]) -> bool: ...
-class HTTPResponse(io.BufferedIOBase):
- msg = ... # type: HTTPMessage
- version = ... # type: int
- debuglevel = ... # type: int
- closed = ... # type: bool
- status = ... # type: int
- reason = ... # type: str
- def read(self, amt: Optional[int] = ...) -> bytes: ...
- def readinto(self, b: bytearray) -> int: ...
- @overload
- def getheader(self, name: str) -> Optional[str]: ...
- @overload
- def getheader(self, name: str, default: _T) -> Union[str, _T]: ...
- def getheaders(self) -> List[Tuple[str, str]]: ...
- def fileno(self) -> int: ...
- def __iter__(self) -> Iterator[bytes]: ...
- def __enter__(self) -> 'HTTPResponse': ...
- def __exit__(self, exc_type: Optional[type],
- exc_val: Optional[Exception],
- exc_tb: Optional[types.TracebackType]) -> bool: ...
+if sys.version_info >= (3, 5):
+ class HTTPResponse(io.BufferedIOBase):
+ msg = ... # type: HTTPMessage
+ version = ... # type: int
+ debuglevel = ... # type: int
+ closed = ... # type: bool
+ status = ... # type: int
+ reason = ... # type: str
+ def read(self, amt: Optional[int] = ...) -> bytes: ...
+ def readinto(self, b: bytearray) -> int: ...
+ @overload
+ def getheader(self, name: str) -> Optional[str]: ...
+ @overload
+ def getheader(self, name: str, default: _T) -> Union[str, _T]: ...
+ def getheaders(self) -> List[Tuple[str, str]]: ...
+ def fileno(self) -> int: ...
+ def __iter__(self) -> Iterator[bytes]: ...
+ def __enter__(self) -> 'HTTPResponse': ...
+ def __exit__(self, exc_type: Optional[type],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[types.TracebackType]) -> bool: ...
+else:
+ class HTTPResponse:
+ msg = ... # type: HTTPMessage
+ version = ... # type: int
+ debuglevel = ... # type: int
+ closed = ... # type: bool
+ status = ... # type: int
+ reason = ... # type: str
+ def read(self, amt: Optional[int] = ...) -> bytes: ...
+ if sys.version_info >= (3, 3):
+ def readinto(self, b: bytearray) -> int: ...
+ @overload
+ def getheader(self, name: str) -> Optional[str]: ...
+ @overload
+ def getheader(self, name: str, default: _T) -> Union[str, _T]: ...
+ def getheaders(self) -> List[Tuple[str, str]]: ...
+ def fileno(self) -> int: ...
+ def __iter__(self) -> Iterator[bytes]: ...
+ def __enter__(self) -> 'HTTPResponse': ...
+ def __exit__(self, exc_type: Optional[type],
+ exc_val: Optional[Exception],
+ exc_tb: Optional[types.TracebackType]) -> bool: ...
class HTTPConnection:
if sys.version_info >= (3, 4):
- def __init__(self, # type: ignore
+ def __init__(self,
host: str, port: Optional[int] = ...,
timeout: int = ...,
source_address: Optional[Tuple[str, int]] = ...) \
-> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
host: str, port: Optional[int] = ...,
strict: bool = ..., timeout: int = ...,
source_address: Optional[Tuple[str, int]] = ...) \
@@ -174,7 +153,7 @@ class HTTPConnection:
class HTTPSConnection(HTTPConnection):
if sys.version_info >= (3, 4):
- def __init__(self, # type: ignore
+ def __init__(self,
host: str, port: Optional[int] = ...,
key_file: Optional[str] = ...,
cert_file: Optional[str] = ...,
@@ -183,7 +162,7 @@ class HTTPSConnection(HTTPConnection):
*, context: Optional[ssl.SSLContext] = ...,
check_hostname: Optional[bool] = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
host: str, port: Optional[int] = ...,
key_file: Optional[str] = ...,
cert_file: Optional[str] = ...,
diff --git a/typeshed/stdlib/3/http/cookiejar.pyi b/typeshed/stdlib/3/http/cookiejar.pyi
index 3761e08..38de5a3 100644
--- a/typeshed/stdlib/3/http/cookiejar.pyi
+++ b/typeshed/stdlib/3/http/cookiejar.pyi
@@ -7,12 +7,10 @@ from urllib.request import Request
_T = TypeVar('_T')
-# TODO uncomment when mypy handles conditionals
-#if sys.version_info >= (3, 3):
-# class LoadError(OSError): ...
-#else:
-# class LoadError(IOError): ...
-class LoadError(OSError): ...
+if sys.version_info >= (3, 3):
+ class LoadError(OSError): ...
+else:
+ class LoadError(IOError): ...
class CookieJar(Iterable['Cookie']):
diff --git a/typeshed/stdlib/3/importlib.pyi b/typeshed/stdlib/3/importlib.pyi
deleted file mode 100644
index 12cc79e..0000000
--- a/typeshed/stdlib/3/importlib.pyi
+++ /dev/null
@@ -1,9 +0,0 @@
-# Stubs for importlib
-
-# NOTE: These are incomplete!
-
-from typing import Any
-
-# TODO more precise type?
-def import_module(name: str, package: str = ...) -> Any: ...
-def invalidate_caches() -> None: ...
diff --git a/typeshed/stdlib/3/importlib/__init__.pyi b/typeshed/stdlib/3/importlib/__init__.pyi
index 1191ed7..7969a3c 100644
--- a/typeshed/stdlib/3/importlib/__init__.pyi
+++ b/typeshed/stdlib/3/importlib/__init__.pyi
@@ -1,3 +1,4 @@
+from importlib.abc import Loader
import sys
import types
from typing import Any, Mapping, Optional, Sequence
@@ -9,8 +10,7 @@ def __import__(name: str, globals: Mapping[str, Any] = None,
def import_module(name: str, package: str = None) -> types.ModuleType: ...
if sys.version_info >= (3, 3):
- # Optionally returns a loader, but importlib.abc doesn't have a stub file.
- def find_loader(name: str, path: str = None): ...
+ def find_loader(name: str, path: 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 9600492..96b3e28 100644
--- a/typeshed/stdlib/3/importlib/abc.pyi
+++ b/typeshed/stdlib/3/importlib/abc.pyi
@@ -1,5 +1,6 @@
import abc
-from _importlib_modulespec import ModuleSpec
+if sys.version_info >= (3, 4):
+ from _importlib_modulespec import ModuleSpec
import sys
import types
from typing import Any, Mapping, Optional, Sequence, Tuple, Union
@@ -35,7 +36,7 @@ class InspectLoader(Loader):
path: str = '<string>') -> types.CodeType: ...
elif sys.version_info >= (3, 5):
@staticmethod
- def source_to_code(self, data: Union[bytes, str],
+ def source_to_code(data: Union[bytes, str],
path: str = '<string>') -> types.CodeType: ...
class ExecutionLoader(InspectLoader):
diff --git a/typeshed/stdlib/3/importlib/machinery.pyi b/typeshed/stdlib/3/importlib/machinery.pyi
index d50b4a5..2305e36 100644
--- a/typeshed/stdlib/3/importlib/machinery.pyi
+++ b/typeshed/stdlib/3/importlib/machinery.pyi
@@ -5,93 +5,147 @@ from typing import Any, Callable, List, Optional, Sequence, Tuple, Union
# ModuleSpec is exported from this module, but for circular import
# reasons exists in its own stub file (with Loader and ModuleType).
-from _importlib_modulespec import ModuleSpec # Exported
+if sys.version_info >= (3, 4):
+ from _importlib_modulespec import ModuleSpec as ModuleSpec # Exported
-class BuiltinImporter(importlib.abc.MetaPathFinder,
- importlib.abc.InspectLoader):
- # MetaPathFinder
- @classmethod
- def find_module(cls, fullname: str,
- path: Optional[Sequence[importlib.abc._Path]]
- ) -> Optional[importlib.abc.Loader]:
- ...
- if sys.version_info >= (3, 4):
+if sys.version_info >= (3, 3):
+ class BuiltinImporter(importlib.abc.MetaPathFinder,
+ importlib.abc.InspectLoader):
+ # MetaPathFinder
@classmethod
- def find_spec(cls, fullname: str,
- path: Optional[Sequence[importlib.abc._Path]],
- target: types.ModuleType = None) -> Optional[ModuleSpec]:
+ def find_module(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]]
+ ) -> Optional[importlib.abc.Loader]:
...
- # InspectLoader
- @classmethod
- def is_package(cls, fullname: str) -> bool: ...
- @classmethod
- def load_module(cls, fullname: str) -> types.ModuleType: ...
- @classmethod
- def get_code(cls, fullname: str) -> None: ... # type: ignore
- @classmethod
- def get_source(cls, fullname: str) -> None: ... # type: ignore
- # Loader
- @classmethod
- def load_module(cls, fullname: str) -> types.ModuleType: ...
- if sys.version_info >= (3, 3):
- @staticmethod
- def module_repr(module: types.ModuleType) -> str: ... # type: ignore
- if sys.version_info >= (3, 4):
- @classmethod
- def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]:
+ if sys.version_info >= (3, 4):
+ @classmethod
+ def find_spec(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]],
+ target: types.ModuleType = None) -> Optional[ModuleSpec]:
+ ...
+ # InspectLoader
+ @classmethod
+ def is_package(cls, fullname: str) -> bool: ...
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
+ @classmethod
+ def get_code(cls, fullname: str) -> None: ... # type: ignore
+ @classmethod
+ def get_source(cls, fullname: str) -> None: ... # type: ignore
+ # Loader
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
+ if sys.version_info >= (3, 3):
+ @staticmethod
+ def module_repr(module: types.ModuleType) -> str: ... # type: ignore
+ if sys.version_info >= (3, 4):
+ @classmethod
+ def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]:
+ ...
+ @classmethod
+ def exec_module(cls, module: types.ModuleType) -> None: ...
+else:
+ class BuiltinImporter(importlib.abc.InspectLoader):
+ # MetaPathFinder
+ @classmethod
+ def find_module(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]]
+ ) -> Optional[importlib.abc.Loader]:
...
+ # InspectLoader
@classmethod
- def exec_module(cls, module: types.ModuleType) -> None: ...
+ def is_package(cls, fullname: str) -> bool: ...
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
+ @classmethod
+ def get_code(cls, fullname: str) -> None: ... # type: ignore
+ @classmethod
+ def get_source(cls, fullname: str) -> None: ... # type: ignore
+ # Loader
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
-class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
- # MetaPathFinder
- @classmethod
- def find_module(cls, fullname: str,
- path: Optional[Sequence[importlib.abc._Path]]
- ) -> Optional[importlib.abc.Loader]:
- ...
- if sys.version_info >= (3, 4):
+if sys.version_info >= (3, 3):
+ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
+ # MetaPathFinder
@classmethod
- def find_spec(cls, fullname: str,
- path: Optional[Sequence[importlib.abc._Path]],
- target: types.ModuleType = None) -> Optional[ModuleSpec]:
+ def find_module(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]]
+ ) -> Optional[importlib.abc.Loader]:
...
- # InspectLoader
- @classmethod
- def is_package(cls, fullname: str) -> bool: ...
- @classmethod
- def load_module(cls, fullname: str) -> types.ModuleType: ...
- @classmethod
- def get_code(cls, fullname: str) -> None: ... # type: ignore
- @classmethod
- def get_source(cls, fullname: str) -> None: ... # type: ignore
- # Loader
- @classmethod
- def load_module(cls, fullname: str) -> types.ModuleType: ...
- if sys.version_info >= (3, 3):
- @staticmethod
- def module_repr(module: types.ModuleType) -> str: ... # type: ignore
- if sys.version_info >= (3, 4):
- @classmethod
- def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]:
+ if sys.version_info >= (3, 4):
+ @classmethod
+ def find_spec(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]],
+ target: types.ModuleType = None) -> Optional[ModuleSpec]:
+ ...
+ # InspectLoader
+ @classmethod
+ def is_package(cls, fullname: str) -> bool: ...
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
+ @classmethod
+ def get_code(cls, fullname: str) -> None: ... # type: ignore
+ @classmethod
+ def get_source(cls, fullname: str) -> None: ... # type: ignore
+ # Loader
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
+ if sys.version_info >= (3, 3):
+ @staticmethod
+ def module_repr(module: types.ModuleType) -> str: ... # type: ignore
+ if sys.version_info >= (3, 4):
+ @classmethod
+ def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]:
+ ...
+ @staticmethod
+ def exec_module(module: types.ModuleType) -> None: ... # type: ignore
+else:
+ class FrozenImporter(importlib.abc.InspectLoader):
+ # MetaPathFinder
+ @classmethod
+ def find_module(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]]
+ ) -> Optional[importlib.abc.Loader]:
...
- @staticmethod
- def exec_module(module: types.ModuleType) -> None: ... # type: ignore
+ # InspectLoader
+ @classmethod
+ def is_package(cls, fullname: str) -> bool: ...
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
+ @classmethod
+ def get_code(cls, fullname: str) -> None: ... # type: ignore
+ @classmethod
+ def get_source(cls, fullname: str) -> None: ... # type: ignore
+ # Loader
+ @classmethod
+ def load_module(cls, fullname: str) -> types.ModuleType: ...
-class WindowsRegisteryFinder(importlib.abc.MetaPathFinder):
- @classmethod
- def find_module(cls, fullname: str,
- path: Optional[Sequence[importlib.abc._Path]]
- ) -> Optional[importlib.abc.Loader]:
- ...
- if sys.version_info >= (3, 4):
+if sys.version_info >= (3, 3):
+ class WindowsRegisteryFinder(importlib.abc.MetaPathFinder):
@classmethod
- def find_spec(cls, fullname: str,
- path: Optional[Sequence[importlib.abc._Path]],
- target: types.ModuleType = None) -> Optional[ModuleSpec]:
+ def find_module(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]]
+ ) -> Optional[importlib.abc.Loader]:
+ ...
+ if sys.version_info >= (3, 4):
+ @classmethod
+ def find_spec(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]],
+ target: types.ModuleType = None) -> Optional[ModuleSpec]:
+ ...
+else:
+ class WindowsRegisteryFinder:
+ @classmethod
+ def find_module(cls, fullname: str,
+ path: Optional[Sequence[importlib.abc._Path]]
+ ) -> Optional[importlib.abc.Loader]:
...
-class PathFinder(importlib.abc.MetaPathFinder): ...
+if sys.version_info >= (3, 3):
+ class PathFinder(importlib.abc.MetaPathFinder): ...
+else:
+ class PathFinder: ...
if sys.version_info >= (3, 3):
SOURCE_SUFFIXES = ... # type: List[str]
@@ -121,4 +175,4 @@ if sys.version_info >= (3, 3):
class ExtensionFileLoader(importlib.abc.ExecutionLoader):
def get_filename(self, fullname: str) -> importlib.abc._Path: ...
- def get_source(self, fullname: str) -> None: ... # type: ignore
+ def get_source(self, fullname: str) -> None: ... # type: ignore
diff --git a/typeshed/stdlib/3/inspect.pyi b/typeshed/stdlib/3/inspect.pyi
index fa75175..0f7af37 100644
--- a/typeshed/stdlib/3/inspect.pyi
+++ b/typeshed/stdlib/3/inspect.pyi
@@ -23,7 +23,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: ...
# Python 3.5+
diff --git a/typeshed/stdlib/3/io.pyi b/typeshed/stdlib/3/io.pyi
index 7b915fc..de2c7a4 100644
--- a/typeshed/stdlib/3/io.pyi
+++ b/typeshed/stdlib/3/io.pyi
@@ -52,11 +52,11 @@ class IOBase:
def readline(self, size: int = ...) -> bytes: ...
def __del__(self) -> None: ...
else:
- def readline(self, limit: int = ...) -> bytes: ... # type: ignore
+ def readline(self, limit: int = ...) -> bytes: ...
if sys.version_info >= (3, 2):
closed = ... # type: bool
else:
- def closed(self) -> bool: ... # type: ignore
+ def closed(self) -> bool: ...
class RawIOBase(IOBase):
def readall(self) -> bytes: ...
@@ -65,7 +65,7 @@ class RawIOBase(IOBase):
if sys.version_info >= (3, 4):
def read(self, size: int = ...) -> Optional[bytes]: ...
else:
- def read(self, n: int = ...) -> Optional[bytes]: ... # type: ignore
+ def read(self, n: int = ...) -> Optional[bytes]: ...
class BufferedIOBase(IOBase):
def detach(self) -> RawIOBase: ...
@@ -77,8 +77,8 @@ class BufferedIOBase(IOBase):
def read(self, size: Optional[int] = ...) -> bytes: ...
def read1(self, size: int = ...) -> bytes: ...
else:
- def read(self, n: Optional[int] = ...) -> bytes: ... # type: ignore
- def read1(self, n: int = ...) -> bytes: ... # type: ignore
+ def read(self, n: Optional[int] = ...) -> bytes: ...
+ def read1(self, n: int = ...) -> bytes: ...
class FileIO(RawIOBase):
@@ -91,7 +91,7 @@ class FileIO(RawIOBase):
Callable[[Union[int, str], str], int]] = ...) \
-> None: ...
else:
- def __init__(self, name: Union[str, bytes, int], # type: ignore
+ def __init__(self, name: Union[str, bytes, int],
mode: str = ..., closefd: bool = ...) -> None: ...
# TODO should extend from BufferedIOBase
@@ -124,11 +124,11 @@ class BytesIO(BinaryIO):
def readline(self, size: int = ...) -> bytes: ...
def __del__(self) -> None: ...
else:
- def readline(self, limit: int = ...): ... # type: ignore
+ def readline(self, limit: int = ...): ...
if sys.version_info >= (3, 2):
closed = ... # type: bool
else:
- def closed(self) -> bool: ... # type: ignore
+ def closed(self) -> bool: ...
# copied from BufferedIOBase
def detach(self) -> RawIOBase: ...
def readinto(self, b: bytearray) -> int: ...
@@ -139,15 +139,15 @@ class BytesIO(BinaryIO):
def read(self, size: Optional[int] = ...) -> bytes: ...
def read1(self, size: int = ...) -> bytes: ...
else:
- def read(self, n: Optional[int] = ...) -> bytes: ... # type: ignore
- def read1(self, n: int = ...) -> bytes: ... # type: ignore
+ def read(self, n: Optional[int] = ...) -> bytes: ...
+ def read1(self, n: int = ...) -> bytes: ...
class BufferedReader(BufferedIOBase):
def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ...
if sys.version_info >= (3, 4):
def peek(self, size: int = ...) -> bytes: ...
else:
- def peek(self, n: int = ...) -> bytes: ... # type: ignore
+ def peek(self, n: int = ...) -> bytes: ...
class BufferedWriter(BufferedIOBase):
def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ...
@@ -179,7 +179,7 @@ class TextIOBase(IOBase):
elif sys.version_info >= (3, 2):
def readline(self, limit: int = ...) -> str: ... # type: ignore
else:
- def readline(self) -> str: ... # type: ignore
+ def readline(self) -> str: ...
if sys.version_info >= (3, 2):
def seek(self, offset: int, whence: int = ...) -> int: ...
def tell(self) -> int: ...
@@ -194,7 +194,7 @@ class TextIOWrapper(TextIO):
# line_buffering: bool = ..., write_through: bool = ...) \
# -> None: ...
#else:
- # def __init__(self, buffer: IO[bytes], # type: ignore
+ # def __init__(self, buffer: IO[bytes],
# encoding: str = ..., errors: Optional[str] = ...,
# newline: Optional[str] = ..., line_buffering: bool = ...) \
# -> None: ...
@@ -222,23 +222,23 @@ class TextIOWrapper(TextIO):
if sys.version_info >= (3, 2):
closed = ... # type: bool
else:
- def closed(self) -> bool: ... # type: ignore
+ def closed(self) -> bool: ...
# copied from TextIOBase
encoding = ... # type: str
errors = ... # type: Optional[str]
newlines = ... # type: Union[str, Tuple[str, ...], None]
- def __iter__(self) -> Iterator[str]: ... # type: ignore
- def __next__(self) -> str: ... # type: ignore
+ def __iter__(self) -> Iterator[str]: ...
+ def __next__(self) -> str: ...
def __enter__(self) -> 'TextIO': ...
def detach(self) -> IOBase: ...
def write(self, s: str) -> int: ...
if sys.version_info >= (3, 4):
- def readline(self, size: int = ...) -> str: ... # type: ignore
+ def readline(self, size: int = ...) -> str: ...
def read(self, size: Optional[int] = ...) -> str: ...
elif sys.version_info >= (3, 2):
- def readline(self, limit: int = ...) -> str: ... # type: ignore
+ def readline(self, limit: int = ...) -> str: ...
else:
- def readline(self) -> str: ... # type: ignore
+ def readline(self) -> str: ...
if sys.version_info >= (3, 2):
def seek(self, offset: int, whence: int = ...) -> int: ...
def tell(self) -> int: ...
diff --git a/typeshed/stdlib/3/json.pyi b/typeshed/stdlib/3/json.pyi
index a706f27..d73245a 100644
--- a/typeshed/stdlib/3/json.pyi
+++ b/typeshed/stdlib/3/json.pyi
@@ -1,4 +1,4 @@
-from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union
+from typing import Any, IO, Iterator, Optional, Tuple, Callable, Dict, List, Union
class JSONDecodeError(ValueError):
def dumps(self, obj: Any) -> str: ...
@@ -49,3 +49,40 @@ def load(fp: IO[str],
parse_constant: Optional[Callable[[str], Any]] = ...,
object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ...,
**kwds: Any) -> Any: ...
+
+class JSONEncoder(object):
+ item_separator = ... # type: str
+ key_separator = ... # type: str
+
+ skipkeys = ... # type: bool
+ ensure_ascii = ... # type: bool
+ check_circular = ... # type: bool
+ allow_nan = ... # type: bool
+ 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 default(self, o: Any) -> Any: ...
+ def encode(self, o: Any) -> str: ...
+ def iterencode(self, o: Any, _one_shot: bool=False) -> Iterator[str]: ...
+
+class JSONDecoder(object):
+
+ object_hook = None # type: Callable[[Dict[str, Any]], Any]
+ parse_float = ... # Callable[[str], Any]
+ parse_int = ... # Callable[[str], Any]
+ parse_constant = ... # Callable[[str], Any]
+ 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 decode(self, s: str) -> Any: ...
+ def raw_decode(self, s: str) -> Tuple[Any, int]: ...
diff --git a/typeshed/stdlib/3/locale.pyi b/typeshed/stdlib/3/locale.pyi
deleted file mode 100644
index a76d137..0000000
--- a/typeshed/stdlib/3/locale.pyi
+++ /dev/null
@@ -1,17 +0,0 @@
-# Stubs for locale (Python 3.4)
-#
-# NOTE: This stub is based on a stub automatically generated by stubgen.
-
-from _locale import *
-
-def format(percent, value, grouping=..., monetary=..., *additional): ...
-def format_string(f, val, grouping=...): ...
-def currency(val, symbol=..., grouping=..., international=...): ...
-def str(val): ...
-def atof(string, func=...): ...
-def atoi(str): ...
-def normalize(localename): ...
-def getdefaultlocale(envvars=...): ...
-def getlocale(category=...): ...
-def resetlocale(category=...): ...
-def getpreferredencoding(do_setlocale=...): ...
diff --git a/typeshed/stdlib/3/mimetypes.pyi b/typeshed/stdlib/3/mimetypes.pyi
deleted file mode 100644
index a014447..0000000
--- a/typeshed/stdlib/3/mimetypes.pyi
+++ /dev/null
@@ -1,26 +0,0 @@
-# Stubs for mimetypes (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-
-class MimeTypes:
- encodings_map = ... # type: Any
- suffix_map = ... # type: Any
- types_map = ... # type: Any
- types_map_inv = ... # type: Any
- def __init__(self, filenames=..., strict=True): ...
- def add_type(self, type, ext, strict=True): ...
- def guess_type(self, url, strict=True): ...
- def guess_all_extensions(self, type, strict=True): ...
- def guess_extension(self, type, strict=True): ...
- def read(self, filename, strict=True): ...
- def readfp(self, fp, strict=True): ...
- def read_windows_registry(self, strict=True): ...
-
-def guess_type(url, strict=True): ...
-def guess_all_extensions(type, strict=True): ...
-def guess_extension(type, strict=True): ...
-def add_type(type, ext, strict=True): ...
-def init(files=None): ...
-def read_mime_types(file): ...
diff --git a/typeshed/stdlib/3/multiprocessing/__init__.pyi b/typeshed/stdlib/3/multiprocessing/__init__.pyi
index ff78662..2e142d5 100644
--- a/typeshed/stdlib/3/multiprocessing/__init__.pyi
+++ b/typeshed/stdlib/3/multiprocessing/__init__.pyi
@@ -2,6 +2,8 @@
from typing import Any, Callable, Iterable, Mapping
+from multiprocessing.process import current_process as current_process
+
class Lock():
def acquire(self, block: bool = ..., timeout: int = ...) -> None: ...
def release(self) -> None: ...
diff --git a/typeshed/stdlib/3/multiprocessing/managers.pyi b/typeshed/stdlib/3/multiprocessing/managers.pyi
index c4f6845..bbdb563 100644
--- a/typeshed/stdlib/3/multiprocessing/managers.pyi
+++ b/typeshed/stdlib/3/multiprocessing/managers.pyi
@@ -6,3 +6,5 @@ from typing import Any
class BaseManager():
def register(typeid: str, callable: Any = ...) -> None: ...
+
+class RemoteError(Exception): ...
diff --git a/typeshed/stdlib/3/multiprocessing/process.pyi b/typeshed/stdlib/3/multiprocessing/process.pyi
new file mode 100644
index 0000000..e1a43f5
--- /dev/null
+++ b/typeshed/stdlib/3/multiprocessing/process.pyi
@@ -0,0 +1,4 @@
+from multiprocessing import Process
+
+def current_process() -> Process: ...
+def active_children() -> List[Process]: ...
diff --git a/typeshed/stdlib/3/os/__init__.pyi b/typeshed/stdlib/3/os/__init__.pyi
index be9cbbd..e781842 100644
--- a/typeshed/stdlib/3/os/__init__.pyi
+++ b/typeshed/stdlib/3/os/__init__.pyi
@@ -105,6 +105,20 @@ WNOHANG = 0 # Unix only
TMP_MAX = 0 # Undocumented, but used by tempfile
# ----- os classes (structures) -----
+if sys.version_info >= (3, 5):
+ class DirEntry:
+ # This is what the scandir interator yields
+ # The constructor is hidden
+
+ name = ''
+ path = ''
+ def inode(self) -> int: ...
+ def is_dir(self, follow_symlinks: bool = ...) -> bool: ...
+ def is_file(self, follow_symlinks: bool = ...) -> bool: ...
+ def is_symlink(self) -> bool: ...
+ def stat(self) -> stat_result: ...
+
+
class stat_result:
# For backward compatibility, the return value of stat() is also
# accessible as a tuple of at least 10 integers giving the most important
@@ -259,6 +273,11 @@ def renames(old: AnyStr, new: AnyStr) -> None: ...
if sys.version_info >= (3, 3):
def replace(src: AnyStr, dst: AnyStr) -> None: ...
def rmdir(path: AnyStr) -> None: ...
+if sys.version_info >= (3, 5):
+ @overload
+ def scandir(path: str = ...) -> Iterator[DirEntry]: ...
+ @overload
+ def scandir(path: bytes) -> Iterator[DirEntry]: ...
def stat(path: AnyStr) -> stat_result: ...
def stat_float_times(newvalue: Union[bool, None] = ...) -> bool: ...
def statvfs(path: str) -> statvfs_result: ... # Unix only
diff --git a/typeshed/stdlib/3/pyclbr.pyi b/typeshed/stdlib/3/pyclbr.pyi
new file mode 100644
index 0000000..03c83f9
--- /dev/null
+++ b/typeshed/stdlib/3/pyclbr.pyi
@@ -0,0 +1,40 @@
+from typing import List, Union, Sequence, Optional, Dict
+
+
+class Class:
+ module = ... # type: str
+ name = ... # type: str
+ super = Optional[List[Union["Class", str]]]
+ methods = ... # type: Dict[str, int]
+ file = ... # type: int
+ lineno = ... # type: int
+
+ def __init__(self,
+ module: str,
+ name: str,
+ super: Optional[List[Union["Class", str]]],
+ file: str,
+ lineno: int) -> None: ...
+
+
+class Function:
+ module = ... # type: str
+ name = ... # type: str
+ file = ... # type: int
+ lineno = ... # type: int
+
+ def __init__(self,
+ module: str,
+ name: str,
+ file: str,
+ lineno: int) -> None: ...
+
+
+def readmodule(module: str,
+ path: Optional[Sequence[str]] = ...
+ ) -> Dict[str, Class]: ...
+
+
+def readmodule_ex(module: str,
+ path: Optional[Sequence[str]] = ...
+ ) -> Dict[str, Union[Class, Function, List[str]]]: ...
diff --git a/typeshed/stdlib/3/queue.pyi b/typeshed/stdlib/3/queue.pyi
index 90cd5fc..28609a0 100644
--- a/typeshed/stdlib/3/queue.pyi
+++ b/typeshed/stdlib/3/queue.pyi
@@ -6,6 +6,9 @@ from typing import Any, TypeVar, Generic
_T = TypeVar('_T')
+class Empty(Exception): ...
+class Full(Exception): ...
+
class Queue(Generic[_T]):
def __init__(self, maxsize: int = ...) -> None: ...
def full(self) -> bool: ...
@@ -17,4 +20,5 @@ class Queue(Generic[_T]):
def qsize(self) -> int: ...
def task_done(self) -> None: pass
-class Empty(Exception): ...
+class PriorityQueue(Queue): ...
+class LifoQueue(Queue): ...
diff --git a/typeshed/stdlib/3/re.pyi b/typeshed/stdlib/3/re.pyi
index 31e3cad..5bdd083 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
+ Generic, AnyStr, Match, Pattern, Any, Optional
)
# ----- re variables and constants -----
@@ -44,6 +44,12 @@ def match(pattern: AnyStr, string: AnyStr, flags: int = ...) -> Match[AnyStr]: .
@overload
def match(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> Match[AnyStr]: ...
+# New in Python 3.4
+ at overload
+def fullmatch(pattern: AnyStr, string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ...
+ at overload
+def fullmatch(pattern: Pattern[AnyStr], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ...
+
@overload
def split(pattern: AnyStr, string: AnyStr,
maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ...
diff --git a/typeshed/stdlib/3/socketserver.pyi b/typeshed/stdlib/3/socketserver.pyi
index 4cd6e2d..14a739b 100644
--- a/typeshed/stdlib/3/socketserver.pyi
+++ b/typeshed/stdlib/3/socketserver.pyi
@@ -1,6 +1,6 @@
# Stubs for socketserver
-from typing import BinaryIO, Optional, Tuple
+from typing import Any, BinaryIO, Optional, Tuple
from socket import SocketType
import sys
import types
@@ -68,7 +68,18 @@ class ForkingUDPServer(ForkingMixIn, UDPServer): ...
class ThreadingTCPServer(ThreadingMixIn, TCPServer): ...
class ThreadingUDPServer(ThreadingMixIn, UDPServer): ...
+
class BaseRequestHandler:
+ # Those are technically of types, respectively:
+ # * Union[SocketType, Tuple[bytes, SocketType]]
+ # * Union[Tuple[str, int], str]
+ # But there are some concerns that having unions here would cause
+ # too much inconvenience to people using it (see
+ # https://github.com/python/typeshed/pull/384#issuecomment-234649696)
+ request = ... # type: Any
+ client_address = ... # type: Any
+
+ server = ... # type: BaseServer
def setup(self) -> None: ...
def handle(self) -> None: ...
def finish(self) -> None: ...
diff --git a/typeshed/stdlib/3/ssl.pyi b/typeshed/stdlib/3/ssl.pyi
index cee0978..046a2c4 100644
--- a/typeshed/stdlib/3/ssl.pyi
+++ b/typeshed/stdlib/3/ssl.pyi
@@ -15,9 +15,9 @@ _PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes]
if sys.version_info >= (3, 5):
- _SC1ArgT = Union['SSLSocket', 'SSLObject']
+ _SC1ArgT = Union[SSLSocket, SSLObject]
else:
- _SC1ArgT = 'SSLSocket'
+ _SC1ArgT = SSLSocket
_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], 'SSLSocket'], Optional[int]]
class SSLError(OSError):
@@ -202,7 +202,7 @@ class SSLContext:
binary_form: bool = ...) \
-> Union[List[_PeerCertRetDictType], List[bytes]]: ...
else:
- def load_verify_locations(self, # type: ignore
+ def load_verify_locations(self,
cafile: Optional[str] = ...,
capath: Optional[str] = ...) -> None: ...
def set_default_verify_paths(self) -> None: ...
@@ -250,3 +250,25 @@ if sys.version_info >= (3, 5):
def read(self, n: int = ...) -> bytes: ...
def write(self, buf: bytes) -> int: ...
def write_eof(self) -> None: ...
+
+
+# TODO below documented in cpython but not in docs.python.org
+# taken from python 3.4
+SSL_ERROR_EOF = ... # type: int
+SSL_ERROR_INVALID_ERROR_CODE = ... # type: int
+SSL_ERROR_SSL = ... # type: int
+SSL_ERROR_SYSCALL = ... # type: int
+SSL_ERROR_WANT_CONNECT = ... # type: int
+SSL_ERROR_WANT_READ = ... # type: int
+SSL_ERROR_WANT_WRITE = ... # type: int
+SSL_ERROR_WANT_X509_LOOKUP = ... # type: int
+SSL_ERROR_ZERO_RETURN = ... # type: int
+
+def get_protocol_name(protocol_code: int) -> str: ...
+
+AF_INET = ... # type: int
+PEM_FOOTER = ... # type: str
+PEM_HEADER = ... # type: str
+SOCK_STREAM = ... # type: int
+SOL_SOCKET = ... # type: int
+SO_TYPE = ... # type: int
diff --git a/typeshed/stdlib/3/stat.pyi b/typeshed/stdlib/3/stat.pyi
index eadffb9..374373f 100644
--- a/typeshed/stdlib/3/stat.pyi
+++ b/typeshed/stdlib/3/stat.pyi
@@ -2,6 +2,7 @@
# Based on http://docs.python.org/3.2/library/stat.html
+import sys
import typing
def S_ISDIR(mode: int) -> bool: ...
@@ -62,8 +63,9 @@ UF_IMMUTABLE = 0
UF_APPEND = 0
UF_OPAQUE = 0
UF_NOUNLINK = 0
-#int UF_COMPRESSED # OS X 10.6+ only
-#int UF_HIDDEN # OX X 10.5+ only
+if sys.platform == 'darwin':
+ UF_COMPRESSED = 0 # OS X 10.6+ only
+ UF_HIDDEN = 0 # OX X 10.5+ only
SF_ARCHIVED = 0
SF_IMMUTABLE = 0
SF_APPEND = 0
diff --git a/typeshed/stdlib/3/string.pyi b/typeshed/stdlib/3/string.pyi
index bc35bb3..e2c7291 100644
--- a/typeshed/stdlib/3/string.pyi
+++ b/typeshed/stdlib/3/string.pyi
@@ -2,7 +2,7 @@
# Based on http://docs.python.org/3.2/library/string.html
-from typing import Mapping
+from typing import Mapping, Sequence, Any, Optional, Union, List, Tuple, Iterable, AnyStr
ascii_letters = ... # type: str
ascii_lowercase = ... # type: str
@@ -24,4 +24,19 @@ class Template:
def safe_substitute(self, mapping: Mapping[str, str],
**kwds: str) -> str: ...
-# TODO Formatter
+# TODO(MichalPokorny): This is probably badly and/or loosely typed.
+class Formatter(object):
+ def format(self, format_string: str, *args, **kwargs) -> str: ...
+ def vformat(self, format_string: str, args: Sequence[Any],
+ kwargs: Mapping[str, Any]) -> str: ...
+ def parse(self, format_string: str) -> Iterable[Tuple[str, Optional[str], Optional[str], Optional[str]]]: ...
+ def get_field(self, field_name: str, args: Sequence[Any],
+ kwargs: Mapping[str, Any]) -> Any: ...
+ def get_value(self, key: Union[int, str], args: Sequence[Any],
+ kwargs: Mapping[str, Any]) -> Any:
+ raise IndexError()
+ raise KeyError()
+ def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any],
+ kwargs: Mapping[str, Any]) -> None: ...
+ def format_field(self, value: Any, format_spec: str) -> Any: ...
+ def convert_field(self, value: Any, conversion: str) -> Any: ...
diff --git a/typeshed/stdlib/3/subprocess.pyi b/typeshed/stdlib/3/subprocess.pyi
index 43934b5..fd9e95b 100644
--- a/typeshed/stdlib/3/subprocess.pyi
+++ b/typeshed/stdlib/3/subprocess.pyi
@@ -1,74 +1,200 @@
# Stubs for subprocess
-# Based on http://docs.python.org/3.2/library/subprocess.html
+# Based on http://docs.python.org/3.5/library/subprocess.html
+import sys
+from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Optional, Union, List
-from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Optional, Union
+
+if sys.version_info >= (3, 5):
+ class CompletedProcess:
+ args = ... # type: Union[List, str]
+ returncode = ... # type: int
+ stdout = ... # type: Union[str, bytes]
+ stderr = ... # type: Union[str, bytes]
+ def __init__(self, args: Union[List, str],
+ returncode: int,
+ stdout: Union[str, bytes],
+ stderr: Union[str, bytes]) -> None: ...
+ def check_returncode(self): ...
+
+ # Nearly same args as Popen.__init__ except for timeout, input, and check
+ def run(args: Union[str, Sequence[str]],
+ timeout: float = ...,
+ input: Union[str, bytes] = ...,
+ check: bool = ...,
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stdout: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...) -> CompletedProcess: ...
# Same args as Popen.__init__
-def call(args: Union[str, Sequence[str]],
- bufsize: int = ...,
- executable: str = ...,
- stdin: Any = ...,
- stdout: Any = ...,
- stderr: Any = ...,
- preexec_fn: Callable[[], Any] = ...,
- close_fds: bool = ...,
- shell: bool = ...,
- cwd: str = ...,
- env: Mapping[str, str] = ...,
- universal_newlines: bool = ...,
- startupinfo: Any = ...,
- creationflags: int = ...,
- restore_signals: bool = ...,
- start_new_session: bool = ...,
- pass_fds: Any = ...) -> int: ...
+if sys.version_info >= (3, 3):
+ # 3.3 added timeout
+ def call(args: Union[str, Sequence[str]],
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stdout: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...,
+ timeout: float = ...) -> int: ...
+else:
+ def call(args: Union[str, Sequence[str]],
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stdout: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...) -> int: ...
# Same args as Popen.__init__
-def check_call(args: Union[str, Sequence[str]],
- bufsize: int = ...,
- executable: str = ...,
- stdin: Any = ...,
- stdout: Any = ...,
- stderr: Any = ...,
- preexec_fn: Callable[[], Any] = ...,
- close_fds: bool = ...,
- shell: bool = ...,
- cwd: str = ...,
- env: Mapping[str, str] = ...,
- universal_newlines: bool = ...,
- startupinfo: Any = ...,
- creationflags: int = ...,
- restore_signals: bool = ...,
- start_new_session: bool = ...,
- pass_fds: Any = ...) -> int: ...
-
-# Same args as Popen.__init__, except for stdout
-def check_output(args: Union[str, Sequence[str]],
- bufsize: int = ...,
- executable: str = ...,
- stdin: Any = ...,
- stderr: Any = ...,
- preexec_fn: Callable[[], Any] = ...,
- close_fds: bool = ...,
- shell: bool = ...,
- cwd: str = ...,
- env: Mapping[str, str] = ...,
- universal_newlines: bool = ...,
- startupinfo: Any = ...,
- creationflags: int = ...,
- restore_signals: bool = ...,
- start_new_session: bool = ...,
- pass_fds: Any = ...) -> Any: ...
+if sys.version_info >= (3, 3):
+ # 3.3 added timeout
+ def check_call(args: Union[str, Sequence[str]],
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stdout: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...,
+ timeout: float = ...) -> int: ...
+else:
+ def check_call(args: Union[str, Sequence[str]],
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stdout: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...) -> int: ...
+
+if sys.version_info >= (3, 4):
+ # 3.4 added input
+ def check_output(args: Union[str, Sequence[str]],
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...,
+ timeout: float = ...,
+ input: Union[str, bytes] = ...) -> Any: ...
+elif sys.version_info >= (3, 3):
+ # 3.3 added timeout
+ def check_output(args: Union[str, Sequence[str]],
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...,
+ timeout: float = ...) -> Any: ...
+else:
+ # Same args as Popen.__init__, except for stdout
+ def check_output(args: Union[str, Sequence[str]],
+ bufsize: int = ...,
+ executable: str = ...,
+ stdin: Any = ...,
+ stderr: Any = ...,
+ preexec_fn: Callable[[], Any] = ...,
+ close_fds: bool = ...,
+ shell: bool = ...,
+ cwd: str = ...,
+ env: Mapping[str, str] = ...,
+ universal_newlines: bool = ...,
+ startupinfo: Any = ...,
+ creationflags: int = ...,
+ restore_signals: bool = ...,
+ start_new_session: bool = ...,
+ pass_fds: Any = ...) -> Any: ...
+
# TODO types
PIPE = ... # type: Any
STDOUT = ... # type: Any
+if sys.version_info >= (3, 3):
+ DEVNULL = ... # type: Any
+ class SubprocessError(Exception): ...
+
class CalledProcessError(Exception):
returncode = 0
cmd = ... # type: str
output = b'' # May be None
+ if sys.version_info >= (3, 5):
+ stdout = b''
+ stderr = b''
+
def __init__(self, returncode: int, cmd: str, output: Optional[str] = ...,
stderr: Optional[str] = ...) -> None: ...
@@ -82,17 +208,17 @@ class Popen:
def __init__(self,
args: Union[str, Sequence[str]],
bufsize: int = ...,
- executable: str = ...,
- stdin: Any = ...,
- stdout: Any = ...,
- stderr: Any = ...,
- preexec_fn: Callable[[], Any] = ...,
+ executable: Optional[str] = ...,
+ stdin: Optional[Any] = ...,
+ stdout: Optional[Any] = ...,
+ stderr: Optional[Any] = ...,
+ preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
- cwd: str = ...,
- env: Mapping[str, str] = ...,
+ cwd: Optional[str] = ...,
+ env: Optional[Mapping[str, str]] = ...,
universal_newlines: bool = ...,
- startupinfo: Any = ...,
+ startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
@@ -101,7 +227,10 @@ class Popen:
def poll(self) -> int: ...
def wait(self) -> int: ...
# Return str/bytes
- def communicate(self, input=...) -> Tuple[Any, Any]: ...
+ if sys.version_info >= (3, 3):
+ def communicate(self, input: Union[str, bytes] = ..., timeout: float = ...) -> Tuple[Any, Any]: ...
+ else:
+ def communicate(self, input: Union[str, bytes] = ...) -> Tuple[Any, Any]: ...
def send_signal(self, signal: int) -> None: ...
def terminate(self) -> None: ...
def kill(self) -> None: ...
diff --git a/typeshed/stdlib/3/sys.pyi b/typeshed/stdlib/3/sys.pyi
index e65d792..c3ce9c6 100644
--- a/typeshed/stdlib/3/sys.pyi
+++ b/typeshed/stdlib/3/sys.pyi
@@ -5,7 +5,7 @@
from typing import (
List, Sequence, Any, Dict, Tuple, TextIO, overload, Optional, Union,
- TypeVar, Callable
+ TypeVar, Callable, Type,
)
from types import TracebackType
@@ -118,7 +118,7 @@ def displayhook(value: Optional[int]) -> None: ...
def excepthook(type_: type, value: BaseException,
traceback: TracebackType) -> None: ...
# TODO should be a union of tuple, see mypy#1178
-def exc_info() -> Tuple[Optional[type],
+def exc_info() -> Tuple[Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType]]: ...
# sys.exit() accepts an optional argument of anything printable
diff --git a/typeshed/stdlib/3/textwrap.pyi b/typeshed/stdlib/3/textwrap.pyi
index f644104..babb45e 100644
--- a/typeshed/stdlib/3/textwrap.pyi
+++ b/typeshed/stdlib/3/textwrap.pyi
@@ -79,6 +79,7 @@ def wrap(
...
def fill(
+ text: str,
width: int = ...,
*,
initial_indent: str = ...,
@@ -96,6 +97,7 @@ def fill(
...
def shorten(
+ text: str,
width: int,
*,
initial_indent: str = ...,
diff --git a/typeshed/stdlib/3/threading.pyi b/typeshed/stdlib/3/threading.pyi
deleted file mode 100644
index 83f2307..0000000
--- a/typeshed/stdlib/3/threading.pyi
+++ /dev/null
@@ -1,64 +0,0 @@
-# Stubs for threading
-
-# NOTE: These are incomplete!
-
-from typing import Any, Optional, Callable, TypeVar, Union, Mapping, Sequence
-
-class Thread:
- name = ... # type: str
- ident = 0
- daemon = False
-
- def __init__(self, group: Any = ..., target: Callable[..., Any] = ...,
- name: str = ..., args: Sequence[Any] = ...,
- kwargs: Mapping[str, Any] = ..., daemon: bool = ...) -> None: ...
- def start(self) -> None: ...
- def run(self) -> None: ...
- def join(self, timeout: float = ...) -> None: ...
- def is_alive(self) -> bool: ...
-
- # Legacy methods
- def getName(self) -> str: ...
- def setName(self, name: str) -> None: ...
- def isDaemon(self) -> bool: ...
- def setDaemon(self, daemon: bool) -> None: ...
-
-class Timer(Thread):
- def __init__(self, interval: float, function: Callable[..., Any],
- args: Sequence[Any] = ...,
- kwargs: Mapping[str, Any] = ...) -> None: ...
- def cancel(self) -> None : ...
-
-class local(Any): ...
-
-class Event:
- def is_set(self) -> bool: ...
- def set(self) -> None: ...
- def clear(self) -> None: ...
- # TODO can it return None?
- def wait(self, timeout: float = ...) -> bool: ...
-
-class Lock:
- def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ...
- def release(self) -> None: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
-
-class RLock:
- def acquire(self, blocking: bool = ...,
- timeout: float = ...) -> Optional[bool]: ...
- def release(self) -> None: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
-
-_T = TypeVar('_T')
-
-class Condition:
- def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ...
- def release(self) -> None: ...
- def notify(self, n: int = ...) -> None: ...
- def notify_all(self) -> None: ...
- def wait(self, timeout: float = ...) -> bool: ...
- def wait_for(self, predicate: Callable[[], _T], timeout: float = ...) -> Union[_T, bool]: ...
- def __enter__(self) -> bool: ...
- def __exit__(self, *args): ...
diff --git a/typeshed/stdlib/3/traceback.pyi b/typeshed/stdlib/3/traceback.pyi
deleted file mode 100644
index 4abc031..0000000
--- a/typeshed/stdlib/3/traceback.pyi
+++ /dev/null
@@ -1,18 +0,0 @@
-# Stubs for traceback
-
-from typing import List
-from types import TracebackType
-import typing
-
-# TODO signatures
-def format_exception_only(etype, value) -> List[str]: ...
-def format_exception(type: type, value: BaseException, tb: TracebackType, limit: int = ..., chain: bool = ...) -> List[str]: ...
-def format_tb(traceback): ...
-def print_exc(limit=..., file=..., chain=...): ...
-def format_exc(limit: int = ..., chain: bool = ...) -> str: ...
-def extract_stack(f=..., limit=...): ...
-def extract_tb(traceback, limit=...): ...
-def format_list(list): ...
-def format_stack(f=..., limit=...) -> List[str]: ...
-
-# TODO add more
diff --git a/typeshed/stdlib/3/typing.pyi b/typeshed/stdlib/3/typing.pyi
index 4492424..e40ff42 100644
--- a/typeshed/stdlib/3/typing.pyi
+++ b/typeshed/stdlib/3/typing.pyi
@@ -1,5 +1,6 @@
# Stubs for typing
+import sys
from abc import abstractmethod, ABCMeta
# Definitions of special type checking related constructs. Their definition
@@ -17,6 +18,7 @@ builtinclass = object()
_promote = object()
NamedTuple = object()
no_type_check = object()
+NewType = object()
# Type aliases and type constructors
@@ -112,11 +114,15 @@ class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
@abstractmethod
def __iter__(self) -> 'Generator[_T_co, _T_contra, _V_co]': ...
-class AbstractFuture(Generic[_T]): ...
-
class Awaitable(Generic[_T_co]):
@abstractmethod
- def __await__(self) -> Generator[AbstractFuture[_T_co], Any, _T_co]:...
+ def __await__(self) -> Generator[Any, None, _T_co]:...
+
+# NOTE: This type does not exist in typing.py or PEP 484.
+# The parameters corrrespond to Generator, but the 4th is the original type.
+class AwaitableGenerator(Generator[_T_co, _T_contra, _V_co], Awaitable[_T_co],
+ Generic[_T_co, _T_contra, _V_co, _S]):
+ pass
class AsyncIterable(Generic[_T_co]):
@abstractmethod
@@ -140,7 +146,10 @@ class Sequence(Iterable[_T_co], Container[_T_co], Sized, Reversible[_T_co], Gene
@abstractmethod
def __getitem__(self, s: slice) -> Sequence[_T_co]: ...
# Mixin methods
- def index(self, x: Any) -> int: ...
+ if sys.version_info >= (3, 5):
+ def index(self, x: Any, start: int = 0, end: int = 0) -> int: ...
+ else:
+ def index(self, x: Any) -> int: ...
def count(self, x: Any) -> int: ...
def __contains__(self, x: object) -> bool: ...
def __iter__(self) -> Iterator[_T_co]: ...
@@ -154,7 +163,7 @@ class MutableSequence(Sequence[_T], Generic[_T]):
def __setitem__(self, i: int, o: _T) -> None: ...
@overload
@abstractmethod
- def __setitem__(self, s: slice, o: Sequence[_T]) -> None: ...
+ def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ...
@overload
@abstractmethod
def __delitem__(self, i: int) -> None: ...
@@ -169,7 +178,7 @@ class MutableSequence(Sequence[_T], Generic[_T]):
def remove(self, object: _T) -> None: ...
def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ...
-class AbstractSet(Iterable[_KT_co], Container[_KT_co], Sized, Generic[_KT_co]):
+class AbstractSet(Iterable[_T_co], Container[_T_co], Sized, Generic[_T_co]):
@abstractmethod
def __contains__(self, x: object) -> bool: ...
# Mixin methods
@@ -177,13 +186,15 @@ class AbstractSet(Iterable[_KT_co], Container[_KT_co], Sized, Generic[_KT_co]):
def __lt__(self, s: AbstractSet[Any]) -> bool: ...
def __gt__(self, s: AbstractSet[Any]) -> bool: ...
def __ge__(self, s: AbstractSet[Any]) -> bool: ...
- def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_KT_co]: ...
- def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_KT_co, _T]]: ...
- def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_KT_co]: ...
- def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_KT_co, _T]]: ...
+ def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ...
+ def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ...
+ def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ...
+ def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ...
# TODO: Argument can be a more general ABC?
def isdisjoint(self, s: AbstractSet[Any]) -> bool: ...
+class FrozenSet(AbstractSet[_T], Generic[_T]): ...
+
class MutableSet(AbstractSet[_T], Generic[_T]):
@abstractmethod
def add(self, x: _T) -> None: ...
@@ -377,6 +388,9 @@ class Pattern(Generic[AnyStr]):
endpos: int = ...) -> Match[AnyStr]: ...
def match(self, string: AnyStr, pos: int = ...,
endpos: int = ...) -> Match[AnyStr]: ...
+ # New in Python 3.4
+ def fullmatch(self, string: AnyStr, pos: int = ...,
+ endpos: int = ...) -> Optional[Match[AnyStr]]: ...
def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr]: ...
def findall(self, string: AnyStr, pos: int = ...,
endpos: int = ...) -> list[Any]: ...
@@ -396,3 +410,7 @@ class Pattern(Generic[AnyStr]):
@overload
def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr,
count: int = ...) -> Tuple[AnyStr, int]: ...
+
+# Functions
+
+def get_type_hints(obj: Callable) -> dict[str, Any]: ...
diff --git a/typeshed/stdlib/3/unittest.pyi b/typeshed/stdlib/3/unittest.pyi
index 41fe554..a727709 100644
--- a/typeshed/stdlib/3/unittest.pyi
+++ b/typeshed/stdlib/3/unittest.pyi
@@ -232,7 +232,7 @@ class TestLoader:
def loadTestsFromModule(self, module: ModuleType,
*, pattern: Any = ...) -> TestSuite: ...
else:
- def loadTestsFromModule(self, # type: ignore
+ def loadTestsFromModule(self,
module: ModuleType) -> TestSuite: ...
def loadTestsFromName(self, name: str,
module: Optional[ModuleType] = ...) -> TestSuite: ...
@@ -297,7 +297,7 @@ class TextTestRunner(TestRunner):
warnings: Optional[Type[Warning]] = ...,
*, tb_locals: bool = ...) -> None: ...
else:
- def __init__(self, # type: ignore
+ def __init__(self,
stream: Optional[TextIO] = ...,
descriptions: bool = ..., verbosity: int = ...,
failfast: bool = ..., buffer: bool = ...,
@@ -308,7 +308,7 @@ class TextTestRunner(TestRunner):
if sys.version_info >= (3, 4):
_DefaultTestType = Union[str, Iterable[str], None]
else:
- _DefaultTestType = Optional[str]
+ _DefaultTestType = Union[str, None]
# not really documented
class TestProgram:
diff --git a/typeshed/stdlib/3/urllib/error.pyi b/typeshed/stdlib/3/urllib/error.pyi
index 2792964..fe4dbb1 100644
--- a/typeshed/stdlib/3/urllib/error.pyi
+++ b/typeshed/stdlib/3/urllib/error.pyi
@@ -1,5 +1,11 @@
+from typing import Any, Dict, Union
+from urllib.response import addinfourl
+
# Stubs for urllib.error
-class URLError(IOError): ...
-class HTTPError(URLError): ...
+class URLError(IOError):
+ reason = ... # type: Union[str, BaseException]
+class HTTPError(URLError, addinfourl):
+ code = ... # type: int
+ headers = ... # type: Dict[str, str]
class ContentTooShortError(URLError): ...
diff --git a/typeshed/stdlib/3/urllib/request.pyi b/typeshed/stdlib/3/urllib/request.pyi
index bdfa336..6786510 100644
--- a/typeshed/stdlib/3/urllib/request.pyi
+++ b/typeshed/stdlib/3/urllib/request.pyi
@@ -38,7 +38,7 @@ class Request:
@full_url.deleter
def full_url(self) -> None: ...
else:
- full_url = ... # type: ignore # type: str
+ full_url = ... # type: str
type = ... # type: str
host = ... # type: str
origin_req_host = ... # type: str
diff --git a/typeshed/stdlib/3/xml/sax/__init__.pyi b/typeshed/stdlib/3/xml/sax/__init__.pyi
new file mode 100644
index 0000000..a0a0a89
--- /dev/null
+++ b/typeshed/stdlib/3/xml/sax/__init__.pyi
@@ -0,0 +1,20 @@
+# 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/3/zipfile.pyi b/typeshed/stdlib/3/zipfile.pyi
deleted file mode 100644
index 5745674..0000000
--- a/typeshed/stdlib/3/zipfile.pyi
+++ /dev/null
@@ -1,29 +0,0 @@
-# TODO these are incomplete
-
-from typing import List, Tuple, BinaryIO, Union
-
-ZIP_STORED = 0
-ZIP_DEFLATED = 0
-
-def is_zipfile(filename: Union[str, BinaryIO]) -> bool: ...
-
-class ZipInfo:
- filename = ... # type: str
- date_time = ... # type: Tuple[int, int, int, int, int, int]
- compressed_size = 0
- file_size = 0
-
-class ZipFile:
- def __init__(self, file: Union[str, BinaryIO], mode: str = ...,
- compression: int = ...,
- allowZip64: bool = ...) -> None: ...
- def close(self) -> None: ...
- def getinfo(name: str) -> ZipInfo: ...
- def infolist(self) -> List[ZipInfo]: ...
- def namelist(self) -> List[str]: ...
- def read(self, name: Union[str, ZipInfo], pwd: str = ...) -> bytes: ...
- def write(self, filename: str, arcname: str = ...,
- compress_type: int = ...) -> None: ...
-
- def __enter__(self) -> 'ZipFile': ...
- def __exit__(self, type, value, traceback) -> bool: ...
diff --git a/typeshed/tests/mypy_test.py b/typeshed/tests/mypy_test.py
index 2d13744..dc02246 100755
--- a/typeshed/tests/mypy_test.py
+++ b/typeshed/tests/mypy_test.py
@@ -116,6 +116,8 @@ def main():
if files:
runs += 1
flags = ['--python-version', '%d.%d' % (major, minor)]
+ flags.append('--strict-optional')
+ ##flags.append('--warn-unused-ignores')
sys.argv = ['mypy'] + flags + files
if args.verbose:
print("running", ' '.join(sys.argv))
diff --git a/typeshed/third_party/2.7/dateutil/relativedelta.pyi b/typeshed/third_party/2.7/dateutil/relativedelta.pyi
new file mode 100644
index 0000000..b37ef5d
--- /dev/null
+++ b/typeshed/third_party/2.7/dateutil/relativedelta.pyi
@@ -0,0 +1,86 @@
+from typing import Any, Optional, Union
+from datetime import date, datetime, timedelta
+
+__all__ = ... # type: List[str]
+
+
+class weekday(object):
+ def __init__(self, weekday: int, n: Optional[int]=...) -> None: ...
+
+ def __call__(self, n: int) -> 'weekday': ...
+
+ def __eq__(self, other) -> bool: ...
+
+ def __repr__(self) -> str: ...
+
+ weekday = ... # type: int
+ n = ... # type: int
+
+MO = ... # type: weekday
+TU = ... # type: weekday
+WE = ... # type: weekday
+TH = ... # type: weekday
+FR = ... # type: weekday
+SA = ... # type: weekday
+SU = ... # type: weekday
+
+
+class relativedelta(object):
+ def __init__(self,
+ dt1: Optional[date]=...,
+ dt2: Optional[date]=...,
+ years: Optional[int]=..., months: Optional[int]=...,
+ days: Optional[int]=..., leapdays: Optional[int]=...,
+ weeks: Optional[int]=...,
+ hours: Optional[int]=..., minutes: Optional[int]=...,
+ seconds: Optional[int]=..., microseconds: Optional[int]=...,
+ year: Optional[int]=..., month: Optional[int]=...,
+ day: Optional[int]=...,
+ weekday: Optional[Union[int, weekday]]=...,
+ yearday: Optional[int]=...,
+ nlyearday: Optional[int]=...,
+ hour: Optional[int]=..., minute: Optional[int]=...,
+ second: Optional[int]=...,
+ microsecond: Optional[int]=...) -> None: ...
+
+ @property
+ def weeks(self) -> int: ...
+
+ @weeks.setter
+ def weeks(self, value: int) -> None: ...
+
+ def normalized(self) -> 'relativedelta': ...
+
+ def __add__(
+ self,
+ other: Union['relativedelta', timedelta, date, datetime]) -> 'relativedelta': ...
+
+ def __radd__(
+ self,
+ other: Any) -> 'relativedelta': ...
+
+ def __rsub__(
+ self,
+ other: Any) -> 'relativedelta': ...
+
+ def __sub__(self, other: 'relativedelta') -> 'relativedelta': ...
+
+ def __neg__(self) -> 'relativedelta': ...
+
+ def __bool__(self) -> bool: ...
+
+ def __nonzero__(self) -> bool: ...
+
+ def __mul__(self, other: float) -> 'relativedelta': ...
+
+ def __rmul__(self, other: float) -> 'relativedelta': ...
+
+ def __eq__(self, other) -> bool: ...
+
+ def __ne__(self, other: object) -> bool: ...
+
+ def __div__(self, other: float) -> 'relativedelta': ...
+
+ def __truediv__(self, other: float) -> 'relativedelta': ...
+
+ def __repr__(self) -> str: ...
diff --git a/typeshed/third_party/2.7/google/protobuf/__init__.pyi b/typeshed/third_party/2.7/google/protobuf/__init__.pyi
index e69de29..d232164 100644
--- a/typeshed/third_party/2.7/google/protobuf/__init__.pyi
+++ b/typeshed/third_party/2.7/google/protobuf/__init__.pyi
@@ -0,0 +1 @@
+__version__ = ... # type: str
diff --git a/typeshed/third_party/2and3/pytz/__init__.pyi b/typeshed/third_party/2and3/pytz/__init__.pyi
new file mode 100644
index 0000000..dc9c8fc
--- /dev/null
+++ b/typeshed/third_party/2and3/pytz/__init__.pyi
@@ -0,0 +1,25 @@
+# Stubs for pytz (Python 3.5)
+
+import datetime as dt
+from typing import Optional, List, Set, Dict # NOQA
+
+all_timezones = ... # type: List
+all_timezones_set = ... # type: Set
+common_timezones = ... # type: List
+common_timezones_set = ... # type: Set
+country_timezones = ... # type: Dict
+country_names = ... # type: Dict
+
+
+class UTC(dt.tzinfo):
+ zone = ... # type: str
+ def fromutc(self, dt: dt.datetime) -> dt.datetime: ...
+ def utcoffset(self, dt: Optional[dt.datetime]) -> dt.timedelta: ... # type: ignore
+ def tzname(self, dt: Optional[dt.datetime]) -> str: ...
+ def dst(self, dt: Optional[dt.datetime]) -> dt.timedelta: ... # type: ignore
+ def localize(self, dt: dt.datetime, is_dst: bool=...) -> dt.datetime: ...
+ def normalize(self, dt: dt.datetime, is_dst: bool=...) -> dt.datetime: ...
+
+utc = ... # type: UTC
+
+def timezone(zone: str) -> UTC: ...
diff --git a/typeshed/third_party/2and3/pytz/lazy.pyi b/typeshed/third_party/2and3/pytz/lazy.pyi
new file mode 100644
index 0000000..3618333
--- /dev/null
+++ b/typeshed/third_party/2and3/pytz/lazy.pyi
@@ -0,0 +1,13 @@
+# Stubs for pytz.lazy (Python 3.5)
+
+from typing import Any, Iterable, List, Set, Dict # NOQA
+from collections import Mapping
+
+class LazyDict(Mapping):
+ pass
+
+class LazyList(List):
+ pass
+
+class LazySet(Set):
+ pass
diff --git a/typeshed/third_party/2and3/ujson.pyi b/typeshed/third_party/2and3/ujson.pyi
new file mode 100644
index 0000000..147f67a
--- /dev/null
+++ b/typeshed/third_party/2and3/ujson.pyi
@@ -0,0 +1,45 @@
+# Stubs for ujson
+# See: https://pypi.python.org/pypi/ujson
+from typing import Any, IO, Optional
+
+__version__ = ... # type: str
+
+def encode(obj: Any,
+ ensure_ascii: bool = ...,
+ double_precision: bool = ...,
+ encode_html_chars: bool = ...,
+ escape_forward_slashes: bool = ...,
+ sort_keys: bool = ...,
+ indent: int = ...,
+ ) -> str: ...
+
+def dumps(obj: Any,
+ ensure_ascii: bool = ...,
+ double_precision: bool = ...,
+ encode_html_chars: bool = ...,
+ escape_forward_slashes: bool = ...,
+ sort_keys: bool = ...,
+ indent: int = ...,
+ ) -> str: ...
+
+def dump(obj: Any,
+ fp: IO[str],
+ ensure_ascii: bool = ...,
+ double_precision: bool = ...,
+ encode_html_chars: bool = ...,
+ escape_forward_slashes: bool = ...,
+ sort_keys: bool = ...,
+ indent: int = ...,
+ ) -> None: ...
+
+def decode(s: str,
+ precise_float: bool = ...,
+ ) -> Any: ...
+
+def loads(s: str,
+ precise_float: bool = ...,
+ ) -> Any: ...
+
+def load(fp: IO[str],
+ precise_float: bool = ...,
+ ) -> Any: ...
diff --git a/typeshed/third_party/3/dateutil/relativedelta.pyi b/typeshed/third_party/3/dateutil/relativedelta.pyi
new file mode 100644
index 0000000..b37ef5d
--- /dev/null
+++ b/typeshed/third_party/3/dateutil/relativedelta.pyi
@@ -0,0 +1,86 @@
+from typing import Any, Optional, Union
+from datetime import date, datetime, timedelta
+
+__all__ = ... # type: List[str]
+
+
+class weekday(object):
+ def __init__(self, weekday: int, n: Optional[int]=...) -> None: ...
+
+ def __call__(self, n: int) -> 'weekday': ...
+
+ def __eq__(self, other) -> bool: ...
+
+ def __repr__(self) -> str: ...
+
+ weekday = ... # type: int
+ n = ... # type: int
+
+MO = ... # type: weekday
+TU = ... # type: weekday
+WE = ... # type: weekday
+TH = ... # type: weekday
+FR = ... # type: weekday
+SA = ... # type: weekday
+SU = ... # type: weekday
+
+
+class relativedelta(object):
+ def __init__(self,
+ dt1: Optional[date]=...,
+ dt2: Optional[date]=...,
+ years: Optional[int]=..., months: Optional[int]=...,
+ days: Optional[int]=..., leapdays: Optional[int]=...,
+ weeks: Optional[int]=...,
+ hours: Optional[int]=..., minutes: Optional[int]=...,
+ seconds: Optional[int]=..., microseconds: Optional[int]=...,
+ year: Optional[int]=..., month: Optional[int]=...,
+ day: Optional[int]=...,
+ weekday: Optional[Union[int, weekday]]=...,
+ yearday: Optional[int]=...,
+ nlyearday: Optional[int]=...,
+ hour: Optional[int]=..., minute: Optional[int]=...,
+ second: Optional[int]=...,
+ microsecond: Optional[int]=...) -> None: ...
+
+ @property
+ def weeks(self) -> int: ...
+
+ @weeks.setter
+ def weeks(self, value: int) -> None: ...
+
+ def normalized(self) -> 'relativedelta': ...
+
+ def __add__(
+ self,
+ other: Union['relativedelta', timedelta, date, datetime]) -> 'relativedelta': ...
+
+ def __radd__(
+ self,
+ other: Any) -> 'relativedelta': ...
+
+ def __rsub__(
+ self,
+ other: Any) -> 'relativedelta': ...
+
+ def __sub__(self, other: 'relativedelta') -> 'relativedelta': ...
+
+ def __neg__(self) -> 'relativedelta': ...
+
+ def __bool__(self) -> bool: ...
+
+ def __nonzero__(self) -> bool: ...
+
+ def __mul__(self, other: float) -> 'relativedelta': ...
+
+ def __rmul__(self, other: float) -> 'relativedelta': ...
+
+ def __eq__(self, other) -> bool: ...
+
+ def __ne__(self, other: object) -> bool: ...
+
+ def __div__(self, other: float) -> 'relativedelta': ...
+
+ def __truediv__(self, other: float) -> 'relativedelta': ...
+
+ def __repr__(self) -> str: ...
diff --git a/typeshed/third_party/3/lxml/etree.pyi b/typeshed/third_party/3/lxml/etree.pyi
index d1004b0..dbf64db 100644
--- a/typeshed/third_party/3/lxml/etree.pyi
+++ b/typeshed/third_party/3/lxml/etree.pyi
@@ -3,7 +3,7 @@
# Any use of `Any` below means I couldn't figure out the type.
import typing
-from typing import Any, Dict, List, Tuple, Union
+from typing import Any, Dict, List, MutableMapping, Tuple, Union
from typing import SupportsBytes
@@ -21,6 +21,11 @@ class _Element:
def addprevious(self, element: '_Element') -> None:
pass
+ attrib = ... # type: MutableMapping[str, str]
+
+class ElementBase(_Element):
+ pass
+
class _ElementTree:
def write(self,
file: Union[AnyStr, typing.IO],
@@ -100,3 +105,57 @@ def parse(source: Union[AnyStr, typing.IO],
parser: XMLParser = ...,
base_url: AnyStr = ...) -> _ElementTree:
pass
+
+
+def fromstring(text: AnyStr,
+ parser: XMLParser = ...,
+ *,
+ base_url: AnyStr = ...) -> _Element: ...
+
+def tostring(element_or_tree: Union[_Element, _ElementTree],
+ encoding: Union[str, type] = ...,
+ method: str = ...,
+ xml_declaration: bool = ...,
+ pretty_print: bool = ...,
+ with_tail: bool = ...,
+ standalone: bool = ...,
+ doctype: str = ...,
+ exclusive: bool = ...,
+ with_comments: bool = ...,
+ inclusive_ns_prefixes: Any = ...) -> AnyStr: ...
+
+
+class _ErrorLog:
+ pass
+
+
+class Error(Exception):
+ pass
+
+class LxmlError(Error):
+ def __init__(self, message: Any, error_log: _ErrorLog = ...) -> None: ...
+ error_log = ... # type: _ErrorLog
+
+class DocumentInvalid(LxmlError):
+ pass
+
+class LxmlSyntaxError(LxmlError, SyntaxError):
+ pass
+
+class ParseError(LxmlSyntaxError):
+ pass
+
+class XMLSyntaxError(ParseError):
+ pass
+
+
+class _Validator:
+ pass
+
+class DTD(_Validator):
+ def __init__(self,
+ file: Union[AnyStr, typing.IO] = ...,
+ *,
+ external_id: Any = ...) -> None: ...
+
+ def assertValid(self, etree: _Element) -> None: ...
diff --git a/typeshed/third_party/3/lxml/objectify.pyi b/typeshed/third_party/3/lxml/objectify.pyi
new file mode 100644
index 0000000..74293c4
--- /dev/null
+++ b/typeshed/third_party/3/lxml/objectify.pyi
@@ -0,0 +1,13 @@
+# Hand-written stub, incomplete
+
+from typing import Union
+
+from lxml.etree import ElementBase, XMLParser
+
+class ObjectifiedElement(ElementBase):
+ pass
+
+def fromstring(text: Union[bytes, str],
+ parser: XMLParser = ...,
+ *,
+ base_url: Union[bytes, str] = ...) -> ObjectifiedElement: ...
diff --git a/typeshed/third_party/3/pkg_resources.pyi b/typeshed/third_party/3/pkg_resources.pyi
new file mode 100644
index 0000000..a58a0a1
--- /dev/null
+++ b/typeshed/third_party/3/pkg_resources.pyi
@@ -0,0 +1,310 @@
+# Stubs for pkg_resources (Python 3.4)
+
+from typing import (
+ Any, Callable, Dict, IO, Iterable, Generator, Optional, Sequence, Tuple,
+ Union,
+ TypeVar, overload,
+)
+import importlib.abc
+import sys
+import types
+import zipimport
+
+_T = TypeVar('_T')
+_NestedStr = Union[str, Iterable[Union[str, Iterable[Any]]]]
+_InstallerType = Callable[[Requirement], Optional[Distribution]]
+_EPDistType = Union[Distribution, Requirement, str]
+_MetadataType = Optional[IResourceProvider]
+_PkgReqType = Union[str, Requirement]
+_DistFinderType = Callable[[str, _Importer, bool],
+ Generator[Distribution, None, None]]
+_NSHandlerType = Callable[[_Importer, str, str, types.ModuleType], str]
+
+def declare_namespace(name: str) -> None: ...
+def fixup_namespace_packages(path_item: str) -> None: ...
+
+
+class WorkingSet:
+ entries = ... # type: List[str]
+ def __init__(self, entries: Optional[Iterable[str]] = ...) -> None: ...
+ def require(self, *requirements: _NestedStr) -> Sequence[Distribution]: ...
+ def run_script(self, requires: str, script_name: str) -> None: ...
+ def iter_entry_points(self, group: str, name: Optional[str] = ...) \
+ -> Generator[EntryPoint, None, None]: ...
+ def add_entry(self, entry: str) -> None: ...
+ def __contains__(self, dist: Distribution) -> bool: ...
+ def __iter__(self) -> Generator[Distribution, None, None]: ...
+ def find(self, req: Requirement) -> Optional[Distribution]: ...
+ def resolve(self, requirements: Sequence[Requirement],
+ env: Optional[Environment] = ...,
+ installer: Optional[_InstallerType] = ...) \
+ -> List[Distribution]: ...
+ def add(self, dist: Distribution, entry: Optional[str] = ...,
+ insert: bool = ..., replace: bool = ...) -> None: ...
+ def subscribe(self, callback: Callable[[Distribution], None]) -> None: ...
+ def find_plugins(self, plugin_env: Environment,
+ full_env: Optional[Environment] = ...,
+ fallback: bool = ...) \
+ -> Tuple[List[Distribution],
+ Dict[Distribution, Exception]]: ...
+
+working_set = ... # type: WorkingSet
+
+def require(*requirements: Union[str, Sequence[str]]) \
+ -> Sequence[Distribution]: ...
+def run_script(requires: str, script_name: str) -> None: ...
+def iter_entry_points(group: str, name: Optional[str] = ...) \
+ -> Generator[EntryPoint, None, None]: ...
+def add_activation_listener(callback: Callable[[Distribution], None]) \
+ -> None: ...
+
+
+class Environment:
+ def __init__(self, search_path: Optional[Sequence[str]] = ...,
+ platform: Optional[str] = ...,
+ python: Optional[str] = ...) -> None: ...
+ def __getitem__(self, project_name: str) -> List[Distribution]: ...
+ def __iter__(self) -> Generator[str, None, None]: ...
+ def add(self, dist: Distribution) -> None: ...
+ def remove(self, dist: Distribution) -> None: ...
+ def can_add(self, dist: Distribution) -> bool: ...
+ def __add__(self,
+ other: Union[Distribution, Environment]) -> Environment: ...
+ def __iadd__(self,
+ other: Union[Distribution, Environment]) -> Environment: ...
+ @overload
+ def best_match(self, req: Requirement, working_set: WorkingSet) -> Distribution: ...
+ @overload
+ def best_match(self, req: Requirement, working_set: WorkingSet,
+ installer: Callable[[Requirement], _T] = ...) -> _T: ...
+ @overload
+ def obtain(self, requirement: Requirement) -> None: ...
+ @overload
+ def obtain(self, requirement: Requirement,
+ installer: Callable[[Requirement], _T] = ...) -> _T: ...
+ def scan(self, search_path: Optional[Sequence[str]] = ...) -> None: ...
+
+
+def parse_requirements(strs: Union[str, Iterable[str]]) -> Generator[Requirement, None, None]: ...
+
+class Requirement:
+ project_name = ... # type: str
+ key = ... # type: str
+ extras = ... # type: Tuple[str, ...]
+ specs = ... # type: List[Tuple[str, str]]
+ @staticmethod
+ def parse(s: Union[str, Iterable[str]]) -> Requirement: ...
+ def __contains__(self,
+ item: Union[Distribution, str, Tuple[str, ...]]) \
+ -> bool: ...
+ def __eq__(self, other_requirement: Any) -> bool: ...
+
+
+
+def load_entry_point(dist: _EPDistType, group: str, name: str) -> None: ...
+def get_entry_info(dist: _EPDistType, group: str,
+ name: str) -> Optional[EntryPoint]: ...
+ at overload
+def get_entry_map(dist: _EPDistType) -> Dict[str, Dict[str, EntryPoint]]: ...
+ at overload
+def get_entry_map(dist: _EPDistType, group: str = ...) -> Dict[str, EntryPoint]: ...
+
+class EntryPoint:
+ name = ... # type: str
+ module_name = ... # type: str
+ attrs = ... # type: Tuple[str, ...]
+ extras = ... # type: Tuple[str, ...]
+ dist = ... # type: Optional[Distribution]
+ def __init__(self, name: str, module_name: str,
+ attrs: Tuple[str, ...] = ..., extras: Tuple[str, ...] = ...,
+ dist: Optional[Distribution] = ...) -> None: ...
+ @classmethod
+ def parse(cls, src: str, dist: Optional[Distribution] = ...) -> EntryPoint: ...
+ @classmethod
+ def parse_group(cls, group: str, lines: Union[str, Sequence[str]],
+ dist: Optional[Distribution] = ...) -> Dict[str, EntryPoint]: ...
+ @classmethod
+ def parse_map(cls, data: Union[Dict[str, Union[str, Sequence[str]]],
+ str, Sequence[str]],
+ dist: Optional[Distribution] = ...) -> Dict[str, EntryPoint]: ...
+ def load(self, require: bool = ..., env: Optional[Environment] = ...,
+ installer: Optional[_InstallerType] = ...) -> Any: ...
+ def require(self, env: Optional[Environment] = ...,
+ installer: Optional[_InstallerType] = ...) -> None: ...
+
+
+def find_distributions(path_item: str, only: bool = ...) \
+ -> Generator[Distribution, None, None]: ...
+def get_distribution(dist: Union[Requirement, str, Distribution]) -> Distribution: ...
+
+class Distribution(IResourceProvider, IMetadataProvider):
+ location = ... # type: str
+ project_name = ... # type: str
+ key = ... # type: str
+ extras = ... # type: List[str]
+ version = ... # type: str
+ parsed_version = ... # type: Tuple[str, ...]
+ py_version = ... # type: str
+ platform = ... # type: Optional[str]
+ precedence = ... # type: int
+ def __init__(self, location: Optional[str] = ...,
+ metadata: Optional[str] = ...,
+ project_name: Optional[str] = ...,
+ version: Optional[str] = ..., py_version: str = ...,
+ platform: Optional[str] = ...,
+ precedence: int = ...) -> None: ...
+ @classmethod
+ def from_location(cls, location: str, basename: str,
+ metadata: Optional[str] = ...,
+ **kw: Union[str, None, int]) -> Distribution: ...
+ @classmethod
+ def from_filename(cls, filename: str, metadata: Optional[str] = ...,
+ **kw: Union[str, None, int]) -> Distribution: ...
+ def activate(self, path: Optional[List[str]] = ...) -> None: ...
+ def as_requirement(self) -> Requirement: ...
+ def requires(self, extras: Tuple[str, ...] = ...) -> List[Requirement]: ...
+ def clone(self, **kw: Union[str, int, None]) -> Requirement: ...
+ def egg_name(self) -> str: ...
+ def __cmp__(self, other: Any) -> bool: ...
+ def get_entry_info(dist: _EPDistType, group: str,
+ name: str) -> Optional[EntryPoint]: ...
+ @overload
+ def get_entry_map(dist: _EPDistType) \
+ -> Dict[str, Dict[str, EntryPoint]]: ...
+ @overload
+ def get_entry_map(dist: _EPDistType, group: str = ...) \
+ -> Dict[str, EntryPoint]: ...
+ def load_entry_point(dist: _EPDistType, group: str, name: str) -> None: ...
+
+EGG_DIST = ... # type: int
+BINARY_DIST = ... # type: int
+SOURCE_DIST = ... # type: int
+CHECKOUT_DIST = ... # type: int
+DEVELOP_DIST = ... # type: int
+
+
+def resource_exists(package_or_requirement: _PkgReqType,
+ resource_name: str) -> bool: ...
+def resource_stream(package_or_requirement: _PkgReqType,
+ resource_name: str) -> IO[bytes]: ...
+def resource_string(package_or_requirement: _PkgReqType,
+ resource_name: str) -> str: ...
+def resource_isdir(package_or_requirement: _PkgReqType,
+ resource_name: str) -> bool: ...
+def resource_listdir(package_or_requirement: _PkgReqType,
+ resource_name: str) -> List[str]: ...
+
+def resource_filename(package_or_requirement: _PkgReqType,
+ resource_name: str) -> str: ...
+def set_extraction_path(path: str) -> None: ...
+def cleanup_resources(force: bool = ...) -> List[str]: ...
+
+class IResourceManager:
+ def resource_exists(self, package_or_requirement: _PkgReqType,
+ resource_name: str) -> bool: ...
+ def resource_stream(self, package_or_requirement: _PkgReqType,
+ resource_name: str) -> IO[bytes]: ...
+ def resource_string(self, package_or_requirement: _PkgReqType,
+ resource_name: str) -> str: ...
+ def resource_isdir(self, package_or_requirement: _PkgReqType,
+ resource_name: str) -> bool: ...
+ def resource_listdir(self, package_or_requirement: _PkgReqType,
+ resource_name: str) -> List[str]: ...
+ def resource_filename(self, package_or_requirement: _PkgReqType,
+ resource_name: str) -> str: ...
+ def set_extraction_path(self, path: str) -> None: ...
+ def cleanup_resources(self, force: bool = ...) -> List[str]: ...
+ def get_cache_path(self, archive_name: str,
+ names: Tuple[str, ...] = ...) -> str: ...
+ def extraction_error(self) -> None: ...
+ def postprocess(self, tempname: str, filename: str) -> None: ...
+
+
+ at overload
+def get_provider(package_or_requirement: str) -> IResourceProvider: ...
+ at overload
+def get_provider(package_or_requirement: Requirement) -> Distribution: ...
+
+class IMetadataProvider:
+ def has_metadata(name: str) -> bool: ...
+ def metadata_isdir(name: str) -> bool: ...
+ def metadata_listdir(name: str) -> List[str]: ...
+ def get_metadata(name: str) -> str: ...
+ def get_metadata_lines(name: str) -> Generator[List[str], None, None]: ...
+ def run_script(script_name: str, namespace: Dict[str, Any]) -> None: ...
+
+
+class ResolutionError(Exception): ...
+class DistributionNotFound(ResolutionError): ...
+class VersionConflict(ResolutionError): ...
+class UnknownExtra(ResolutionError): ...
+
+class ExtractionError(Exception):
+ manager = ... # type: IResourceManager
+ cache_path = ... # type: str
+ original_error = ... # type: Exception
+
+
+if sys.version_info >= (3, 3):
+ class _Importer(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): ...
+else:
+ class _Importer(importlib.abc.InspectLoader): ...
+
+def register_finder(importer_type: type,
+ distribution_finder: _DistFinderType) -> None : ...
+def register_loader_type(loader_type: type,
+ provider_factory: Callable[[types.ModuleType],
+ IResourceProvider]) \
+ -> None: ...
+def register_namespace_handler(importer_type: type,
+ namespace_handler: _NSHandlerType) -> None: ...
+
+
+class IResourceProvider(IMetadataProvider): ...
+
+
+class NullProvider: ...
+
+class EggProvider(NullProvider): ...
+
+class DefaultProvider(EggProvider): ...
+
+class PathMetadata(DefaultProvider, IResourceProvider):
+ def __init__(self, path: str, egg_info: str) -> None: ...
+
+class ZipProvider(EggProvider): ...
+
+class EggMetadata(ZipProvider, IResourceProvider):
+ def __init__(self, zipimporter: zipimport.zipimporter) -> None: ...
+
+class EmptyProvider(NullProvider): ...
+
+empty_provider = ... # type: EmptyProvider
+
+class FileMetadata(EmptyProvider, IResourceProvider):
+ def __init__(self, path_to_pkg_info: str) -> None: ...
+
+
+def parse_version(v: str) -> Tuple[str, ...]: ...
+def yield_lines(strs: _NestedStr) -> Generator[str, None, None]: ...
+def split_sections(strs: _NestedStr) \
+ -> Generator[Tuple[Optional[str], str], None, None]: ...
+def safe_name(name: str) -> str: ...
+def safe_version(version: str) -> str: ...
+def safe_extra(extra: str) -> str: ...
+def to_filename(name_or_version: str) -> str: ...
+
+
+def get_build_platform() -> str: ...
+def get_platform() -> str: ...
+def get_supported_platform() -> str: ...
+def compatible_platforms(provided: Optional[str],
+ required: Optional[str]) -> bool: ...
+def get_default_cache() -> str: ...
+
+
+def get_importer(path_item: str) -> _Importer: ...
+
+
+def ensure_directory(path: str) -> None: ...
+def normalize_path(filename: str) -> str: ...
diff --git a/typeshed/third_party/3/pkg_resources/__init__.pyi b/typeshed/third_party/3/pkg_resources/__init__.pyi
deleted file mode 100644
index ef58019..0000000
--- a/typeshed/third_party/3/pkg_resources/__init__.pyi
+++ /dev/null
@@ -1,508 +0,0 @@
-# Stubs for pkg_resources (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-# NOTE: Still a little bit incomplete.
-
-from typing import (Any, List, Callable, Union, Tuple, Iterator, Iterable,
- Dict, Optional, Pattern)
-import io
-from collections import namedtuple
-import zipfile
-
-from ._vendor.packaging import version
-from ._vendor.packaging.specifiers import SpecifierSet
-
-
-SetuptoolsVersionType = Union['SetuptoolsVersion', 'SetuptoolsLegacyVersion']
-StrOrSequenceOfLines = Union[str, Iterable[str]]
-
-PackageOrRequirementType = Union[str, 'Requirement']
-
-# TODO
-LoaderType = Any
-ModuleType = Any
-ProviderFactoryType = Callable[[ModuleType], 'IResourceProvider']
-
-# entry point funcs types
-EntryPointFuncsDist = Union['Distribution', 'Requirement', str]
-EntryPointFuncsGroup = Dict[str, 'EntryPoint']
-EntryPointFuncsMap = Dict[str, EntryPointFuncsGroup]
-
-OnChangeCallback = Callable[['Distribution'], None]
-InstallerCallback = Callable[['Requirement'], 'Distribution']
-FindPluginsOutput = Tuple[List['Distribution'], Dict['Distribution', 'ResolutionError']]
-
-ImporterClassType = Any
-FinderCallable = Callable[[ImporterClassType, str, bool], Iterator['Distribution']]
-ImporterType = Any
-NamespaceHandlerCallable = Callable[[ImporterType, str, str, ModuleType], str]
-
-EPAttrsType = Tuple[str, ...]
-EPExtrasType = Tuple[str, ...]
-
-require = ... # type: Optional[Callable[..., List[Distribution]]]
-working_set = ... # type: Optional[WorkingSet]
-
-class PEP440Warning(RuntimeWarning): ...
-
-class _SetuptoolsVersionMixin:
- def __hash__(self) -> int: ...
- def __lt__(self, other) -> bool: ...
- def __le__(self, other) -> bool: ...
- def __eq__(self, other) -> bool: ...
- def __ge__(self, other) -> bool: ...
- def __gt__(self, other) -> bool: ...
- def __ne__(self, other) -> bool: ...
- def __getitem__(self, key: Any) -> Any: ...
- def __iter__(self) -> Iterator[str]: ...
-
-
-class SetuptoolsVersion(_SetuptoolsVersionMixin, version.Version): ...
-class SetuptoolsLegacyVersion(_SetuptoolsVersionMixin, version.LegacyVersion): ...
-
-
-def parse_version(v: str) -> SetuptoolsVersionType: ...
-
-class ResolutionError(Exception): ...
-
-class VersionConflict(ResolutionError):
- @property
- def dist(self) -> Distribution: ...
- @property
- def req(self) -> Requirement: ...
- def report(self) -> str: ...
- # TODO: fill required_by
- def with_context(self, required_by) -> Union['VersionConflict', 'ContextualVersionConflict']: ...
-
-
-class ContextualVersionConflict(VersionConflict):
- @property
- # TODO: fill required_by
- def required_by(self): ...
-
-# TODO
-class DistributionNotFound(ResolutionError):
- @property
- def req(self) -> Requirement: ...
- @property
- def requirers(self): ...
- @property
- def requirers_str(self) -> str: ...
- def report(self) -> str: ...
-
-class UnknownExtra(ResolutionError): ...
-
-EGG_DIST = ... # type: int
-BINARY_DIST = ... # type: int
-SOURCE_DIST = ... # type: int
-CHECKOUT_DIST = ... # type: int
-DEVELOP_DIST = ... # type: int
-
-# TODO
-def register_loader_type(loader_type: LoaderType,
- provider_factory: ProviderFactoryType) -> None: ...
-def get_provider(moduleOrReq: PackageOrRequirementType) -> Union['IResourceProvider', 'Distribution']: ...
-
-get_platform = ... # type: Callable[[], str]
-
-def compatible_platforms(provided: Optional[str], required: Optional[str]) -> bool: ...
-def run_script(dist_spec, script_name: str) -> None: ...
-
-run_main = ... # type: Any
-
-def get_distribution(dist: EntryPointFuncsDist) -> 'Distribution': ...
-def load_entry_point(dist: EntryPointFuncsDist, group: str, name: str) -> 'EntryPoint': ...
-def get_entry_map(dist: EntryPointFuncsDist,
- group: Optional[str] = None) -> EntryPointFuncsMap: ...
-def get_entry_info(dist: EntryPointFuncsDist, group: str, name: str) -> Optional['EntryPoint']: ...
-
-# TODO
-class IMetadataProvider:
- def has_metadata(name): ...
- def get_metadata(name): ...
- def get_metadata_lines(name): ...
- def metadata_isdir(name): ...
- def metadata_listdir(name): ...
- def run_script(script_name, namespace): ...
-
-# TODO
-class IResourceProvider(IMetadataProvider):
- def get_resource_filename(manager, resource_name): ...
- def get_resource_stream(manager, resource_name): ...
- def get_resource_string(manager, resource_name): ...
- def has_resource(resource_name): ...
- def resource_isdir(resource_name): ...
- def resource_listdir(resource_name): ...
-
-class WorkingSet:
- entries = ... # type: List[str]
- entry_keys = ... # type: Dict[str, List[str]]
- by_key = ... # type: Dict[str, Distribution]
- callbacks = ... # type: List[OnChangeCallback]
-
- def __init__(self, entries: List[str] = None) -> None: ...
- def add_entry(self, entry: str) -> None: ...
- def __contains__(self, dist: Distribution) -> bool: ...
- def find(self, req: Requirement) -> Distribution: ...
- def iter_entry_points(self, group: str,
- name: str = None) -> Iterator[EntryPoint]: ...
- # TODO: add type RequirementsType and add here
- def run_script(self, requires, script_name: str) -> None: ...
- def __iter__(self) -> Iterator[Distribution]: ...
- def add(self, dist: Distribution,
- entry: str = None,
- insert: bool = ...,
- replace: bool = ...) -> None: ...
- def resolve(self, requirements: Iterable[Requirement],
- env: Environment = None,
- installer: Optional[InstallerCallback] = None,
- replace_conflicting: bool = ...) -> List[Distribution]: ...
- def find_plugins(self, plugin_env: Environment,
- full_env: Optional[Environment] = None,
- installer: Optional[InstallerCallback] = None,
- fallback: bool = ...) -> FindPluginsOutput: ...
- # TODO: check requirements type
- def require(self, *requirements: StrOrSequenceOfLines) -> List[Distribution]: ...
- def subscribe(self, callback: OnChangeCallback) -> None: ...
-
-class Environment:
- platform = ... # type: str
- python = ... # type: str
- def __init__(self, search_path: Iterable[str] = None,
- platform: str = ...,
- python: str = ...) -> None: ...
- def can_add(self, dist: Distribution) -> bool: ...
- def remove(self, dist: Distribution) -> None: ...
- def scan(self, search_path: Optional[Iterable[str]] = None) -> None: ...
- def __getitem__(self, project_name: str) -> List[Distribution]: ...
- def add(self, dist: Distribution) -> None: ...
- def best_match(self, req: Requirement,
- working_set: WorkingSet,
- installer: Optional[InstallerCallback] = None) -> Optional[Distribution]: ...
- def obtain(self, requirement: Requirement,
- installer: Optional[InstallerCallback] = None) -> Optional[Distribution]: ...
- def __iter__(self) -> Iterator[str]: ...
- def __iadd__(self, other: Union[Distribution, 'Environment']) -> 'Environment': ...
- def __add__(self, other: Union[Distribution, 'Environment']) -> 'Environment': ...
-
-AvailableDistributions = ... # type: Environment
-
-class ExtractionError(RuntimeError): ...
-
-class ResourceManager:
- extraction_path = ... # type: Any
- cached_files = ... # type: Any
- def __init__(self) -> None: ...
- def resource_exists(self, package_or_requirement: PackageOrRequirementType,
- resource_name: str) -> bool: ...
- def resource_isdir(self, package_or_requirement: PackageOrRequirementType,
- resource_name: str) -> bool: ...
- def resource_filename(self, package_or_requirement: PackageOrRequirementType,
- resource_name: str) -> str: ...
- # TODO: return type
- def resource_stream(self, package_or_requirement: PackageOrRequirementType,
- resource_name: str): ...
- # TODO: return type
- def resource_string(self, package_or_requirement: PackageOrRequirementType,
- resource_name: str): ...
- def resource_listdir(self, package_or_requirement: PackageOrRequirementType,
- resource_name: str) -> List[str]: ...
- def extraction_error(self) -> None: ...
- def get_cache_path(self, archive_name: str,
- names: Iterable[str] = ...) -> str: ...
- def postprocess(self, tempname: str, filename: str) -> None: ...
- def set_extraction_path(self, path: str) -> None: ...
- def cleanup_resources(self, force: bool = ...) -> List[str]: ...
-
-def get_default_cache() -> str: ...
-
-def safe_name(name: str) -> str: ...
-
-def safe_version(version: str) -> str: ...
-
-def safe_extra(extra: str) -> str: ...
-
-def to_filename(name: str) -> str: ...
-
-def invalid_marker(text: str) -> Union[SyntaxError, bool]: ...
-
-def evaluate_marker(text: str, extra=None) -> bool: ...
-
-
-class NullProvider:
- egg_name = ... # type: Optional[str]
- egg_info = ... # type: Optional[str]
- loader = ... # type: Optional[LoaderType]
- module_path = ... # type: Optional[str]
- # TODO: init param
- def __init__(self, module) -> None: ...
- def get_resource_filename(self, manager: ResourceManager, resource_name: str) -> str: ...
- # TODO: return type
- def get_resource_stream(self, manager: ResourceManager, resource_name: str) -> io.BytesIO: ...
- # TODO: return type
- def get_resource_string(self, manager: ResourceManager, resource_name: str): ...
- def has_resource(self, resource_name: str) -> bool: ...
- def has_metadata(self, name: str) -> bool: ...
- def get_metadata(self, name: str) -> str: ...
- def get_metadata_lines(self, name: str) -> Iterator[str]: ...
- def resource_isdir(self, resource_name: str) -> bool: ...
- def metadata_isdir(self, name: str) -> bool: ...
- def resource_listdir(self, resource_name: str) -> List[str]: ...
- def metadata_listdir(self, name: str) -> List[str]: ...
- def run_script(self, script_name: str, namespace: Dict[str, Any]) -> None: ...
-
-
-class EggProvider(NullProvider):
- # TODO: module type
- def __init__(self, module) -> None: ...
-
-
-class DefaultProvider(EggProvider):
- # TODO: return type
- def get_resource_stream(self, manager: ResourceManager, resource_name: str): ...
-
-
-class EmptyProvider(NullProvider):
- module_path = ... # type: Optional[str]
- def __init__(self) -> None: ...
-
-
-empty_provider = ... # type: EmptyProvider
-
-
-class ZipManifests(dict):
- @classmethod
- def build(cls, path): ...
- load = ... # type: Any
-
-
-class MemoizedZipManifests(ZipManifests): ...
-
-
-manifest_mod = namedtuple('manifest_mod', 'manifest mtime')
-def load(self, path): ...
-
-
-class ContextualZipFile(zipfile.ZipFile):
- def __enter__(self): ...
- def __exit__(self, type, value, traceback): ...
- def __new__(cls, *args, **kwargs): ...
-
-
-class ZipProvider(EggProvider):
- eagers = ... # type: Optional[List[str]]
-
- zip_pre = ... # type: str
-
- def __init__(self, module) -> None: ...
-
- @property
- def zipinfo(self): ...
-
- def get_resource_filename(self, manager: ResourceManager, resource_name: str) -> str: ...
-
-class FileMetadata(EmptyProvider):
- path = ... # type: Any
-
- def __init__(self, path) -> None: ...
-
- def has_metadata(self, name: str) -> bool: ...
- # TODO
- def get_metadata(self, name: str): ...
-
- def get_metadata_lines(self, name): ...
-
-
-class PathMetadata(DefaultProvider):
- module_path = ... # type: Optional[str]
-
- egg_info = ... # type: Optional[str]
-
- def __init__(self, path: str, egg_info: str) -> None: ...
-
-
-class EggMetadata(ZipProvider):
- zip_pre = ... # type: str
-
- loader = ... # type: Optional[LoaderType]
-
- module_path = ... # type: Optional[str]
-
- def __init__(self, importer: ImporterType) -> None: ...
-
-def register_finder(importer_type: ImporterClassType,
- distribution_finder: FinderCallable): ...
-
-def find_distributions(path_item: str,
- only: bool = ...) -> Iterator['Distribution']: ...
-
-def register_namespace_handler(importer_type: ImporterClassType,
- namespace_handler: NamespaceHandlerCallable): ...
-
-def declare_namespace(packageName: str) -> None: ...
-
-# TODO:
-def fixup_namespace_packages(path_item, parent=None): ...
-
-def normalize_path(filename: str) -> str: ...
-
-def yield_lines(strs: StrOrSequenceOfLines) -> Iterator[str]: ...
-
-class EntryPoint:
- name = ... # type: str
- module_name = ... # type: str
- attrs = ... # type: EPAttrsType
- extras = ... # type: EPExtrasType
- dist = ... # type: Optional['Distribution']
- def __init__(self, name: str, module_name: str,
- attrs: EPAttrsType=...,
- extras: EPExtrasType=...,
- dist: Optional['Distribution'] = None) -> None: ...
- def load(self,
- require: bool = ...,
- *args, **kwargs) -> Any: ...
- def resolve(self) -> Any: ...
- def require(self,
- env: Optional[Environment] = None,
- installer: Optional[InstallerCallback] = None) -> None: ...
- pattern = ... # type: Pattern
- @classmethod
- def parse(cls, src: str,
- dist: Optional['Distribution'] = None) -> 'EntryPoint': ...
- @classmethod
- def parse_group(cls, group: str, lines: StrOrSequenceOfLines,
- dist: Optional['Distribution'] = None) -> EntryPointFuncsGroup: ...
- @classmethod
- def parse_map(cls,
- data: Union[Dict[str, StrOrSequenceOfLines], StrOrSequenceOfLines],
- dist: Optional['Distribution'] = None) -> EntryPointFuncsMap: ...
-
-class Distribution:
- PKG_INFO = ... # type: str
- project_name = ... # type: str
- py_version = ... # type: str
- platform = ... # type: Optional[str]
- location = ... # type: str
- precedence = ... # type: int
-
- def __init__(self,
- location: Optional[str] = None,
- metadata: Optional[IResourceProvider] = None,
- project_name: Optional[str] = None,
- version: Optional[str] = None,
- py_version: str = ...,
- platform: Optional[str] = None,
- precedence: int = ...) -> None: ...
-
- @classmethod
- def from_location(cls,
- location: str,
- basename: str,
- metadata: Optional[IResourceProvider] = None,
- **kw) -> 'Distribution': ...
-
- # TODO: add exact tuple form
- @property
- def hashcmp(self) -> Tuple[SetuptoolsVersionType, int, str, str, str, str]: ...
- def __hash__(self) -> int: ...
- def __lt__(self, other: 'Distribution') -> bool: ...
- def __le__(self, other: 'Distribution') -> bool: ...
- def __gt__(self, other: 'Distribution') -> bool: ...
- def __ge__(self, other: 'Distribution') -> bool: ...
- def __eq__(self, other: Any) -> bool: ...
- def __ne__(self, other: Any) -> bool: ...
-
- @property
- def key(self) -> str: ...
-
- @property
- def parsed_version(self) -> SetuptoolsVersionType: ...
-
- @property
- def version(self) -> str: ...
-
- def requires(self,
- extras: Iterable[str] = ...) -> List[Requirement]: ...
-
- def activate(self,
- path: Optional[Iterable[str]] = None) -> None: ...
-
- def egg_name(self) -> str: ...
-
- def __getattr__(self, attr: str) -> Any: ...
-
- @classmethod
- def from_filename(cls, filename: str,
- metadata: Optional[IResourceProvider] = None, **kw) -> 'Distribution': ...
-
- def as_requirement(self) -> Requirement: ...
-
- def load_entry_point(self, group: str, name: str) -> Any: ...
-
- def get_entry_map(self,
- group: Optional[str] = None) -> EntryPointFuncsMap: ...
-
- def get_entry_info(self, group: str, name: str) -> Optional[EntryPoint]: ...
-
- def insert_on(self, path: List[str],
- loc: Optional[str] = None,
- replace: bool = ...) -> None: ...
-
- def check_version_conflict(self) -> None: ...
-
- def has_version(self) -> bool: ...
-
- def clone(self, **kw) -> 'Distribution': ...
-
- @property
- def extras(self) -> List[str]: ...
-
-
-class EggInfoDistribution(Distribution): ...
-
-
-class DistInfoDistribution(Distribution):
- PKG_INFO = ... # type: str
- EQEQ = ... # type: Pattern
-
-
-class RequirementParseError(ValueError): ...
-
-
-def parse_requirements(strs) -> Iterator['Requirement']: ...
-
-
-class Requirement:
- project_name = ... # type: str
- key = ... # type: str
- specifier = ... # type: SpecifierSet
- specs = ... # type: List[Tuple[str, str]]
- extras = ... # type: Tuple[str]
- hashCmp = ... # type: Tuple[str, SpecifierSet, frozenset]
-
- def __init__(self, project_name: str, specs: List[Tuple[str, str]],
- extras: Tuple[str]) -> None: ...
- def __eq__(self, other: Any) -> bool: ...
- def __ne__(self, other: Any) -> bool: ...
- def __contains__(self, item: Union[Distribution, str]) -> bool: ...
- def __hash__(self) -> int: ...
-
- @staticmethod
- def parse(s: StrOrSequenceOfLines) -> 'Requirement': ...
-
-def ensure_directory(path: str) -> None: ...
-
-ContentType = List[str]
-def split_sections(s) -> Iterator[Tuple[Optional[str], ContentType]]: ...
-
-# Names in __all__ with no definition:
-# add_activation_listener
-# cleanup_resources
-# iter_entry_points
-# resource_exists
-# resource_filename
-# resource_isdir
-# resource_listdir
-# resource_stream
-# resource_string
-# set_extraction_path
diff --git a/typeshed/third_party/3/pkg_resources/_vendor/packaging/__init__.pyi b/typeshed/third_party/3/pkg_resources/_vendor/packaging/__init__.pyi
deleted file mode 100644
index 6ccb56e..0000000
--- a/typeshed/third_party/3/pkg_resources/_vendor/packaging/__init__.pyi
+++ /dev/null
@@ -1,4 +0,0 @@
-# Stubs for packaging (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
diff --git a/typeshed/third_party/3/pkg_resources/_vendor/packaging/specifiers.pyi b/typeshed/third_party/3/pkg_resources/_vendor/packaging/specifiers.pyi
deleted file mode 100644
index df128e0..0000000
--- a/typeshed/third_party/3/pkg_resources/_vendor/packaging/specifiers.pyi
+++ /dev/null
@@ -1,58 +0,0 @@
-# Stubs for packaging.specifiers (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-import abc
-
-class InvalidSpecifier(ValueError): ...
-
-class BaseSpecifier:
- def __hash__(self): ...
- def __eq__(self, other): ...
- def __ne__(self, other): ...
- @abc.abstractproperty
- def prereleases(self): ...
- @prereleases.setter
- def prereleases(self, value): ...
- def contains(self, item, prereleases=None): ...
- def filter(self, iterable, prereleases=None): ...
-
-class _IndividualSpecifier(BaseSpecifier):
- def __init__(self, spec:str=..., prereleases=None) -> None: ...
- def __hash__(self): ...
- def __eq__(self, other): ...
- def __ne__(self, other): ...
- @property
- def operator(self): ...
- @property
- def version(self): ...
- @property
- def prereleases(self): ...
- @prereleases.setter
- def prereleases(self, value): ...
- def __contains__(self, item): ...
- def contains(self, item, prereleases=None): ...
- def filter(self, iterable, prereleases=None): ...
-
-class LegacySpecifier(_IndividualSpecifier): ...
-
-class Specifier(_IndividualSpecifier):
- @property
- def prereleases(self): ...
- @prereleases.setter
- def prereleases(self, value): ...
-
-class SpecifierSet(BaseSpecifier):
- def __init__(self, specifiers:str=..., prereleases=None) -> None: ...
- def __hash__(self): ...
- def __and__(self, other): ...
- def __eq__(self, other): ...
- def __ne__(self, other): ...
- def __len__(self): ...
- def __iter__(self): ...
- @property
- def prereleases(self): ...
- @prereleases.setter
- def prereleases(self, value): ...
- def __contains__(self, item): ...
- def contains(self, item, prereleases=None): ...
- def filter(self, iterable, prereleases=None): ...
diff --git a/typeshed/third_party/3/pkg_resources/_vendor/packaging/version.pyi b/typeshed/third_party/3/pkg_resources/_vendor/packaging/version.pyi
deleted file mode 100644
index 8f5cd41..0000000
--- a/typeshed/third_party/3/pkg_resources/_vendor/packaging/version.pyi
+++ /dev/null
@@ -1,49 +0,0 @@
-# Stubs for packaging.version (Python 3.5)
-#
-# NOTE: This dynamically typed stub was automatically generated by stubgen.
-
-from typing import Any
-from collections import namedtuple
-
-_Version = namedtuple('_Version', ['epoch', 'release', 'dev', 'pre', 'post', 'local'])
-
-def parse(version): ...
-
-class InvalidVersion(ValueError): ...
-
-class _BaseVersion:
- def __hash__(self): ...
- def __lt__(self, other): ...
- def __le__(self, other): ...
- def __eq__(self, other): ...
- def __ge__(self, other): ...
- def __gt__(self, other): ...
- def __ne__(self, other): ...
-
-class LegacyVersion(_BaseVersion):
- def __init__(self, version): ...
- @property
- def public(self): ...
- @property
- def base_version(self): ...
- @property
- def local(self): ...
- @property
- def is_prerelease(self): ...
- @property
- def is_postrelease(self): ...
-
-VERSION_PATTERN = ... # type: Any
-
-class Version(_BaseVersion):
- def __init__(self, version): ...
- @property
- def public(self): ...
- @property
- def base_version(self): ...
- @property
- def local(self): ...
- @property
- def is_prerelease(self): ...
- @property
- def is_postrelease(self): ...
--
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