Skip to content

Commit

Permalink
Merge #931
Browse files Browse the repository at this point in the history
931: black, flake8, and isort (part 2) r=hgrecco a=crusaderky

- Configure flake8 and isort
- Resolve all flake8 errors
- Assorted code quality tweaks (embeds #664)
- Out of scope: CI integration and documentation (will be done in a successive PR)

Co-authored-by: Guido Imperiale <[email protected]>
  • Loading branch information
bors[bot] and crusaderky authored Dec 16, 2019
2 parents 89b5bd1 + 0d15f54 commit 2503f00
Show file tree
Hide file tree
Showing 43 changed files with 339 additions and 413 deletions.
2 changes: 1 addition & 1 deletion bench/bench.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import copy
import fnmatch
import os
import copy
from timeit import Timer

import yaml
Expand Down
14 changes: 7 additions & 7 deletions docs/_themes/flask_theme_support.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
# flasky extensions. flasky pygments style based on tango style
from pygments.style import Style
from pygments.token import (
Keyword,
Name,
Comment,
String,
Error,
Generic,
Keyword,
Literal,
Name,
Number,
Operator,
Generic,
Whitespace,
Punctuation,
Other,
Literal,
Punctuation,
String,
Whitespace,
)


Expand Down
12 changes: 6 additions & 6 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pint documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 1 13:33:14 2012.
Expand All @@ -12,9 +11,10 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import pkg_resources
import datetime

import pkg_resources

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
Expand Down Expand Up @@ -60,7 +60,7 @@

try: # pragma: no cover
version = pkg_resources.get_distribution(project).version
except: # pragma: no cover
except Exception: # pragma: no cover
# we seem to have a local copy not installed without setuptools
# so the reported version will be unknown
version = "unknown"
Expand Down Expand Up @@ -200,11 +200,11 @@

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
"preamble": "".join(("\DeclareUnicodeCharacter{2212}{-}",)) # MINUS
"preamble": "".join((r"\DeclareUnicodeCharacter{2212}{-}",)) # MINUS
}

# Grouping the document tree into LaTeX files. List of tuples
Expand Down
21 changes: 12 additions & 9 deletions pint/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint
~~~~
Expand All @@ -12,6 +11,8 @@
:license: BSD, see LICENSE for more details.
"""

import sys

import pkg_resources

from .context import Context
Expand All @@ -26,24 +27,24 @@
from .formatting import formatter
from .measurement import Measurement
from .quantity import Quantity
from .registry import UnitRegistry, LazyRegistry
from .registry import LazyRegistry, UnitRegistry
from .unit import Unit
from .util import pi_theorem, logger


import sys
from .util import logger, pi_theorem

try:
from pintpandas import PintType, PintArray
from pintpandas import PintArray, PintType

del PintType
del PintArray

_HAS_PINTPANDAS = True
except Exception:
except ImportError:
_HAS_PINTPANDAS = False
_, _pintpandas_error, _ = sys.exc_info()

try: # pragma: no cover
__version__ = pkg_resources.get_distribution("pint").version
except: # pragma: no cover
except Exception: # pragma: no cover
# we seem to have a local copy not installed without setuptools
# so the reported version will be unknown
__version__ = "unknown"
Expand Down Expand Up @@ -124,7 +125,9 @@ def test():
"RedefinitionError",
"UndefinedUnitError",
"UnitStrippedWarning",
"formatter",
"get_application_registry",
"set_application_registry",
"pi_theorem",
"__version__",
)
5 changes: 2 additions & 3 deletions pint/babel_names.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.babel
~~~~~~~~~~
Expand Down Expand Up @@ -57,7 +56,7 @@
millimeter="length-millimeter",
metric_horsepower="power-horsepower",
gibibyte="digital-gigabyte",
## 'temperature-generic',
# 'temperature-generic',
liter="volume-liter",
turn="angle-revolution",
microsecond="duration-microsecond",
Expand Down Expand Up @@ -111,7 +110,7 @@
century="duration-century",
cubic_foot="volume-cubic-foot",
deciliter="volume-deciliter",
##pint='volume-pint-metric',
# pint='volume-pint-metric',
cubic_meter="volume-cubic-meter",
cubic_kilometer="volume-cubic-kilometer",
quart="volume-quart",
Expand Down
8 changes: 4 additions & 4 deletions pint/compat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.compat
~~~~~~~~~~~
Expand All @@ -9,10 +8,9 @@
:license: BSD, see LICENSE for more details.
"""
import tokenize
import warnings
from decimal import Decimal
from io import BytesIO
from numbers import Number
from decimal import Decimal


def tokenizer(input_string):
Expand Down Expand Up @@ -129,10 +127,12 @@ def _to_magnitude(value, force_ndarray=False):
HAS_BABEL = False

if not HAS_BABEL:
Loc = babel_units = None
Loc = babel_units = None # noqa: F811

# Define location of pint.Quantity in NEP-13 type cast hierarchy by defining upcast and
# downcast/wrappable types


def is_upcast_type(other):
# Check if class name is in preset list
return other.__class__.__name__ in ("PintArray", "Series", "DataArray")
Expand Down
16 changes: 8 additions & 8 deletions pint/context.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.context
~~~~~~~~~~~~
Expand All @@ -13,8 +12,8 @@
import weakref
from collections import ChainMap, defaultdict

from .util import ParserHelper, UnitsContainer, to_units_container, SourceIterator
from .errors import DefinitionSyntaxError
from .util import ParserHelper, SourceIterator, to_units_container

#: Regex to match the header parts of a context.
_header_re = re.compile(
Expand All @@ -37,6 +36,7 @@ class Context:
dimension to another. Each Dimension are specified using a UnitsContainer.
Simple transformation are given with a function taking a single parameter.
>>> from pint.util import UnitsContainer
>>> timedim = UnitsContainer({'[time]': 1})
>>> spacedim = UnitsContainer({'[length]': 1})
>>> def f(time):
Expand Down Expand Up @@ -106,10 +106,10 @@ def from_lines(cls, lines, to_base_func=None):
else:
aliases = ()
defaults = r.groupdict()["defaults"]
except:
except Exception as exc:
raise DefinitionSyntaxError(
"Could not parse the Context header '%s'" % header, lineno=lineno
)
) from exc

if defaults:

Expand All @@ -123,11 +123,11 @@ def to_num(val):
try:
defaults = (part.split("=") for part in defaults.strip("()").split(","))
defaults = {str(k).strip(): to_num(v) for k, v in defaults}
except (ValueError, TypeError):
except (ValueError, TypeError) as exc:
raise DefinitionSyntaxError(
f"Could not parse Context definition defaults: '{txt}'",
lineno=lineno,
)
) from exc

ctx = cls(name, aliases, defaults)
else:
Expand Down Expand Up @@ -156,11 +156,11 @@ def to_num(val):
ctx.add_transformation(src, dst, func)
else:
raise Exception
except:
except Exception as exc:
raise DefinitionSyntaxError(
"Could not parse Context %s relation '%s'" % (name, line),
lineno=lineno,
)
) from exc

if defaults:
missing_pars = defaults.keys() - set(names)
Expand Down
1 change: 0 additions & 1 deletion pint/converters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.converters
~~~~~~~~~~~~~~~
Expand Down
5 changes: 2 additions & 3 deletions pint/definitions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.definitions
~~~~~~~~~~~~~~~~
Expand All @@ -9,8 +8,8 @@
:license: BSD, see LICENSE for more details.
"""

from .converters import ScaleConverter, OffsetConverter
from .util import UnitsContainer, _is_dim, ParserHelper
from .converters import OffsetConverter, ScaleConverter
from .util import ParserHelper, UnitsContainer, _is_dim


class Definition:
Expand Down
1 change: 0 additions & 1 deletion pint/errors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.errors
~~~~~~~~~~~
Expand Down
17 changes: 8 additions & 9 deletions pint/formatting.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.formatter
~~~~~~~~~~~~~~
Expand All @@ -11,7 +10,7 @@

import re

from .babel_names import _babel_units, _babel_lengths
from .babel_names import _babel_lengths, _babel_units
from .compat import Loc

__JOIN_REG_EXP = re.compile(r"\{\d*\}")
Expand Down Expand Up @@ -43,7 +42,7 @@ def _pretty_fmt_exponent(num):
"""Format an number into a pretty printed exponent.
"""
# TODO: Will not work for decimals
ret = "{0:n}".format(num).replace("-", "⁻")
ret = f"{num:n}".replace("-", "⁻")
for n in range(10):
ret = ret.replace(str(n), _PRETTY_EXPONENTS[n])
return ret
Expand Down Expand Up @@ -104,7 +103,7 @@ def formatter(
division_fmt=" / ",
power_fmt="{} ** {}",
parentheses_fmt="({0})",
exp_call=lambda x: "{0:n}".format(x),
exp_call=lambda x: f"{x:n}",
locale=None,
babel_length="long",
babel_plural_form="one",
Expand Down Expand Up @@ -266,7 +265,7 @@ def _tothe(power):
# remove unit prefix if it exists
# siunitx supports \prefix commands

l = lpos if power >= 0 else lneg
lpick = lpos if power >= 0 else lneg
prefix = None
for p in registry._prefixes.values():
p = str(p)
Expand All @@ -275,11 +274,11 @@ def _tothe(power):
unit = unit.replace(prefix, "", 1)

if power < 0:
l.append(r"\per")
lpick.append(r"\per")
if prefix is not None:
l.append(r"\{}".format(prefix))
l.append(r"\{}".format(unit))
l.append(r"{}".format(_tothe(abs(power))))
lpick.append(r"\{}".format(prefix))
lpick.append(r"\{}".format(unit))
lpick.append(r"{}".format(_tothe(abs(power))))

return "".join(lpos) + "".join(lneg)

Expand Down
1 change: 0 additions & 1 deletion pint/matplotlib.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.matplotlib
~~~~~~~~~~~~~~~
Expand Down
3 changes: 1 addition & 2 deletions pint/measurement.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pint.measurement
~~~~~~~~~~~~~~~~
Expand Down Expand Up @@ -76,7 +75,7 @@ def __repr__(self):
)

def __str__(self):
return "{0}".format(self)
return "{}".format(self)

def __format__(self, spec):
# special cases
Expand Down
Loading

0 comments on commit 2503f00

Please sign in to comment.