Merge pull request #9354 from jdufresne/super

Use short Python3 super() syntax
This commit is contained in:
Pradyun Gedam 2020-12-25 19:18:28 +00:00 committed by GitHub
commit f91ba6b348
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 64 additions and 81 deletions

View File

@ -46,7 +46,7 @@ class Cache(object):
def __init__(self, cache_dir, format_control, allowed_formats):
# type: (str, FormatControl, Set[str]) -> None
super(Cache, self).__init__()
super().__init__()
assert not cache_dir or os.path.isabs(cache_dir)
self.cache_dir = cache_dir or None
self.format_control = format_control
@ -175,9 +175,7 @@ class SimpleWheelCache(Cache):
def __init__(self, cache_dir, format_control):
# type: (str, FormatControl) -> None
super(SimpleWheelCache, self).__init__(
cache_dir, format_control, {"binary"}
)
super().__init__(cache_dir, format_control, {"binary"})
def get_path_for_link_legacy(self, link):
# type: (Link) -> str
@ -262,9 +260,7 @@ class EphemWheelCache(SimpleWheelCache):
globally_managed=True,
)
super(EphemWheelCache, self).__init__(
self._temp_dir.path, format_control
)
super().__init__(self._temp_dir.path, format_control)
class CacheEntry(object):
@ -286,9 +282,7 @@ class WheelCache(Cache):
def __init__(self, cache_dir, format_control):
# type: (str, FormatControl) -> None
super(WheelCache, self).__init__(
cache_dir, format_control, {'binary'}
)
super().__init__(cache_dir, format_control, {'binary'})
self._wheel_cache = SimpleWheelCache(cache_dir, format_control)
self._ephem_cache = EphemWheelCache(format_control)

View File

@ -52,7 +52,7 @@ class Command(CommandContextMixIn):
def __init__(self, name, summary, isolated=False):
# type: (str, str, bool) -> None
super(Command, self).__init__()
super().__init__()
parser_kw = {
'usage': self.usage,
'prog': '{} {}'.format(get_prog(), name),

View File

@ -13,7 +13,7 @@ if MYPY_CHECK_RUNNING:
class CommandContextMixIn(object):
def __init__(self):
# type: () -> None
super(CommandContextMixIn, self).__init__()
super().__init__()
self._in_main_context = False
self._main_context = ExitStack()

View File

@ -27,7 +27,7 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
kwargs['max_help_position'] = 30
kwargs['indent_increment'] = 1
kwargs['width'] = shutil.get_terminal_size()[0] - 2
optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs)
super().__init__(*args, **kwargs)
def format_option_strings(self, option):
return self._format_option_strings(option)
@ -113,7 +113,7 @@ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
if self.parser is not None:
self.parser._update_defaults(self.parser.defaults)
default_values = self.parser.defaults.get(option.dest)
help_text = optparse.IndentedHelpFormatter.expand_default(self, option)
help_text = super().expand_default(option)
if default_values and option.metavar == 'URL':
if isinstance(default_values, str):
@ -162,7 +162,7 @@ class ConfigOptionParser(CustomOptionParser):
self.config = Configuration(isolated)
assert self.name
optparse.OptionParser.__init__(self, *args, **kwargs)
super().__init__(*args, **kwargs)
def check_default(self, option, key, val):
try:

View File

@ -76,10 +76,7 @@ class InterruptibleMixin(object):
Save the original SIGINT handler for later.
"""
# https://github.com/python/mypy/issues/5887
super(InterruptibleMixin, self).__init__( # type: ignore
*args,
**kwargs
)
super().__init__(*args, **kwargs) # type: ignore
self.original_handler = signal(SIGINT, self.handle_sigint)
@ -99,7 +96,7 @@ class InterruptibleMixin(object):
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super(InterruptibleMixin, self).finish() # type: ignore
super().finish() # type: ignore
signal(SIGINT, self.original_handler)
def handle_sigint(self, signum, frame): # type: ignore
@ -133,10 +130,7 @@ class DownloadProgressMixin(object):
def __init__(self, *args, **kwargs):
# type: (List[Any], Dict[Any, Any]) -> None
# https://github.com/python/mypy/issues/5887
super(DownloadProgressMixin, self).__init__( # type: ignore
*args,
**kwargs
)
super().__init__(*args, **kwargs) # type: ignore
self.message = (" " * (
get_indentation() + 2
)) + self.message # type: str
@ -185,7 +179,7 @@ class WindowsMixin(object):
self.hide_cursor = False
# https://github.com/python/mypy/issues/5887
super(WindowsMixin, self).__init__(*args, **kwargs) # type: ignore
super().__init__(*args, **kwargs) # type: ignore
# Check if we are running on Windows and we have the colorama module,
# if we do then wrap our file with it.

View File

@ -51,7 +51,7 @@ class SessionCommandMixin(CommandContextMixIn):
"""
def __init__(self):
# type: () -> None
super(SessionCommandMixin, self).__init__()
super().__init__()
self._session = None # Optional[PipSession]
@classmethod
@ -190,7 +190,7 @@ class RequirementCommand(IndexGroupCommand):
def __init__(self, *args, **kw):
# type: (Any, Any) -> None
super(RequirementCommand, self).__init__(*args, **kw)
super().__init__(*args, **kw)
self.cmd_opts.add_option(cmdoptions.no_clean())

View File

@ -110,7 +110,7 @@ class Configuration(object):
def __init__(self, isolated, load_only=None):
# type: (bool, Optional[Kind]) -> None
super(Configuration, self).__init__()
super().__init__()
if load_only is not None and load_only not in VALID_LOAD_ONLY:
raise ConfigurationError(

View File

@ -28,7 +28,7 @@ class AbstractDistribution(object, metaclass=abc.ABCMeta):
"""
def __init__(self, req):
# type: (InstallRequirement) -> None
super(AbstractDistribution, self).__init__()
super().__init__()
self.req = req
@abc.abstractmethod

View File

@ -106,8 +106,7 @@ class NetworkConnectionError(PipError):
if (self.response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(NetworkConnectionError, self).__init__(
error_msg, response, request)
super().__init__(error_msg, response, request)
def __str__(self):
# type: () -> str
@ -357,7 +356,7 @@ class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
def __init__(self, reason="could not be loaded", fname=None, error=None):
# type: (str, Optional[str], Optional[configparser.Error]) -> None
super(ConfigurationFileCouldNotBeLoaded, self).__init__(error)
super().__init__(error)
self.reason = reason
self.fname = fname
self.error = error

View File

@ -68,7 +68,7 @@ def _match_vcs_scheme(url):
class _NotHTML(Exception):
def __init__(self, content_type, request_desc):
# type: (str, str) -> None
super(_NotHTML, self).__init__(content_type, request_desc)
super().__init__(content_type, request_desc)
self.content_type = content_type
self.request_desc = request_desc

View File

@ -21,7 +21,7 @@ class InstallationCandidate(KeyBasedCompareMixin):
self.version = parse_version(version) # type: _BaseVersion
self.link = link
super(InstallationCandidate, self).__init__(
super().__init__(
key=(self.name, self.version, self.link),
defining_class=InstallationCandidate
)

View File

@ -10,7 +10,7 @@ class PackageIndex(object):
def __init__(self, url, file_storage_domain):
# type: (str, str) -> None
super(PackageIndex, self).__init__()
super().__init__()
self.url = url
self.netloc = urllib_parse.urlsplit(url).netloc
self.simple_url = self._url_for_path('simple')

View File

@ -76,7 +76,7 @@ class Link(KeyBasedCompareMixin):
self.requires_python = requires_python if requires_python else None
self.yanked_reason = yanked_reason
super(Link, self).__init__(key=url, defining_class=Link)
super().__init__(key=url, defining_class=Link)
self.cache_link_parsing = cache_link_parsing

View File

@ -42,7 +42,7 @@ class SafeFileCache(BaseCache):
def __init__(self, directory):
# type: (str) -> None
assert directory is not None, "Cache directory must not be None."
super(SafeFileCache, self).__init__()
super().__init__()
self.directory = directory
def _get_cache_path(self, name):

View File

@ -211,17 +211,13 @@ class LocalFSAdapter(BaseAdapter):
class InsecureHTTPAdapter(HTTPAdapter):
def cert_verify(self, conn, url, verify, cert):
super(InsecureHTTPAdapter, self).cert_verify(
conn=conn, url=url, verify=False, cert=cert
)
super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
class InsecureCacheControlAdapter(CacheControlAdapter):
def cert_verify(self, conn, url, verify, cert):
super(InsecureCacheControlAdapter, self).cert_verify(
conn=conn, url=url, verify=False, cert=cert
)
super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
class PipSession(requests.Session):
@ -238,7 +234,7 @@ class PipSession(requests.Session):
trusted_hosts = kwargs.pop("trusted_hosts", []) # type: List[str]
index_urls = kwargs.pop("index_urls", None)
super(PipSession, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
# Namespace the attribute with "pip_" just in case to prevent
# possible conflicts with the base class.
@ -425,4 +421,4 @@ class PipSession(requests.Session):
kwargs.setdefault("timeout", self.timeout)
# Dispatch the actual request
return super(PipSession, self).request(method, url, *args, **kwargs)
return super().request(method, url, *args, **kwargs)

View File

@ -28,7 +28,7 @@ class PipXmlrpcTransport(xmlrpc_client.Transport):
def __init__(self, index_url, session, use_datetime=False):
# type: (str, PipSession, bool) -> None
xmlrpc_client.Transport.__init__(self, use_datetime)
super().__init__(use_datetime)
index_parts = urllib_parse.urlparse(index_url)
self._scheme = index_parts.scheme
self._session = session

View File

@ -449,7 +449,7 @@ class ScriptFile(object):
class MissingCallableSuffix(InstallationError):
def __init__(self, entry_point):
# type: (str) -> None
super(MissingCallableSuffix, self).__init__(
super().__init__(
"Invalid script entry point: {} - A callable "
"suffix is required. Cf https://packaging.python.org/"
"specifications/entry-points/#use-for-scripts for more "
@ -468,7 +468,7 @@ class PipScriptMaker(ScriptMaker):
def make(self, specification, options=None):
# type: (str, Dict[str, Any]) -> List[str]
_raise_for_invalid_entrypoint(specification)
return super(PipScriptMaker, self).make(specification, options)
return super().make(specification, options)
def _install_wheel(

View File

@ -298,7 +298,7 @@ class RequirementPreparer(object):
lazy_wheel, # type: bool
):
# type: (...) -> None
super(RequirementPreparer, self).__init__()
super().__init__()
self.src_dir = src_dir
self.build_dir = build_dir

View File

@ -124,7 +124,7 @@ class Resolver(BaseResolver):
py_version_info=None, # type: Optional[Tuple[int, ...]]
):
# type: (...) -> None
super(Resolver, self).__init__()
super().__init__()
assert upgrade_strategy in self._allowed_strategies
if py_version_info is None:

View File

@ -304,7 +304,7 @@ class LinkCandidate(_InstallRequirementBackedCandidate):
template.link is template.original_link):
ireq.original_link_is_in_wheel_cache = True
super(LinkCandidate, self).__init__(
super().__init__(
link=link,
source_link=source_link,
ireq=ireq,
@ -332,7 +332,7 @@ class EditableCandidate(_InstallRequirementBackedCandidate):
version=None, # type: Optional[_BaseVersion]
):
# type: (...) -> None
super(EditableCandidate, self).__init__(
super().__init__(
link=link,
source_link=link,
ireq=make_install_req_from_editable(link, template),

View File

@ -57,7 +57,7 @@ class Resolver(BaseResolver):
upgrade_strategy, # type: str
py_version_info=None, # type: Optional[Tuple[int, ...]]
):
super(Resolver, self).__init__()
super().__init__()
assert upgrade_strategy in self._allowed_strategies
self.factory = Factory(

View File

@ -153,7 +153,7 @@ class MissingHashes(Hashes):
"""Don't offer the ``hashes`` kwarg."""
# Pass our favorite hash in to generate a "gotten hash". With the
# empty list, it will never match, so an error will always raise.
super(MissingHashes, self).__init__(hashes={FAVORITE_HASH: []})
super().__init__(hashes={FAVORITE_HASH: []})
def _raise(self, gots):
# type: (Dict[str, _Hash]) -> NoReturn

View File

@ -110,7 +110,7 @@ class IndentingFormatter(logging.Formatter):
with their record's timestamp.
"""
self.add_timestamp = kwargs.pop("add_timestamp", False)
super(IndentingFormatter, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def get_message_start(self, formatted, levelno):
"""
@ -133,7 +133,7 @@ class IndentingFormatter(logging.Formatter):
Calls the standard formatter, but will indent all of the log message
lines by our current indentation level.
"""
formatted = super(IndentingFormatter, self).format(record)
formatted = super().format(record)
message_start = self.get_message_start(formatted, record.levelno)
formatted = message_start + formatted
@ -169,7 +169,7 @@ class ColorizedStreamHandler(logging.StreamHandler):
COLORS = []
def __init__(self, stream=None, no_color=None):
logging.StreamHandler.__init__(self, stream)
super().__init__(stream)
self._no_color = no_color
if WINDOWS and colorama:
@ -228,7 +228,7 @@ class ColorizedStreamHandler(logging.StreamHandler):
_is_broken_pipe_error(exc_class, exc)):
raise BrokenStdoutLoggingError()
return super(ColorizedStreamHandler, self).handleError(record)
return super().handleError(record)
class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):
@ -256,7 +256,7 @@ class ExcludeLoggerFilter(Filter):
def filter(self, record):
# The base Filter class allows only records from a logger (or its
# children).
return not super(ExcludeLoggerFilter, self).filter(record)
return not super().filter(record)
def setup_logging(verbosity, no_color, user_log_file):

View File

@ -121,7 +121,7 @@ class TempDirectory(object):
kind="temp", # type: str
globally_managed=False, # type: bool
):
super(TempDirectory, self).__init__()
super().__init__()
if delete is _default:
if path is not None:
@ -231,7 +231,7 @@ class AdjacentTempDirectory(TempDirectory):
def __init__(self, original, delete=None):
# type: (str, Optional[bool]) -> None
self.original = original.rstrip('/\\')
super(AdjacentTempDirectory, self).__init__(delete=delete)
super().__init__(delete=delete)
@classmethod
def _generate_names(cls, name):

View File

@ -32,13 +32,13 @@ class WheelMetadata(DictMetadata):
"""
def __init__(self, metadata, wheel_name):
# type: (Dict[str, bytes], str) -> None
super(WheelMetadata, self).__init__(metadata)
super().__init__(metadata)
self._wheel_name = wheel_name
def get_metadata(self, name):
# type: (str) -> str
try:
return super(WheelMetadata, self).get_metadata(name)
return super().get_metadata(name)
except UnicodeDecodeError as e:
# Augment the default error with the origin of the file.
raise UnsupportedWheel(

View File

@ -31,7 +31,7 @@ class Bazaar(VersionControl):
)
def __init__(self, *args, **kwargs):
super(Bazaar, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
# This is only needed for python <2.7.5
# Register lp but do not expose as a scheme to support bzr+lp.
if getattr(urllib_parse, 'uses_fragment', None):
@ -82,7 +82,7 @@ class Bazaar(VersionControl):
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
# hotfix the URL scheme after removing bzr+ from bzr+ssh:// readd it
url, rev, user_pass = super(Bazaar, cls).get_url_rev_and_auth(url)
url, rev, user_pass = super().get_url_rev_and_auth(url)
if url.startswith('ssh://'):
url = 'bzr+' + url
return url, rev, user_pass

View File

@ -393,10 +393,10 @@ class Git(VersionControl):
if '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
url, rev, user_pass = super().get_url_rev_and_auth(url)
url = url.replace('ssh://', '')
else:
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
url, rev, user_pass = super().get_url_rev_and_auth(url)
return url, rev, user_pass
@ -411,7 +411,7 @@ class Git(VersionControl):
@classmethod
def get_repository_root(cls, location):
loc = super(Git, cls).get_repository_root(location)
loc = super().get_repository_root(location)
if loc:
return loc
try:

View File

@ -134,7 +134,7 @@ class Mercurial(VersionControl):
@classmethod
def get_repository_root(cls, location):
loc = super(Mercurial, cls).get_repository_root(location)
loc = super().get_repository_root(location)
if loc:
return loc
try:

View File

@ -84,7 +84,7 @@ class Subversion(VersionControl):
if scheme == 'ssh':
# The --username and --password options can't be used for
# svn+ssh URLs, so keep the auth information in the URL.
return super(Subversion, cls).get_netloc_and_auth(netloc, scheme)
return super().get_netloc_and_auth(netloc, scheme)
return split_auth_from_netloc(netloc)
@ -92,7 +92,7 @@ class Subversion(VersionControl):
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
# hotfix the URL scheme after removing svn+ from svn+ssh:// readd it
url, rev, user_pass = super(Subversion, cls).get_url_rev_and_auth(url)
url, rev, user_pass = super().get_url_rev_and_auth(url)
if url.startswith('ssh://'):
url = 'svn+' + url
return url, rev, user_pass
@ -197,7 +197,7 @@ class Subversion(VersionControl):
# Empty tuple: Could not parse version.
self._vcs_version = None # type: Optional[Tuple[int, ...]]
super(Subversion, self).__init__()
super().__init__()
def call_vcs_version(self):
# type: () -> Tuple[int, ...]

View File

@ -287,7 +287,7 @@ class VcsSupport(object):
# systems
urllib_parse.uses_netloc.extend(self.schemes)
urllib_parse.uses_fragment.extend(self.schemes)
super(VcsSupport, self).__init__()
super().__init__()
def __iter__(self):
# type: () -> Iterator[str]

View File

@ -506,7 +506,7 @@ class PipTestEnvironment(TestFileEnvironment):
self.pip_expect_warning = kwargs.pop('pip_expect_warning', None)
# Call the TestFileEnvironment __init__
super(PipTestEnvironment, self).__init__(base_path, *args, **kwargs)
super().__init__(base_path, *args, **kwargs)
# Expand our absolute path directories into relative
for name in ["base", "venv", "bin", "lib", "site_packages",
@ -531,7 +531,7 @@ class PipTestEnvironment(TestFileEnvironment):
if fn.endswith('__pycache__') or fn.endswith(".pyc"):
result = True
else:
result = super(PipTestEnvironment, self)._ignore_file(fn)
result = super()._ignore_file(fn)
return result
def _find_traverse(self, path, result):
@ -542,7 +542,7 @@ class PipTestEnvironment(TestFileEnvironment):
if not self.temp_path or path != 'tmp':
result[path] = FoundDir(self.base_path, path)
else:
super(PipTestEnvironment, self)._find_traverse(path, result)
super()._find_traverse(path, result)
def run(self, *args, **kw):
"""
@ -620,7 +620,7 @@ class PipTestEnvironment(TestFileEnvironment):
# Pass expect_stderr=True to allow any stderr. We do this because
# we do our checking of stderr further on in check_stderr().
kw['expect_stderr'] = True
result = super(PipTestEnvironment, self).run(cwd=cwd, *args, **kw)
result = super().run(cwd=cwd, *args, **kw)
if expect_error and not allow_error:
if result.returncode == 0:

View File

@ -56,7 +56,7 @@ else:
class _RequestHandler(WSGIRequestHandler):
def make_environ(self):
environ = super(_RequestHandler, self).make_environ()
environ = super().make_environ()
# From pallets/werkzeug#1469, will probably be in release after
# 0.16.0.

View File

@ -27,11 +27,11 @@ class FakeCommand(Command):
raise SystemExit(1)
self.run_func = run_func
super(FakeCommand, self).__init__(self._name, self._name)
super().__init__(self._name, self._name)
def main(self, args):
args.append("--disable-pip-version-check")
return super(FakeCommand, self).main(args)
return super().main(args)
def run(self, options, args):
logging.getLogger("pip.tests").info("fake")

View File

@ -8,7 +8,7 @@ from pip._internal.models.format_control import FormatControl
class SimpleCommand(Command):
def __init__(self):
super(SimpleCommand, self).__init__('fake', 'fake summary')
super().__init__('fake', 'fake summary')
def add_options(self):
self.cmd_opts.add_option(cmdoptions.no_binary())