From 6dca735a0cc30afaa09adec0545ecf082cbab90e Mon Sep 17 00:00:00 2001 From: peterrrock2 Date: Mon, 29 Apr 2024 16:14:15 -0600 Subject: [PATCH] Make flake happy --- gerrychain/__init__.py | 3 +- gerrychain/_version.py | 157 ++++++++++++++---------- gerrychain/optimization/gingleator.py | 30 ++--- gerrychain/optimization/optimization.py | 6 +- 4 files changed, 116 insertions(+), 80 deletions(-) diff --git a/gerrychain/__init__.py b/gerrychain/__init__.py index 7eac04a8..f3e66f99 100644 --- a/gerrychain/__init__.py +++ b/gerrychain/__init__.py @@ -28,4 +28,5 @@ del get_versions from . import _version -__version__ = _version.get_versions()['version'] + +__version__ = _version.get_versions()["version"] diff --git a/gerrychain/_version.py b/gerrychain/_version.py index fa65e7ac..af21f27b 100644 --- a/gerrychain/_version.py +++ b/gerrychain/_version.py @@ -1,4 +1,3 @@ - # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build @@ -68,12 +67,14 @@ class NotThisMethod(Exception): def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f + return decorate @@ -100,10 +101,14 @@ def run_command( try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) + process = subprocess.Popen( + [command] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, + ) break except OSError as e: if e.errno == errno.ENOENT: @@ -141,15 +146,21 @@ def versions_from_parentdir( for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} + return { + "version": dirname[len(parentdir_prefix) :], + "full-revisionid": None, + "dirty": False, + "error": None, + "date": None, + } rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -212,7 +223,7 @@ def git_versions_from_keywords( # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -221,7 +232,7 @@ def git_versions_from_keywords( # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} + tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -229,32 +240,36 @@ def git_versions_from_keywords( for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') - if not re.match(r'\d', r): + if not re.match(r"\d", r): continue if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command + tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command ) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. @@ -273,8 +288,7 @@ def git_pieces_from_vcs( env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -282,10 +296,19 @@ def git_pieces_from_vcs( # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) + describe_out, rc = runner( + GITS, + [ + "describe", + "--tags", + "--dirty", + "--always", + "--long", + "--match", + f"{tag_prefix}[[:digit:]]*", + ], + cwd=root, + ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") @@ -300,8 +323,7 @@ def git_pieces_from_vcs( pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") @@ -341,17 +363,16 @@ def git_pieces_from_vcs( dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -360,10 +381,12 @@ def git_pieces_from_vcs( if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -412,8 +435,7 @@ def render_pep440(pieces: Dict[str, Any]) -> str: rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -442,8 +464,7 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str: rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -604,11 +625,13 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str: def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default @@ -632,9 +655,13 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } def get_versions() -> Dict[str, Any]: @@ -648,8 +675,7 @@ def get_versions() -> Dict[str, Any]: verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass @@ -658,13 +684,16 @@ def get_versions() -> Dict[str, Any]: # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): + for _ in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None, + } try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) @@ -678,6 +707,10 @@ def get_versions() -> Dict[str, Any]: except NotThisMethod: pass - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } diff --git a/gerrychain/optimization/gingleator.py b/gerrychain/optimization/gingleator.py index 37a0b05a..77399b3c 100755 --- a/gerrychain/optimization/gingleator.py +++ b/gerrychain/optimization/gingleator.py @@ -39,8 +39,8 @@ def __init__( :type constraints: Union[Iterable[Callable], Validator, Iterable[Bounds], Callable] :param initial_state: Initial :class:`gerrychain.partition.Partition` class. :type initial_state: Partition - :param minority_perc_col: The name of the updater mapping of district ids to the - fraction of minority population within that district. If no updater is + :param minority_perc_col: The name of the updater mapping of district ids to the + fraction of minority population within that district. If no updater is specified, one is made according to the ``min_perc_column_name`` parameter. Defaults to None. :type minority_perc_col: Optional[str] @@ -52,14 +52,14 @@ def __init__( 'a where 'a is Comparable``. This class implements a few potential choices as class methods. Defaults to None. :type score_function: Optional[Callable] - :param minority_pop_col: If minority_perc_col is not defined, the minority population + :param minority_pop_col: If minority_perc_col is not defined, the minority population column with which to compute percentage. Defaults to None. :type minority_pop_col: Optional[str] :param total_pop_col: If minority_perc_col is defined, the total population column with which to compute percentage. Defaults to "TOTPOP". :type total_pop_col: str, optional - :param min_perc_column_name: If minority_perc_col is not defined, the name to give the - created percentage updater. Defaults to + :param min_perc_column_name: If minority_perc_col is not defined, the name to give the + created percentage updater. Defaults to "_gingleator_auxiliary_helper_updater_min_perc_col". :type min_perc_column_name: str, optional """ @@ -106,8 +106,8 @@ def num_opportunity_dists( :param part: Partition to score. :type part: Partition - :param minority_perc_col: The name of the updater mapping of district ids to the - fraction of minority population within that district. + :param minority_perc_col: The name of the updater mapping of district ids to the + fraction of minority population within that district. :type minority_perc_col: str :param threshold: Fraction beyond which to consider something a "Gingles" (or opportunity) district. @@ -129,8 +129,8 @@ def reward_partial_dist( :param part: Partition to score. :type part: Partition - :param minority_perc_col: The name of the updater mapping of district ids to the - fraction of minority population within that district. + :param minority_perc_col: The name of the updater mapping of district ids to the + fraction of minority population within that district. :type minority_perc_col: str :param threshold: Fraction beyond which to consider something a "Gingles" (or opportunity) district. @@ -155,8 +155,8 @@ def reward_next_highest_close( :param part: Partition to score. :type part: Partition - :param minority_perc_col: The name of the updater mapping of district ids to the - fraction of minority population within that district. + :param minority_perc_col: The name of the updater mapping of district ids to the + fraction of minority population within that district. :type minority_perc_col: str :param threshold: Fraction beyond which to consider something a "Gingles" (or opportunity) district. @@ -185,8 +185,8 @@ def penalize_maximum_over( :param part: Partition to score. :type part: Partition - :param minority_perc_col: The name of the updater mapping of district ids to the - fraction of minority population within that district. + :param minority_perc_col: The name of the updater mapping of district ids to the + fraction of minority population within that district. :type minority_perc_col: str :param threshold: Fraction beyond which to consider something a "Gingles" (or opportunity) district. @@ -213,8 +213,8 @@ def penalize_avg_over( :param part: Partition to score. :type part: Partition - :param minority_perc_col: The name of the updater mapping of district ids to the - fraction of minority population within that district. + :param minority_perc_col: The name of the updater mapping of district ids to the + fraction of minority population within that district. :type minority_perc_col: str :param threshold: Fraction beyond which to consider something a "Gingles" (or opportunity) district. diff --git a/gerrychain/optimization/optimization.py b/gerrychain/optimization/optimization.py index 0a3075a5..5b45e3c6 100644 --- a/gerrychain/optimization/optimization.py +++ b/gerrychain/optimization/optimization.py @@ -52,7 +52,8 @@ def __init__( :param optimization_metric: The score function with which to optimize over. This should have the signature: ``Partition -> 'a`` where 'a is comparable. :type optimization_metric: Callable[[Partition], Any] - :param maximize: Boolean indicating whether to maximize or minimize the function. Defaults to True for maximize. + :param maximize: Boolean indicating whether to maximize or minimize the function. + Defaults to True for maximize. :type maximize: bool, optional :param step_indexer: Name of the updater tracking the partitions step in the chain. If not implemented on the partition the constructor creates and adds it. Defaults to "step". @@ -522,7 +523,8 @@ def variable_length_short_bursts( :param stuck_buffer: How many bursts of a given length with no improvement to allow before increasing the burst length. :type stuck_buffer: int - :param accept: Function accepting or rejecting the proposed state. Defaults to :func:`~gerrychain.accept.always_accept`. + :param accept: Function accepting or rejecting the proposed state. Defaults to + :func:`~gerrychain.accept.always_accept`. :type accept: Callable[[Partition], bool], optional :param with_progress_bar: Whether or not to draw tqdm progress bar. Defaults to False. :type with_progress_bar: bool, optional