Skip to content

Use zero-argument super() #1726

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Use zero-argument super() where applicable
This replaces 2-argument super(...) calls with zero-argument
super() calls, where doing so preserves the exact semantics. This
turns out to be everywhere in the actual code (now all uses of the
super builtin are calls to it with zero arguments), and also in
most places code was discussed in comments.

The single exception, occurring in comments (technically a string
literal, but being used as a comment), appears in
git.objects.util.TraversableIterableObj, where super(Commit, self),
rather than super(TraversableIterableObj, self) which would have
the same meaning as super(), is shown. It may be that this should
be changed, but such a revision would not signify identical
semantics, and may require other changes to preserve or recover
clarity or documentary accuracy.
  • Loading branch information
EliahKagan committed Nov 2, 2023
commit a47e46d7512c595dc230b2caeedb4ba615fadfa9
4 changes: 2 additions & 2 deletions git/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ def __init__(self, working_dir: Union[None, PathLike] = None):
It is meant to be the working tree directory if available, or the
``.git`` directory in case of bare repositories.
"""
super(Git, self).__init__()
super().__init__()
self._working_dir = expand_path(working_dir)
self._git_options: Union[List[str], Tuple[str, ...]] = ()
self._persistent_git_options: List[str] = []
Expand Down Expand Up @@ -765,7 +765,7 @@ def _set_cache_(self, attr: str) -> None:
tuple(int(n) for n in version_numbers.split(".")[:4] if n.isdigit()),
)
else:
super(Git, self)._set_cache_(attr)
super()._set_cache_(attr)
# END handle version info

@property
Expand Down
30 changes: 15 additions & 15 deletions git/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def __new__(cls, name: str, bases: Tuple, clsdict: Dict[str, Any]) -> "MetaParse
# END for each base
# END if mutating methods configuration is set

new_type = super(MetaParserBuilder, cls).__new__(cls, name, bases, clsdict)
new_type = super().__new__(cls, name, bases, clsdict)
return new_type


Expand Down Expand Up @@ -178,7 +178,7 @@ def __del__(self) -> None:
def __getattr__(self, attr: str) -> Any:
if attr in self._valid_attrs_:
return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs)
return super(SectionConstraint, self).__getattribute__(attr)
return super().__getattribute__(attr)

def _call_config(self, method: str, *args: Any, **kwargs: Any) -> Any:
"""Call the configuration at the given method which must take a section name
Expand Down Expand Up @@ -207,36 +207,36 @@ class _OMD(OrderedDict_OMD):
"""Ordered multi-dict."""

def __setitem__(self, key: str, value: _T) -> None:
super(_OMD, self).__setitem__(key, [value])
super().__setitem__(key, [value])

def add(self, key: str, value: Any) -> None:
if key not in self:
super(_OMD, self).__setitem__(key, [value])
super().__setitem__(key, [value])
return None
super(_OMD, self).__getitem__(key).append(value)
super().__getitem__(key).append(value)

def setall(self, key: str, values: List[_T]) -> None:
super(_OMD, self).__setitem__(key, values)
super().__setitem__(key, values)

def __getitem__(self, key: str) -> Any:
return super(_OMD, self).__getitem__(key)[-1]
return super().__getitem__(key)[-1]

def getlast(self, key: str) -> Any:
return super(_OMD, self).__getitem__(key)[-1]
return super().__getitem__(key)[-1]

def setlast(self, key: str, value: Any) -> None:
if key not in self:
super(_OMD, self).__setitem__(key, [value])
super().__setitem__(key, [value])
return

prior = super(_OMD, self).__getitem__(key)
prior = super().__getitem__(key)
prior[-1] = value

def get(self, key: str, default: Union[_T, None] = None) -> Union[_T, None]:
return super(_OMD, self).get(key, [default])[-1]
return super().get(key, [default])[-1]

def getall(self, key: str) -> List[_T]:
return super(_OMD, self).__getitem__(key)
return super().__getitem__(key)

def items(self) -> List[Tuple[str, _T]]: # type: ignore[override]
"""List of (key, last value for key)."""
Expand Down Expand Up @@ -680,7 +680,7 @@ def write_section(name: str, section_dict: _OMD) -> None:

def items(self, section_name: str) -> List[Tuple[str, str]]: # type: ignore[override]
""":return: list((option, value), ...) pairs of all items in the given section"""
return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != "__name__"]
return [(k, v) for k, v in super().items(section_name) if k != "__name__"]

def items_all(self, section_name: str) -> List[Tuple[str, List[str]]]:
""":return: list((option, [values...]), ...) pairs of all items in the given section"""
Expand Down Expand Up @@ -748,7 +748,7 @@ def _assure_writable(self, method_name: str) -> None:

def add_section(self, section: str) -> None:
"""Assures added options will stay in order"""
return super(GitConfigParser, self).add_section(section)
return super().add_section(section)

@property
def read_only(self) -> bool:
Expand Down Expand Up @@ -899,7 +899,7 @@ def rename_section(self, section: str, new_name: str) -> "GitConfigParser":
if self.has_section(new_name):
raise ValueError("Destination section '%s' already exists" % new_name)

super(GitConfigParser, self).add_section(new_name)
super().add_section(new_name)
new_section = self._sections[new_name]
for k, vs in self.items_all(section):
new_section.setall(k, vs)
Expand Down
2 changes: 1 addition & 1 deletion git/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class GitCmdObjectDB(LooseObjectDB):

def __init__(self, root_path: PathLike, git: "Git") -> None:
"""Initialize this instance with the root and a git command."""
super(GitCmdObjectDB, self).__init__(root_path)
super().__init__(root_path)
self._git = git

def info(self, binsha: bytes) -> OInfo:
Expand Down
6 changes: 3 additions & 3 deletions git/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ class GitCommandNotFound(CommandError):
the GIT_PYTHON_GIT_EXECUTABLE environment variable."""

def __init__(self, command: Union[List[str], Tuple[str], str], cause: Union[str, Exception]) -> None:
super(GitCommandNotFound, self).__init__(command, cause)
super().__init__(command, cause)
self._msg = "Cmd('%s') not found%s"


Expand All @@ -151,7 +151,7 @@ def __init__(
stderr: Union[bytes, str, None] = None,
stdout: Union[bytes, str, None] = None,
) -> None:
super(GitCommandError, self).__init__(command, status, stderr, stdout)
super().__init__(command, status, stderr, stdout)


class CheckoutError(GitError):
Expand Down Expand Up @@ -207,7 +207,7 @@ def __init__(
stderr: Union[bytes, str, None] = None,
stdout: Union[bytes, str, None] = None,
) -> None:
super(HookExecutionError, self).__init__(command, status, stderr, stdout)
super().__init__(command, status, stderr, stdout)
self._msg = "Hook('%s') failed%s"


Expand Down
4 changes: 2 additions & 2 deletions git/index/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def _set_cache_(self, attr: str) -> None:

self._deserialize(stream)
else:
super(IndexFile, self)._set_cache_(attr)
super()._set_cache_(attr)

def _index_path(self) -> PathLike:
if self.repo.git_dir:
Expand Down Expand Up @@ -1425,4 +1425,4 @@ def diff(
raise ValueError("other must be None, Diffable.Index, a Tree or Commit, was %r" % other)

# Diff against working copy - can be handled by superclass natively.
return super(IndexFile, self).diff(other, paths, create_patch, **kwargs)
return super().diff(other, paths, create_patch, **kwargs)
8 changes: 4 additions & 4 deletions git/objects/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(self, repo: "Repo", binsha: bytes):

:param binsha: 20 byte SHA1
"""
super(Object, self).__init__()
super().__init__()
self.repo = repo
self.binsha = binsha
assert len(binsha) == 20, "Require 20 byte binary sha, got %r, len = %i" % (
Expand Down Expand Up @@ -108,7 +108,7 @@ def _set_cache_(self, attr: str) -> None:
self.size = oinfo.size # type: int
# assert oinfo.type == self.type, _assertion_msg_format % (self.binsha, oinfo.type, self.type)
else:
super(Object, self)._set_cache_(attr)
super()._set_cache_(attr)

def __eq__(self, other: Any) -> bool:
""":return: True if the objects have the same SHA1"""
Expand Down Expand Up @@ -190,7 +190,7 @@ def __init__(
Path may not be set if the index object has been created directly, as it
cannot be retrieved without knowing the parent tree.
"""
super(IndexObject, self).__init__(repo, binsha)
super().__init__(repo, binsha)
if mode is not None:
self.mode = mode
if path is not None:
Expand All @@ -212,7 +212,7 @@ def _set_cache_(self, attr: str) -> None:
% (attr, type(self).__name__)
)
else:
super(IndexObject, self)._set_cache_(attr)
super()._set_cache_(attr)
# END handle slot attribute

@property
Expand Down
4 changes: 2 additions & 2 deletions git/objects/commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def __init__(
as what time.altzone returns. The sign is inverted compared to git's
UTC timezone.
"""
super(Commit, self).__init__(repo, binsha)
super().__init__(repo, binsha)
self.binsha = binsha
if tree is not None:
assert isinstance(tree, Tree), "Tree needs to be a Tree instance, was %s" % type(tree)
Expand Down Expand Up @@ -218,7 +218,7 @@ def _set_cache_(self, attr: str) -> None:
_binsha, _typename, self.size, stream = self.repo.odb.stream(self.binsha)
self._deserialize(BytesIO(stream.read()))
else:
super(Commit, self)._set_cache_(attr)
super()._set_cache_(attr)
# END handle attrs

@property
Expand Down
6 changes: 3 additions & 3 deletions git/objects/submodule/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def __init__(
:param branch_path: Full (relative) path to ref to checkout when cloning the
remote repository.
"""
super(Submodule, self).__init__(repo, binsha, mode, path)
super().__init__(repo, binsha, mode, path)
self.size = 0
self._parent_commit = parent_commit
if url is not None:
Expand Down Expand Up @@ -154,7 +154,7 @@ def _set_cache_(self, attr: str) -> None:
elif attr == "_name":
raise AttributeError("Cannot retrieve the name of a submodule if it was not set initially")
else:
super(Submodule, self)._set_cache_(attr)
super()._set_cache_(attr)
# END handle attribute name

@classmethod
Expand All @@ -174,7 +174,7 @@ def __eq__(self, other: Any) -> bool:
"""Compare with another submodule."""
# We may only compare by name as this should be the ID they are hashed with.
# Otherwise this type wouldn't be hashable.
# return self.path == other.path and self.url == other.url and super(Submodule, self).__eq__(other)
# return self.path == other.path and self.url == other.url and super().__eq__(other)
return self._name == other._name

def __ne__(self, other: object) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion git/objects/submodule/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class RootModule(Submodule):

def __init__(self, repo: "Repo"):
# repo, binsha, mode=None, path=None, name = None, parent_commit=None, url=None, ref=None)
super(RootModule, self).__init__(
super().__init__(
repo,
binsha=self.NULL_BIN_SHA,
mode=self.k_default_mode,
Expand Down
4 changes: 2 additions & 2 deletions git/objects/submodule/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
self._smref: Union["ReferenceType[Submodule]", None] = None
self._index = None
self._auto_write = True
super(SubmoduleConfigParser, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

# { Interface
def set_submodule(self, submodule: "Submodule") -> None:
Expand Down Expand Up @@ -107,7 +107,7 @@ def flush_to_index(self) -> None:

# { Overridden Methods
def write(self) -> None: # type: ignore[override]
rval: None = super(SubmoduleConfigParser, self).write()
rval: None = super().write()
self.flush_to_index()
return rval

Expand Down
4 changes: 2 additions & 2 deletions git/objects/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __init__(
The timezone that the authored_date is in, in a format similar
to :attr:`time.altzone`.
"""
super(TagObject, self).__init__(repo, binsha)
super().__init__(repo, binsha)
if object is not None:
self.object: Union["Commit", "Blob", "Tree", "TagObject"] = object
if tag is not None:
Expand Down Expand Up @@ -108,4 +108,4 @@ def _set_cache_(self, attr: str) -> None:
self.message = ""
# END check our attributes
else:
super(TagObject, self)._set_cache_(attr)
super()._set_cache_(attr)
10 changes: 5 additions & 5 deletions git/objects/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def __init__(
mode: int = tree_id << 12,
path: Union[PathLike, None] = None,
):
super(Tree, self).__init__(repo, binsha, mode, path)
super().__init__(repo, binsha, mode, path)

@classmethod
def _get_intermediate_items(
Expand All @@ -254,7 +254,7 @@ def _set_cache_(self, attr: str) -> None:
ostream = self.repo.odb.stream(self.binsha)
self._cache: List[TreeCacheTup] = tree_entries_from_data(ostream.read())
else:
super(Tree, self)._set_cache_(attr)
super()._set_cache_(attr)
# END handle attribute

def _iter_convert_to_object(self, iterable: Iterable[TreeCacheTup]) -> Iterator[IndexObjUnion]:
Expand Down Expand Up @@ -352,13 +352,13 @@ def traverse(
# def is_tree_traversed(inp: Tuple) -> TypeGuard[Tuple[Iterator[Union['Tree', 'Blob', 'Submodule']]]]:
# return all(isinstance(x, (Blob, Tree, Submodule)) for x in inp[1])

# ret = super(Tree, self).traverse(predicate, prune, depth, branch_first, visit_once, ignore_self)
# ret = super().traverse(predicate, prune, depth, branch_first, visit_once, ignore_self)
# ret_tup = itertools.tee(ret, 2)
# assert is_tree_traversed(ret_tup), f"Type is {[type(x) for x in list(ret_tup[0])]}"
# return ret_tup[0]"""
return cast(
Union[Iterator[IndexObjUnion], Iterator[TraversedTreeTup]],
super(Tree, self)._traverse(
super()._traverse(
predicate,
prune,
depth, # type: ignore
Expand All @@ -374,7 +374,7 @@ def list_traverse(self, *args: Any, **kwargs: Any) -> IterableList[IndexObjUnion
traverse()
Tree -> IterableList[Union['Submodule', 'Tree', 'Blob']]
"""
return super(Tree, self)._list_traverse(*args, **kwargs)
return super()._list_traverse(*args, **kwargs)

# List protocol

Expand Down
6 changes: 2 additions & 4 deletions git/objects/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ class TraversableIterableObj(IterableObj, Traversable):
TIobj_tuple = Tuple[Union[T_TIobj, None], T_TIobj]

def list_traverse(self: T_TIobj, *args: Any, **kwargs: Any) -> IterableList[T_TIobj]:
return super(TraversableIterableObj, self)._list_traverse(*args, **kwargs)
return super()._list_traverse(*args, **kwargs)

@overload # type: ignore
def traverse(self: T_TIobj) -> Iterator[T_TIobj]:
Expand Down Expand Up @@ -652,7 +652,5 @@ def is_commit_traversed(inp: Tuple) -> TypeGuard[Tuple[Iterator[Tuple['Commit',
"""
return cast(
Union[Iterator[T_TIobj], Iterator[Tuple[Union[None, T_TIobj], T_TIobj]]],
super(TraversableIterableObj, self)._traverse(
predicate, prune, depth, branch_first, visit_once, ignore_self, as_edge # type: ignore
),
super()._traverse(predicate, prune, depth, branch_first, visit_once, ignore_self, as_edge), # type: ignore
)
2 changes: 1 addition & 1 deletion git/refs/head.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class HEAD(SymbolicReference):
def __init__(self, repo: "Repo", path: PathLike = _HEAD_NAME):
if path != self._HEAD_NAME:
raise ValueError("HEAD instance must point to %r, got %r" % (self._HEAD_NAME, path))
super(HEAD, self).__init__(repo, path)
super().__init__(repo, path)
self.commit: "Commit"

def orig_head(self) -> SymbolicReference:
Expand Down
2 changes: 1 addition & 1 deletion git/refs/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ class RefLog(List[RefLogEntry], Serializable):
__slots__ = ("_path",)

def __new__(cls, filepath: Union[PathLike, None] = None) -> "RefLog":
inst = super(RefLog, cls).__new__(cls)
inst = super().__new__(cls)
return inst

def __init__(self, filepath: Union[PathLike, None] = None):
Expand Down
4 changes: 2 additions & 2 deletions git/refs/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(self, repo: "Repo", path: PathLike, check_path: bool = True) -> Non
if check_path and not str(path).startswith(self._common_path_default + "/"):
raise ValueError(f"Cannot instantiate {self.__class__.__name__!r} from path {path}")
self.path: str # SymbolicReference converts to string at the moment.
super(Reference, self).__init__(repo, path)
super().__init__(repo, path)

def __str__(self) -> str:
return self.name
Expand All @@ -87,7 +87,7 @@ def set_object(
# END handle commit retrieval
# END handle message is set

super(Reference, self).set_object(object, logmsg)
super().set_object(object, logmsg)

if oldbinsha is not None:
# From refs/files-backend.c in git-source:
Expand Down
2 changes: 1 addition & 1 deletion git/refs/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def iter_items(
common_path = join_path(common_path, str(remote))
# END handle remote constraint
# super is Reference
return super(RemoteReference, cls).iter_items(repo, common_path)
return super().iter_items(repo, common_path)

# The Head implementation of delete also accepts strs, but this
# implementation does not. mypy doesn't have a way of representing
Expand Down
Loading