From 36a3b7618479f200e0d4ad0fca38dab217db7dc5 Mon Sep 17 00:00:00 2001 From: Eliah Kagan Date: Thu, 2 Nov 2023 12:40:24 -0400 Subject: [PATCH 1/3] Revise some comments and strings These are a few things I had missed in #1725. --- git/config.py | 1 + git/objects/base.py | 4 ++-- git/refs/symbolic.py | 6 +++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/git/config.py b/git/config.py index 8f68c4e66..1931f142d 100644 --- a/git/config.py +++ b/git/config.py @@ -150,6 +150,7 @@ class SectionConstraint(Generic[T_ConfigParser]): """ __slots__ = ("_config", "_section_name") + _valid_attrs_ = ( "get_value", "set_value", diff --git a/git/objects/base.py b/git/objects/base.py index a771f9fbf..6d2efa32a 100644 --- a/git/objects/base.py +++ b/git/objects/base.py @@ -137,7 +137,7 @@ def __repr__(self) -> str: @property def hexsha(self) -> str: """:return: 40 byte hex version of our 20 byte binary sha""" - # b2a_hex produces bytes + # b2a_hex produces bytes. return bin_to_hex(self.binsha).decode("ascii") @property @@ -206,7 +206,7 @@ def __hash__(self) -> int: def _set_cache_(self, attr: str) -> None: if attr in IndexObject.__slots__: - # they cannot be retrieved lateron ( not without searching for them ) + # They cannot be retrieved later on (not without searching for them). raise AttributeError( "Attribute '%s' unset: path and mode attributes must have been set during %s object creation" % (attr, type(self).__name__) diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 6e4b657d6..73f64a57b 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -215,7 +215,7 @@ def _check_ref_name_valid(ref_path: PathLike) -> None: elif any(component.endswith(".lock") for component in str(ref_path).split("/")): raise ValueError( f"Invalid reference '{ref_path}': references cannot have slash-separated components that end with" - f" '.lock'" + " '.lock'" ) @classmethod @@ -309,8 +309,8 @@ def set_commit( ) -> "SymbolicReference": """As set_object, but restricts the type of object to be a Commit. - :raise ValueError: If commit is not a Commit object or doesn't point to - a commit + :raise ValueError: If commit is not a :class:`~git.objects.commit.Commit` object + or doesn't point to a commit :return: self """ # Check the type - assume the best if it is a base-string. From a47e46d7512c595dc230b2caeedb4ba615fadfa9 Mon Sep 17 00:00:00 2001 From: Eliah Kagan Date: Thu, 2 Nov 2023 13:30:12 -0400 Subject: [PATCH 2/3] 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. --- git/cmd.py | 4 ++-- git/config.py | 30 +++++++++++++++--------------- git/db.py | 2 +- git/exc.py | 6 +++--- git/index/base.py | 4 ++-- git/objects/base.py | 8 ++++---- git/objects/commit.py | 4 ++-- git/objects/submodule/base.py | 6 +++--- git/objects/submodule/root.py | 2 +- git/objects/submodule/util.py | 4 ++-- git/objects/tag.py | 4 ++-- git/objects/tree.py | 10 +++++----- git/objects/util.py | 6 ++---- git/refs/head.py | 2 +- git/refs/log.py | 2 +- git/refs/reference.py | 4 ++-- git/refs/remote.py | 2 +- git/remote.py | 6 +++--- git/util.py | 8 ++++---- test/performance/lib.py | 6 +++--- test/test_commit.py | 2 +- test/test_git.py | 2 +- test/test_index.py | 2 +- test/test_remote.py | 4 ++-- 24 files changed, 64 insertions(+), 66 deletions(-) diff --git a/git/cmd.py b/git/cmd.py index 5359924f0..fd39a8eeb 100644 --- a/git/cmd.py +++ b/git/cmd.py @@ -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] = [] @@ -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 diff --git a/git/config.py b/git/config.py index 1931f142d..2cb057021 100644 --- a/git/config.py +++ b/git/config.py @@ -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 @@ -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 @@ -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).""" @@ -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""" @@ -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: @@ -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) diff --git a/git/db.py b/git/db.py index 1aacd0c84..9e278ea75 100644 --- a/git/db.py +++ b/git/db.py @@ -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: diff --git a/git/exc.py b/git/exc.py index bfb023fa5..124c5eeea 100644 --- a/git/exc.py +++ b/git/exc.py @@ -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" @@ -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): @@ -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" diff --git a/git/index/base.py b/git/index/base.py index b87fefd56..c2333a2c2 100644 --- a/git/index/base.py +++ b/git/index/base.py @@ -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: @@ -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) diff --git a/git/objects/base.py b/git/objects/base.py index 6d2efa32a..9f188a955 100644 --- a/git/objects/base.py +++ b/git/objects/base.py @@ -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" % ( @@ -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""" @@ -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: @@ -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 diff --git a/git/objects/commit.py b/git/objects/commit.py index d39ca52bb..04acb668b 100644 --- a/git/objects/commit.py +++ b/git/objects/commit.py @@ -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) @@ -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 diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 018f9a39c..1516306ec 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -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: @@ -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 @@ -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: diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index 0ac8a22db..cfcbb4cb7 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -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, diff --git a/git/objects/submodule/util.py b/git/objects/submodule/util.py index e13528a8f..3fc0b0b56 100644 --- a/git/objects/submodule/util.py +++ b/git/objects/submodule/util.py @@ -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: @@ -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 diff --git a/git/objects/tag.py b/git/objects/tag.py index a7ff7f263..6eb1c8d90 100644 --- a/git/objects/tag.py +++ b/git/objects/tag.py @@ -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: @@ -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) diff --git a/git/objects/tree.py b/git/objects/tree.py index 708ab3edd..1be6f193e 100644 --- a/git/objects/tree.py +++ b/git/objects/tree.py @@ -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( @@ -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]: @@ -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 @@ -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 diff --git a/git/objects/util.py b/git/objects/util.py index 5ccb3ec37..7af7fa0e5 100644 --- a/git/objects/util.py +++ b/git/objects/util.py @@ -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]: @@ -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 ) diff --git a/git/refs/head.py b/git/refs/head.py index 30ff336d5..fa40943c6 100644 --- a/git/refs/head.py +++ b/git/refs/head.py @@ -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: diff --git a/git/refs/log.py b/git/refs/log.py index 21c757ccd..ebdaf04d1 100644 --- a/git/refs/log.py +++ b/git/refs/log.py @@ -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): diff --git a/git/refs/reference.py b/git/refs/reference.py index 8a0262ea4..f0eb6bfaa 100644 --- a/git/refs/reference.py +++ b/git/refs/reference.py @@ -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 @@ -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: diff --git a/git/refs/remote.py b/git/refs/remote.py index e4b1f4392..f26ee08fc 100644 --- a/git/refs/remote.py +++ b/git/refs/remote.py @@ -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 diff --git a/git/remote.py b/git/remote.py index 880e87232..ccf70a25c 100644 --- a/git/remote.py +++ b/git/remote.py @@ -573,14 +573,14 @@ def __getattr__(self, attr: str) -> Any: """Allows to call this instance like remote.special( \\*args, \\*\\*kwargs) to call git-remote special self.name.""" if attr == "_config_reader": - return super(Remote, self).__getattr__(attr) + return super().__getattr__(attr) # Sometimes, probably due to a bug in Python itself, we are being called # even though a slot of the same name exists. try: return self._config_reader.get(attr) except cp.NoOptionError: - return super(Remote, self).__getattr__(attr) + return super().__getattr__(attr) # END handle exception def _config_section_name(self) -> str: @@ -592,7 +592,7 @@ def _set_cache_(self, attr: str) -> None: # values implicitly, such as in print(r.pushurl). self._config_reader = SectionConstraint(self.repo.config_reader("repository"), self._config_section_name()) else: - super(Remote, self)._set_cache_(attr) + super()._set_cache_(attr) def __str__(self) -> str: return self.name diff --git a/git/util.py b/git/util.py index 73b3a2edd..bd1fbe247 100644 --- a/git/util.py +++ b/git/util.py @@ -718,7 +718,7 @@ class CallableRemoteProgress(RemoteProgress): def __init__(self, fn: Callable) -> None: self._callable = fn - super(CallableRemoteProgress, self).__init__() + super().__init__() def update(self, *args: Any, **kwargs: Any) -> None: self._callable(*args, **kwargs) @@ -1040,7 +1040,7 @@ def __init__( :param max_block_time_s: Maximum amount of seconds we may lock. """ - super(BlockingLockFile, self).__init__(file_path) + super().__init__(file_path) self._check_interval = check_interval_s self._max_block_time = max_block_time_s @@ -1054,7 +1054,7 @@ def _obtain_lock(self) -> None: maxtime = starttime + float(self._max_block_time) while True: try: - super(BlockingLockFile, self)._obtain_lock() + super()._obtain_lock() except IOError as e: # synity check: if the directory leading to the lockfile is not # readable anymore, raise an exception @@ -1103,7 +1103,7 @@ class IterableList(List[T_IterableObj]): __slots__ = ("_id_attr", "_prefix") def __new__(cls, id_attr: str, prefix: str = "") -> "IterableList[T_IterableObj]": - return super(IterableList, cls).__new__(cls) + return super().__new__(cls) def __init__(self, id_attr: str, prefix: str = "") -> None: self._id_attr = id_attr diff --git a/test/performance/lib.py b/test/performance/lib.py index 8e76fe815..1ac3e0b60 100644 --- a/test/performance/lib.py +++ b/test/performance/lib.py @@ -33,7 +33,7 @@ class TestBigRepoR(TestBase): def setUp(self): try: - super(TestBigRepoR, self).setUp() + super().setUp() except AttributeError: pass @@ -65,7 +65,7 @@ class TestBigRepoRW(TestBigRepoR): def setUp(self): self.gitrwrepo = None try: - super(TestBigRepoRW, self).setUp() + super().setUp() except AttributeError: pass dirname = tempfile.mktemp() @@ -74,7 +74,7 @@ def setUp(self): self.puregitrwrepo = Repo(dirname, odbt=GitDB) def tearDown(self): - super(TestBigRepoRW, self).tearDown() + super().tearDown() if self.gitrwrepo is not None: rmtree(self.gitrwrepo.working_dir) self.gitrwrepo.git.clear_cache() diff --git a/test/test_commit.py b/test/test_commit.py index 21d17ae2c..1327616ed 100644 --- a/test/test_commit.py +++ b/test/test_commit.py @@ -275,7 +275,7 @@ def test_iteration(self): class Child(Commit): def __init__(self, *args, **kwargs): - super(Child, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) child_commits = list(Child.iter_items(self.rorepo, "master", paths=("CHANGES", "AUTHORS"))) assert type(child_commits[0]) is Child diff --git a/test/test_git.py b/test/test_git.py index 814316edd..06f8f5c97 100644 --- a/test/test_git.py +++ b/test/test_git.py @@ -32,7 +32,7 @@ class TestGit(TestBase): @classmethod def setUpClass(cls): - super(TestGit, cls).setUpClass() + super().setUpClass() cls.git = Git(cls.rorepo.working_dir) def tearDown(self): diff --git a/test/test_index.py b/test/test_index.py index bf582bad9..3357dc880 100644 --- a/test/test_index.py +++ b/test/test_index.py @@ -66,7 +66,7 @@ def _make_hook(git_dir, name, content, make_exec=True): class TestIndex(TestBase): def __init__(self, *args): - super(TestIndex, self).__init__(*args) + super().__init__(*args) self._reset_progress() def _assert_fprogress(self, entries): diff --git a/test/test_remote.py b/test/test_remote.py index 3e7a025c5..8205c0bcd 100644 --- a/test/test_remote.py +++ b/test/test_remote.py @@ -44,7 +44,7 @@ class TestRemoteProgress(RemoteProgress): __slots__ = ("_seen_lines", "_stages_per_op", "_num_progress_messages") def __init__(self): - super(TestRemoteProgress, self).__init__() + super().__init__() self._seen_lines = [] self._stages_per_op = {} self._num_progress_messages = 0 @@ -53,7 +53,7 @@ def _parse_progress_line(self, line): # We may remove the line later if it is dropped. # Keep it for debugging. self._seen_lines.append(line) - rval = super(TestRemoteProgress, self)._parse_progress_line(line) + rval = super()._parse_progress_line(line) return rval def line_dropped(self, line): From 91131770eb0e932b9bc0918fe8374875ecbbd816 Mon Sep 17 00:00:00 2001 From: Eliah Kagan Date: Thu, 2 Nov 2023 13:45:32 -0400 Subject: [PATCH 3/3] Don't swallow AttributeError from super().setUp() This is conceptually independent of the immediately preceding super() call refactoring, but serves the same goal of simplifying and clarifying super() calls. In test.performance.lib, the TestBigRepoR and TestBigRepoRW classes' setUp methods had calls to setUp through super proxies, which were wrapped in try-blocks to swallow AttributeError exceptions. This removes that, relying on the presence of setUp methods in some parent or sibling class in the MRO. The intent appeared to be solely to account for the possibility that no class in the MRO would define a setUp method. However, the unittest.TestCase base class defines noop setUp and tearDown methods to ensure this does not have to be done. This may also make the code more robust, because the form in which AttributeError was being swallowed was: try: super().setUp() except AttributeError: pass But that has the disadvantage of also catching AttributeError due to a bug or other problem in code that runs *in* an ancestor or sibling class's existing setUp method. This could alternatively be addressed by using: try: other_setUp = super().setUp except AttributeError: pass else: other_setUp() However, because unittest.TestCase provides empty setUp and tearDown methods to allow such special-casing to be avoided (both in cases like this and for the test runner), this isn't needed. --- test/performance/lib.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/test/performance/lib.py b/test/performance/lib.py index 1ac3e0b60..2b2a632d9 100644 --- a/test/performance/lib.py +++ b/test/performance/lib.py @@ -32,10 +32,7 @@ class TestBigRepoR(TestBase): """ def setUp(self): - try: - super().setUp() - except AttributeError: - pass + super().setUp() repo_path = os.environ.get(k_env_git_repo) if repo_path is None: @@ -64,10 +61,7 @@ class TestBigRepoRW(TestBigRepoR): def setUp(self): self.gitrwrepo = None - try: - super().setUp() - except AttributeError: - pass + super().setUp() dirname = tempfile.mktemp() os.mkdir(dirname) self.gitrwrepo = self.gitrorepo.clone(dirname, shared=True, bare=True, odbt=GitCmdObjectDB)