Skip to content

Commit

Permalink
Upgrade code with pyupgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
sdispater committed Oct 18, 2021
1 parent c768a15 commit 9cfef0a
Show file tree
Hide file tree
Showing 88 changed files with 160 additions and 379 deletions.
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ repos:
additional_dependencies: [toml]
exclude: ^.*/?setup\.py$

- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
- id: pyupgrade

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
Expand Down
24 changes: 8 additions & 16 deletions clock
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
from __future__ import unicode_literals

import glob
import json
Expand Down Expand Up @@ -41,7 +40,7 @@ class _LambdaCompiler(_GettextCompiler):
code = code.replace("||", "or")
if method == "in":
expr = self.compile(expr)
code = "(%s == %s and %s)" % (expr, expr, code)
code = f"({expr} == {expr} and {code})"
return code


Expand All @@ -52,10 +51,7 @@ class LocaleCreate(Command):

arguments = [argument("locales", "Locales to dump.", optional=False, multiple=True)]

TEMPLATE = """# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .custom import translations as custom_translations
TEMPLATE = """from .custom import translations as custom_translations
\"\"\"
Expand All @@ -73,11 +69,7 @@ locale = {{
}}
"""

CUSTOM_TEMPLATE = """# -*- coding: utf-8 -*-
from __future__ import unicode_literals
\"\"\"
CUSTOM_TEMPLATE = """\"\"\"
{locale} custom locale file.
\"\"\"
Expand All @@ -99,10 +91,10 @@ translations = {{}}

normalized = normalize_locale(locale.replace("-", "_"))
if not normalized:
self.line("<error>Locale [{}] does not exist.</error>".format(locale))
self.line(f"<error>Locale [{locale}] does not exist.</error>")
continue

self.line("<info>Generating <comment>{}</> locale.</>".format(locale))
self.line(f"<info>Generating <comment>{locale}</> locale.</>")

content = LocaleDataDict(load(normalized))

Expand Down Expand Up @@ -140,7 +132,7 @@ translations = {{}}
]
data["units"] = {}
for unit in units:
pattern = patterns["duration-{}".format(unit)]["long"]
pattern = patterns[f"duration-{unit}"]["long"]
if "per" in pattern:
del pattern["per"]

Expand Down Expand Up @@ -199,7 +191,7 @@ translations = {{}}
else:
v = repr(v)

s.append("%s%r: %s,\n" % (" " * tab, k, v))
s.append("{}{!r}: {},\n".format(" " * tab, k, v))
s.append("%s}" % (" " * (tab - 1)))

return "".join(s)
Expand All @@ -208,7 +200,7 @@ translations = {{}}
to_py = _LambdaCompiler().compile
result = ["lambda n: "]
for tag, ast in PluralRule.parse(rule).abstract:
result.append("'%s' if %s else " % (tag, to_py(ast)))
result.append("'{}' if {} else ".format(tag, to_py(ast)))
result.append("'other'")
return "".join(result)

Expand Down
23 changes: 10 additions & 13 deletions pendulum/date.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
from __future__ import absolute_import
from __future__ import division

import calendar
import math

Expand Down Expand Up @@ -399,9 +396,9 @@ def start_of(self, unit):
:rtype: Date
"""
if unit not in self._MODIFIERS_VALID_UNITS:
raise ValueError('Invalid unit "{}" for start_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for start_of()')

return getattr(self, "_start_of_{}".format(unit))()
return getattr(self, f"_start_of_{unit}")()

def end_of(self, unit):
"""
Expand Down Expand Up @@ -603,9 +600,9 @@ def first_of(self, unit, day_of_week=None):
:rtype: Date
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for first_of()')

return getattr(self, "_first_of_{}".format(unit))(day_of_week)
return getattr(self, f"_first_of_{unit}")(day_of_week)

def last_of(self, unit, day_of_week=None):
"""
Expand All @@ -624,9 +621,9 @@ def last_of(self, unit, day_of_week=None):
:rtype: Date
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for first_of()')

return getattr(self, "_last_of_{}".format(unit))(day_of_week)
return getattr(self, f"_last_of_{unit}")(day_of_week)

def nth_of(self, unit, nth, day_of_week):
"""
Expand All @@ -648,9 +645,9 @@ def nth_of(self, unit, nth, day_of_week):
:rtype: Date
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for first_of()')

dt = getattr(self, "_nth_of_{}".format(unit))(nth, day_of_week)
dt = getattr(self, f"_nth_of_{unit}")(nth, day_of_week)
if dt is False:
raise PendulumException(
"Unable to find occurence {} of {} in {}".format(
Expand Down Expand Up @@ -873,13 +870,13 @@ def today(cls):

@classmethod
def fromtimestamp(cls, t):
dt = super(Date, cls).fromtimestamp(t)
dt = super().fromtimestamp(t)

return cls(dt.year, dt.month, dt.day)

@classmethod
def fromordinal(cls, n):
dt = super(Date, cls).fromordinal(n)
dt = super().fromordinal(n)

return cls(dt.year, dt.month, dt.day)

Expand Down
24 changes: 10 additions & 14 deletions pendulum/datetime.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division

import calendar
import datetime

Expand Down Expand Up @@ -350,7 +346,7 @@ def _to_string(self, fmt: str, locale: Optional[str] = None) -> str:
Format the instance to a common string format.
"""
if fmt not in self._FORMATS:
raise ValueError("Format [{}] is not supported".format(fmt))
raise ValueError(f"Format [{fmt}] is not supported")

fmt = self._FORMATS[fmt]
if callable(fmt):
Expand All @@ -364,7 +360,7 @@ def __str__(self) -> str:
def __repr__(self) -> str:
us = ""
if self.microsecond:
us = ", {}".format(self.microsecond)
us = f", {self.microsecond}"

repr_ = "{klass}(" "{year}, {month}, {day}, " "{hour}, {minute}, {second}{us}"

Expand Down Expand Up @@ -665,9 +661,9 @@ def start_of(self, unit: str) -> "DateTime":
* century: date to first day of century and time to 00:00:00
"""
if unit not in self._MODIFIERS_VALID_UNITS:
raise ValueError('Invalid unit "{}" for start_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for start_of()')

return getattr(self, "_start_of_{}".format(unit))()
return getattr(self, f"_start_of_{unit}")()

def end_of(self, unit: str) -> "DateTime":
"""
Expand Down Expand Up @@ -884,9 +880,9 @@ def first_of(self, unit: str, day_of_week: Optional[int] = None) -> "DateTime":
Supported units are month, quarter and year.
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for first_of()')

return getattr(self, "_first_of_{}".format(unit))(day_of_week)
return getattr(self, f"_first_of_{unit}")(day_of_week)

def last_of(self, unit: str, day_of_week: Optional[int] = None) -> "DateTime":
"""
Expand All @@ -898,9 +894,9 @@ def last_of(self, unit: str, day_of_week: Optional[int] = None) -> "DateTime":
Supported units are month, quarter and year.
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for first_of()')

return getattr(self, "_last_of_{}".format(unit))(day_of_week)
return getattr(self, f"_last_of_{unit}")(day_of_week)

def nth_of(self, unit: str, nth: int, day_of_week: int) -> "DateTime":
"""
Expand All @@ -913,9 +909,9 @@ def nth_of(self, unit: str, nth: int, day_of_week: int) -> "DateTime":
Supported units are month, quarter and year.
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError('Invalid unit "{}" for first_of()'.format(unit))
raise ValueError(f'Invalid unit "{unit}" for first_of()')

dt = getattr(self, "_nth_of_{}".format(unit))(nth, day_of_week)
dt = getattr(self, f"_nth_of_{unit}")(nth, day_of_week)
if dt is False:
raise PendulumException(
"Unable to find occurence {} of {} in {}".format(
Expand Down
21 changes: 9 additions & 12 deletions pendulum/duration.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
from __future__ import absolute_import
from __future__ import division

from datetime import timedelta

import pendulum
Expand Down Expand Up @@ -275,31 +272,31 @@ def __str__(self):
return self.in_words()

def __repr__(self):
rep = "{}(".format(self.__class__.__name__)
rep = f"{self.__class__.__name__}("

if self._years:
rep += "years={}, ".format(self._years)
rep += f"years={self._years}, "

if self._months:
rep += "months={}, ".format(self._months)
rep += f"months={self._months}, "

if self._weeks:
rep += "weeks={}, ".format(self._weeks)
rep += f"weeks={self._weeks}, "

if self._days:
rep += "days={}, ".format(self._remaining_days)
rep += f"days={self._remaining_days}, "

if self.hours:
rep += "hours={}, ".format(self.hours)
rep += f"hours={self.hours}, "

if self.minutes:
rep += "minutes={}, ".format(self.minutes)
rep += f"minutes={self.minutes}, "

if self.remaining_seconds:
rep += "seconds={}, ".format(self.remaining_seconds)
rep += f"seconds={self.remaining_seconds}, "

if self.microseconds:
rep += "microseconds={}, ".format(self.microseconds)
rep += f"microseconds={self.microseconds}, "

rep += ")"

Expand Down
10 changes: 5 additions & 5 deletions pendulum/formatting/difference_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from ..locales.locale import Locale


class DifferenceFormatter(object):
class DifferenceFormatter:
"""
Handles formatting differences in text.
"""
Expand Down Expand Up @@ -105,14 +105,14 @@ def format(
count = 1

if absolute:
key = "translations.units.{}".format(unit)
key = f"translations.units.{unit}"
else:
is_future = diff.invert

if is_now:
# Relative to now, so we can use
# the CLDR data
key = "translations.relative.{}".format(unit)
key = f"translations.relative.{unit}"

if is_future:
key += ".future"
Expand All @@ -125,9 +125,9 @@ def format(
# Checking for special pluralization rules
key = "custom.units_relative"
if is_future:
key += ".{}.future".format(unit)
key += f".{unit}.future"
else:
key += ".{}.past".format(unit)
key += f".{unit}.past"

trans = locale.get(key)
if not trans:
Expand Down
Loading

0 comments on commit 9cfef0a

Please sign in to comment.