Skip to content

Commit

Permalink
global: format to <100 line-width
Browse files Browse the repository at this point in the history
  • Loading branch information
PascalEgn authored and drjova committed Aug 6, 2024
1 parent 146946c commit 36c7e2d
Show file tree
Hide file tree
Showing 26 changed files with 533 additions and 365 deletions.
6 changes: 1 addition & 5 deletions inspire_utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
# In applying this license, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization
# or submit itself to any jurisdiction.

"""INSPIRE configuration loader.
Inspired by the Flask configuration loader:
Expand Down Expand Up @@ -47,10 +46,7 @@ def __init__(self, file_path, cause):
cause (string): reason of failure, i.e. what exactly was the
problem while parsing
"""
message = six.text_type("Malformed config at {}: {}").format(
file_path,
cause
)
message = six.text_type("Malformed config at {}: {}").format(file_path, cause)
super(MalformedConfig, self).__init__(message)


Expand Down
49 changes: 32 additions & 17 deletions inspire_utils/date.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
# In applying this license, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization
# or submit itself to any jurisdiction.

"""Utils to handle dates in INSPIRE."""

from __future__ import absolute_import, division, print_function
Expand Down Expand Up @@ -48,13 +47,18 @@ class PartialDate(object):
Raises:
TypeError: when the date parts are not `int` s or `None`.
ValueError: when the date is not valid.
"""

def __init__(self, year, month=None, day=None):
well_typed = all(isinstance(part, int) or part is None for part in (year, month, day))
well_typed = all(
isinstance(part, int) or part is None for part in (year, month, day)
)
if not well_typed:
raise TypeError(u'arguments to {classname} must be of type int or None'.format(
classname=type(self).__name__))
raise TypeError(
u'arguments to {classname} must be of type int or None'.format(
classname=type(self).__name__
)
)
if year is None or year < 1000:
raise ValueError('year must be an int >= 1000')
if day and not month:
Expand All @@ -68,10 +72,18 @@ def __init__(self, year, month=None, day=None):
self.day = day

def __repr__(self):
return u'PartialDate(year={self.year}, month={self.month}, day={self.day})'.format(self=self)
return (
u'PartialDate(year={self.year}, month={self.month}, day={self.day})'.format(
self=self
)
)

def __eq__(self, other):
return self.year == other.year and self.month == other.month and self.day == other.day
return (
self.year == other.year
and self.month == other.month
and self.day == other.day
)

def __lt__(self, other):
self_month = self.month or 99
Expand All @@ -97,7 +109,6 @@ def loads(cls, string):
Traceback (most recent call last):
...
ValueError: month must be in 1..12
"""

date_parts = string.split('-')
Expand All @@ -116,7 +127,6 @@ def dumps(self):
Returns:
str: normalized date, in the form ``YYYY-MM-DD``, ``YYYY-MM`` or
``YYYY`` (depending on the information present in the date)
"""
non_empty = itertools.takewhile(bool, (self.year, self.month, self.day))
# XXX: this only handles dates after 1000, which should be sufficient
Expand Down Expand Up @@ -147,7 +157,6 @@ def parse(cls, date, **kwargs):
Examples:
>>> PartialDate.parse('30 Jun 1686')
PartialDate(year=1686, month=6, day=30)
"""
# In order to detect partial dates, parse twice with different defaults
# and compare the results.
Expand Down Expand Up @@ -180,7 +189,6 @@ def from_parts(cls, year, month=None, day=None):
Examples:
>>> PartialDate.from_parts('1686', 'June', '30')
PartialDate(year=1686, month=6, day=30)
"""
# XXX: 0 is not a valid year/month/day
non_empty = itertools.takewhile(
Expand All @@ -194,13 +202,18 @@ def pprint(self):
Examples:
>>> PartialDate(1686, 6, 30).pprint()
u'Jun 30, 1686'
"""
if not self.month:
return dates.format_date(datetime.date(self.year, 1, 1), 'yyyy', locale='en')
return dates.format_date(
datetime.date(self.year, 1, 1), 'yyyy', locale='en'
)
if not self.day:
return dates.format_date(datetime.date(self.year, self.month, 1), 'MMM, yyyy', locale='en')
return dates.format_date(datetime.date(self.year, self.month, self.day), 'MMM d, yyyy', locale='en')
return dates.format_date(
datetime.date(self.year, self.month, 1), 'MMM, yyyy', locale='en'
)
return dates.format_date(
datetime.date(self.year, self.month, self.day), 'MMM d, yyyy', locale='en'
)


def normalize_date(date, **kwargs):
Expand Down Expand Up @@ -232,7 +245,6 @@ def normalize_date(date, **kwargs):
>>> normalize_date(None)
>>> normalize_date('30 Jun 1686')
'1686-06-30'
"""
if date is None:
return
Expand Down Expand Up @@ -265,7 +277,10 @@ def earliest_date(dates):


def fill_missing_date_parts(date):
"""Sets missing day and/or month to 1. Useful to avoid errors when saving to DB."""
"""Sets missing day and/or month to 1.
Useful to avoid errors when saving to DB.
"""

if date is None:
return
Expand Down
10 changes: 6 additions & 4 deletions inspire_utils/dedupers.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
def dedupe_list(list_with_duplicates):
"""Remove duplicates from a list preserving the order.
We might be tempted to use the list(set(l)) idiom, but it doesn't preserve
the order, which hinders testability.
We might be tempted to use the list(set(l)) idiom, but it doesn't
preserve the order, which hinders testability.
"""
result = []

Expand All @@ -43,9 +43,11 @@ def dedupe_list(list_with_duplicates):
def dedupe_list_of_dicts(ld):
"""Remove duplicates from a list of dictionaries preserving the order.
We can't use the generic list helper because a dictionary isn't hashable.
Adapted from http://stackoverflow.com/a/9427216/374865.
We can't use the generic list helper because a dictionary isn't
hashable. Adapted from
http://stackoverflow.com/a/9427216/374865.
"""

def _freeze(o):
"""Recursively freezes a dict into an hashable object.
Expand Down
14 changes: 8 additions & 6 deletions inspire_utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ def force_list(data):
['foo', 'bar']
>>> force_list(['foo', 'bar', 'baz'])
['foo', 'bar', 'baz']
"""
if data is None:
return []
Expand All @@ -81,7 +80,6 @@ def maybe_float(el):
Examples:
>>> maybe_float('35.0499505')
35.0499505
"""
try:
return float(el)
Expand All @@ -101,7 +99,6 @@ def maybe_int(el):
Examples:
>>> maybe_int('10')
10
"""
try:
return int(el)
Expand Down Expand Up @@ -132,7 +129,8 @@ def remove_tags(dirty, allowed_tags=(), allowed_trees=(), strip=None):
removed.
Examples:
>>> tag = '<p><b><i>Only</i></b> this text remains.<span class="hidden">Not this one.</span></p>'
>>> tag = '<p><b><i>Only</i></b> this text remains.
<span class="hidden">Not this one.</span></p>'
>>> remove_tags(tag, allowed_tree=('b',), strip='@class="hidden"')
u'<b><i>Only</i></b> this text remains.'
>>> remove_tags(tag, allowed_tags=('b',), strip='@class="hidden"')
Expand All @@ -141,7 +139,9 @@ def remove_tags(dirty, allowed_tags=(), allowed_trees=(), strip=None):
u'<b>Only</b> this text remains.'
"""
if isinstance(dirty, six.string_types):
element = etree.fromstring(u''.join(('<DUMMYROOTTAG>', dirty, '</DUMMYROOTTAG>')))
element = etree.fromstring(
u''.join(('<DUMMYROOTTAG>', dirty, '</DUMMYROOTTAG>'))
)
elif isinstance(dirty, etree._Element):
element = dirty
else: # assuming scrapy Selector
Expand All @@ -156,7 +156,9 @@ def remove_tags(dirty, allowed_tags=(), allowed_trees=(), strip=None):
return tail

subtext = u''.join(
remove_tags(child, allowed_tags=allowed_tags, allowed_trees=allowed_trees, strip=strip)
remove_tags(
child, allowed_tags=allowed_tags, allowed_trees=allowed_trees, strip=strip
)
for child in element
)
text = element.text or u''
Expand Down
6 changes: 4 additions & 2 deletions inspire_utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ def __getattr__(self, item):
def error(self, message, *args, **kwargs):
"""Log error with stack trace and locals information.
By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry.
By default, enables stack trace information in logging messages,
so that stacktrace and locals appear in Sentry.
"""
kwargs.setdefault('extra', {}).setdefault('stack', True)
return self.logger.error(message, *args, **kwargs)


def getStackTraceLogger(*args, **kwargs):
"""Returns a :class:`StackTrace` logger that wraps a Python logger instance."""
"""Returns a :class:`StackTrace` logger that wraps a Python logger
instance."""
logger = logging.getLogger(*args, **kwargs)
return StackTraceLogger(logger)
Loading

0 comments on commit 36c7e2d

Please sign in to comment.