Run pyupgrade to clean up Python 2 syntaxes

Update all .py source files by
 $ pyupgrade --py3-only $(git ls-files | grep ".py$")
to modernize the code according to Python 3 syntaxes.

pep8 errors are fixed by
 $ autopep8 --select=E127,E128,E501 --max-line-length 79 -r \
    --in-place oslo_utils

Also add the pyupgrade hook to pre-commit to avoid merging additional
Python 2 syntaxes.

Change-Id: If34f08dc3156b75f38dfe1c5e4698952fea7abba
This commit is contained in:
Takashi Kajinami 2025-01-13 13:32:18 +09:00 committed by Jay Faulkner
parent a0c8385fdc
commit 41f5fb6e00
31 changed files with 95 additions and 107 deletions

View File

@ -1,6 +1,6 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v5.0.0
hooks:
- id: trailing-whitespace
# Replaces or checks mixed line ending
@ -19,12 +19,17 @@ repos:
- id: check-yaml
files: .*\.(yaml|yml)$
- repo: https://opendev.org/openstack/hacking
rev: 6.1.0
rev: 7.0.0
hooks:
- id: hacking
additional_dependencies: []
- repo: https://github.com/PyCQA/bandit
rev: 1.7.6
rev: 1.7.10
hooks:
- id: bandit
args: ['-x', 'tests']
- repo: https://github.com/asottile/pyupgrade
rev: v3.18.0
hooks:
- id: pyupgrade
args: [--py3-only]

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -24,6 +24,6 @@ def flatten_dict_to_keypairs(d, separator=':'):
if isinstance(value, dict):
for subname, subvalue in flatten_dict_to_keypairs(value,
separator):
yield '%s%s%s' % (name, separator, subname), subvalue
yield '{}{}{}'.format(name, separator, subname), subvalue
else:
yield name, value

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -146,14 +144,14 @@ def is_monkey_patched(module):
return _patcher.is_monkey_patched(module)
class EventletEvent(object):
class EventletEvent:
"""A class that provides consistent eventlet/threading Event API.
This wraps the eventlet.event.Event class to have the same API as
the standard threading.Event object.
"""
def __init__(self, *args, **kwargs):
super(EventletEvent, self).__init__()
super().__init__()
self.clear()
def clear(self):

View File

@ -49,7 +49,7 @@ class CausedByException(Exception):
.. versionadded:: 2.4
"""
def __init__(self, message, cause=None):
super(CausedByException, self).__init__(message)
super().__init__(message)
self.cause = cause
def __bytes__(self):
@ -142,7 +142,7 @@ def raise_with_cause(exc_cls, message, *args, **kwargs):
raise exc_cls(message, *args, **kwargs) from kwargs.get('cause')
class save_and_reraise_exception(object):
class save_and_reraise_exception:
"""Save current exception, run some code and then re-raise.
In some cases the exception context can be cleared, resulting in None
@ -287,7 +287,7 @@ def forever_retry_uncaught_exceptions(*args, **kwargs):
return decorator
class exception_filter(object):
class exception_filter:
"""A context manager that prevents some exceptions from being raised.
Use this class as a decorator for a function that returns whether a given

View File

@ -150,7 +150,7 @@ def last_bytes(path, num):
with open(path, 'rb') as fp:
try:
fp.seek(-num, os.SEEK_END)
except IOError as e:
except OSError as e:
# seek() fails with EINVAL when trying to go before the start of
# the file. It means that num is larger than the file size, so
# just go to the start.
@ -173,7 +173,7 @@ def is_json(file_path):
:returns: bool
"""
with open(file_path, 'r') as fh:
with open(file_path) as fh:
data = fh.read()
try:
json.loads(data)
@ -195,7 +195,7 @@ def is_yaml(file_path):
:returns: bool
"""
with open(file_path, 'r') as fh:
with open(file_path) as fh:
data = fh.read()
is_yaml = False
try:

View File

@ -1,4 +1,3 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
@ -37,11 +36,11 @@ class TimeFixture(fixtures.Fixture):
"""
def __init__(self, override_time=None):
super(TimeFixture, self).__init__()
super().__init__()
self._override_time = override_time
def setUp(self):
super(TimeFixture, self).setUp()
super().setUp()
timeutils.set_time_override(self._override_time)
self.addCleanup(timeutils.clear_time_override)
@ -54,7 +53,7 @@ class TimeFixture(fixtures.Fixture):
timeutils.advance_time_seconds(seconds)
class _UUIDSentinels(object):
class _UUIDSentinels:
"""Registry of dynamically created, named, random UUID strings in regular
(with hyphens) and similar to some keystone IDs (without hyphens) formats.

View File

@ -77,7 +77,7 @@ def main():
safe = False
failure_reasons = []
for exc in e.failures.items():
failure_reasons.append("%s: %s" % (exc[0], exc[1]))
failure_reasons.append("{}: {}".format(exc[0], exc[1]))
virtual_size = inspector.virtual_size
actual_size = inspector.actual_size

View File

@ -39,7 +39,7 @@ def _chunked_reader(fileobj, chunk_size=512):
yield chunk
class CaptureRegion(object):
class CaptureRegion:
"""Represents a region of a file we want to capture.
A region of a file we want to capture requires a byte offset into
@ -1416,7 +1416,7 @@ class InspectWrapper:
This will be None if a decision has not been reached.
"""
non_raw = set([i for i in self._inspectors if i.NAME != 'raw'])
non_raw = {i for i in self._inspectors if i.NAME != 'raw'}
complete = all([i.complete for i in non_raw])
matches = [i for i in non_raw if i.format_match]
if not complete and not self._finished:

View File

@ -34,7 +34,7 @@ from oslo_utils._i18n import _
from oslo_utils import strutils
class QemuImgInfo(object):
class QemuImgInfo:
"""Parse Qemu image information from command `qemu-img info`'s output.
The instance of :class:`QemuImgInfo` has properties: `image`,
@ -130,8 +130,9 @@ class QemuImgInfo(object):
# Allow abbreviated unit such as K to mean KB for compatibility.
if len(unit_of_measure) == 1 and unit_of_measure != 'B':
unit_of_measure += 'B'
return strutils.string_to_bytes('%s%s' % (magnitude, unit_of_measure),
return_int=True)
return strutils.string_to_bytes(
'{}{}'.format(magnitude, unit_of_measure),
return_int=True)
def _extract_details(self, root_cmd, root_details, lines_after):
real_details = root_details

View File

@ -57,7 +57,7 @@ def import_object_ns(name_space, import_str, *args, **kwargs):
Don't capture :exc:`ImportError` when instanciating the object, only
when importing the object class.
"""
import_value = "%s.%s" % (name_space, import_str)
import_value = "{}.{}".format(name_space, import_str)
try:
cls = import_class(import_value)
except ImportError:
@ -91,7 +91,7 @@ def import_versioned_module(module, version, submodule=None):
# NOTE(gcb) Disallow parameter version include character '.'
if '.' in '%s' % version:
raise ValueError("Parameter version shouldn't include character '.'.")
module_str = '%s.v%s' % (module, version)
module_str = '{}.v{}'.format(module, version)
if submodule:
module_str = '.'.join((module_str, submodule))
return import_module(module_str)

View File

@ -270,7 +270,7 @@ def is_ipv6_enabled():
if _IS_IPV6_ENABLED is None:
disabled_ipv6_path = "/proc/sys/net/ipv6/conf/default/disable_ipv6"
if os.path.exists(disabled_ipv6_path):
with open(disabled_ipv6_path, 'r') as f:
with open(disabled_ipv6_path) as f:
disabled = f.read().strip()
_IS_IPV6_ENABLED = disabled == "0"
else:
@ -389,7 +389,7 @@ def get_my_ipv4():
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as csock:
csock.connect(('192.0.2.0', 80))
return csock.getsockname()[0]
except socket.error:
except OSError:
return _get_my_ipv4_address()
@ -445,7 +445,7 @@ def get_my_ipv6():
with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as csock:
csock.connect(('2001:db8::1', 80))
return csock.getsockname()[0]
except socket.error:
except OSError:
return _get_my_ipv6_address()

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -88,7 +86,7 @@ def get_class_name(obj, fully_qualified=True, truncate_builtins=True):
if built_in:
return obj.__name__
if fully_qualified and hasattr(obj, '__module__'):
return '%s.%s' % (obj.__module__, obj.__name__)
return '{}.{}'.format(obj.__module__, obj.__name__)
else:
return obj.__name__

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
@ -32,7 +30,7 @@ class TestCase(testtools.TestCase):
def setUp(self):
"""Run before each test method to initialize test environment."""
super(TestCase, self).setUp()
super().setUp()
test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
try:
test_timeout = int(test_timeout)

View File

@ -13,16 +13,16 @@
# under the License.
class V2FakeDriver(object):
class V2FakeDriver:
def __init__(self, first_arg=True):
self.first_arg = first_arg
class V2FakeDriver2(object):
class V2FakeDriver2:
def __init__(self, first_arg):
self.first_arg = first_arg
class V2FakeDriver3(object):
class V2FakeDriver3:
def __init__(self):
raise ImportError("ImportError occurs in __init__")

View File

@ -42,11 +42,11 @@ def get_size_format_from_qemu_img(filename):
@ddt.ddt
class TestFormatInspectors(test_base.BaseTestCase):
def setUp(self):
super(TestFormatInspectors, self).setUp()
super().setUp()
self._created_files = []
def tearDown(self):
super(TestFormatInspectors, self).tearDown()
super().tearDown()
for fn in self._created_files:
try:
os.remove(fn)
@ -95,7 +95,7 @@ class TestFormatInspectors(test_base.BaseTestCase):
# are the same and can cause test failures
out_fn = "%s.iso" % fn
subprocess.check_output(
'%s -V "TEST" -o %s %s' % (base_cmd, out_fn, fn),
'{} -V "TEST" -o {} {}'.format(base_cmd, out_fn, fn),
shell=True)
self._created_files.append(out_fn)
return out_fn
@ -120,8 +120,8 @@ class TestFormatInspectors(test_base.BaseTestCase):
0x01, # start LBA
0x00, # size LBA
)
fn = tempfile.mktemp(prefix='%s-gpt-%s' % (TEST_IMAGE_PREFIX,
subformat))
fn = tempfile.mktemp(prefix='{}-gpt-{}'.format(TEST_IMAGE_PREFIX,
subformat))
with open(fn, 'wb') as f:
f.write(data)
self._created_files.append(fn)
@ -180,7 +180,7 @@ class TestFormatInspectors(test_base.BaseTestCase):
prefix += subformat + '-'
if options:
opt += '-o ' + ','.join('%s=%s' % (k, v)
opt += '-o ' + ','.join('{}={}'.format(k, v)
for k, v in options.items())
if backing_file is not None:
@ -218,8 +218,8 @@ class TestFormatInspectors(test_base.BaseTestCase):
# Convert it to VMDK
subprocess.check_output(
'qemu-img convert -f raw -O vmdk -o subformat=%s -S 0 %s %s' % (
subformat, raw, fn),
'qemu-img convert -f raw -O vmdk -o subformat={} -S 0 {} {}'
.format(subformat, raw, fn),
shell=True)
return fn
@ -334,10 +334,10 @@ class TestFormatInspectors(test_base.BaseTestCase):
fn = tempfile.mktemp(prefix=prefix, suffix='.iso')
self._created_files.append(fn)
subprocess.check_output(
'dd if=%s of=%s bs=32K count=1' % (qcow, fn),
'dd if={} of={} bs=32K count=1'.format(qcow, fn),
shell=True)
subprocess.check_output(
'dd if=%s of=%s bs=32K skip=1 seek=1' % (iso, fn),
'dd if={} of={} bs=32K skip=1 seek=1'.format(iso, fn),
shell=True)
return qcow, iso, fn

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2016 EasyStack Inc.
# All Rights Reserved.
#

View File

@ -25,12 +25,12 @@ from oslo_utils import eventletutils
class EventletUtilsTest(test_base.BaseTestCase):
def setUp(self):
super(EventletUtilsTest, self).setUp()
super().setUp()
self._old_avail = eventletutils.EVENTLET_AVAILABLE
eventletutils.EVENTLET_AVAILABLE = True
def tearDown(self):
super(EventletUtilsTest, self).tearDown()
super().tearDown()
eventletutils.EVENTLET_AVAILABLE = self._old_avail
@mock.patch("oslo_utils.eventletutils._patcher")

View File

@ -63,7 +63,7 @@ class SaveAndReraiseTest(test_base.BaseTestCase):
def _force_reraise():
try:
raise IOError("I broke")
raise OSError("I broke")
except Exception:
with excutils.save_and_reraise_exception() as e:
e.reraise = False
@ -75,7 +75,7 @@ class SaveAndReraiseTest(test_base.BaseTestCase):
def _force_reraise():
try:
raise IOError("I broke")
raise OSError("I broke")
except Exception:
excutils.save_and_reraise_exception().capture().force_reraise()
@ -163,7 +163,7 @@ class SaveAndReraiseTest(test_base.BaseTestCase):
class ForeverRetryUncaughtExceptionsTest(test_base.BaseTestCase):
def setUp(self):
super(ForeverRetryUncaughtExceptionsTest, self).setUp()
super().setUp()
self._exceptions = []
@ -437,7 +437,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
return ignore_exceptions
def _make_filter_method(self, ignore_classes=AssertionError):
class ExceptionIgnorer(object):
class ExceptionIgnorer:
def __init__(self, ignore):
self.ignore = ignore
@ -449,7 +449,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
return ExceptionIgnorer(ignore_classes).ignore_exceptions
def _make_filter_classmethod(self, ignore_classes=AssertionError):
class ExceptionIgnorer(object):
class ExceptionIgnorer:
ignore = ignore_classes
@excutils.exception_filter
@ -461,7 +461,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
return ExceptionIgnorer.ignore_exceptions
def _make_filter_staticmethod(self, ignore_classes=AssertionError):
class ExceptionIgnorer(object):
class ExceptionIgnorer:
@excutils.exception_filter
@staticmethod
def ignore_exceptions(ex):

View File

@ -36,7 +36,7 @@ class EnsureTree(test_base.BaseTestCase):
def test_ensure_tree(self):
tmpdir = tempfile.mkdtemp()
try:
testdir = '%s/foo/bar/baz' % (tmpdir,)
testdir = '{}/foo/bar/baz'.format(tmpdir)
fileutils.ensure_tree(testdir, TEST_PERMISSIONS)
self.assertTrue(os.path.isdir(testdir))
self.assertEqual(os.stat(testdir).st_mode,
@ -124,11 +124,11 @@ class RemovePathOnError(test_base.BaseTestCase):
class WriteToTempfileTestCase(test_base.BaseTestCase):
def setUp(self):
super(WriteToTempfileTestCase, self).setUp()
self.content = 'testing123'.encode('ascii')
super().setUp()
self.content = b'testing123'
def check_file_content(self, path):
with open(path, 'r') as fd:
with open(path) as fd:
ans = fd.read()
self.assertEqual(self.content, ans.encode("latin-1"))
@ -197,11 +197,11 @@ class WriteToTempfileTestCase(test_base.BaseTestCase):
class TestComputeFileChecksum(test_base.BaseTestCase):
def setUp(self):
super(TestComputeFileChecksum, self).setUp()
self.content = 'fake_content'.encode('ascii')
super().setUp()
self.content = b'fake_content'
def check_file_content(self, content, path):
with open(path, 'r') as fd:
with open(path) as fd:
ans = fd.read()
self.assertEqual(content, ans.encode("latin-1"))
@ -269,7 +269,7 @@ class LastBytesTestCase(test_base.BaseTestCase):
"""Test the last_bytes() utility method."""
def setUp(self):
super(LastBytesTestCase, self).setUp()
super().setUp()
self.content = b'1234567890'
def test_truncated(self):
@ -295,7 +295,7 @@ class FileTypeTestCase(test_base.BaseTestCase):
"""Test the is_yaml() and is_json() utility methods."""
def setUp(self):
super(FileTypeTestCase, self).setUp()
super().setUp()
data = {
'name': 'test',
'website': 'example.com'

View File

@ -1,4 +1,3 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#

View File

@ -513,7 +513,7 @@ def mock_file_content(content):
class TestIsIPv6Enabled(test_base.BaseTestCase):
def setUp(self):
super(TestIsIPv6Enabled, self).setUp()
super().setUp()
def reset_detection_flag():
netutils._IS_IPV6_ENABLED = None

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -47,7 +45,7 @@ def function_with_kwargs(a, b, **kwargs):
pass
class TestObject(object):
class TestObject:
def _hello(self):
pass
@ -55,7 +53,7 @@ class TestObject(object):
pass
class Class(object):
class Class:
def method(self, c, d):
pass
@ -69,7 +67,7 @@ class Class(object):
pass
class BadClass(object):
class BadClass:
def do_something(self):
pass
@ -77,12 +75,12 @@ class BadClass(object):
return False
class CallableClass(object):
class CallableClass:
def __call__(self, i, j):
pass
class ClassWithInit(object):
class ClassWithInit:
def __init__(self, k, lll):
pass
@ -123,7 +121,7 @@ class CallbackEqualityTest(test_base.BaseTestCase):
def test_static_instance_callbacks(self):
class A(object):
class A:
@staticmethod
def b(a, b, c):
@ -136,7 +134,7 @@ class CallbackEqualityTest(test_base.BaseTestCase):
def test_different_instance_callbacks(self):
class A(object):
class A:
def b(self):
pass
@ -201,7 +199,7 @@ class GetCallableNameTest(test_base.BaseTestCase):
class GetCallableNameTestExtended(test_base.BaseTestCase):
# Tests items in http://legacy.python.org/dev/peps/pep-3155/
class InnerCallableClass(object):
class InnerCallableClass:
def __call__(self):
pass
@ -298,7 +296,7 @@ class GetClassNameTest(test_base.BaseTestCase):
self.assertEqual('.'.join((__name__, 'Class')), name)
def test_qualified_class(self):
class QualifiedClass(object):
class QualifiedClass:
pass
name = reflection.get_class_name(QualifiedClass)

View File

@ -31,7 +31,7 @@ class SecretUtilsTest(testscenarios.TestWithScenarios,
('unicode', {'converter': lambda text: text}),
]
_test_data = "Openstack forever".encode('utf-8')
_test_data = b"Openstack forever"
_md5_digest = hashlib.md5(_test_data).digest()
def test_md5_with_data(self):

View File

@ -170,7 +170,7 @@ class StrUtilsTest(test_base.BaseTestCase):
self.assertEqual("ju5tnum8er", to_slug("ju5tnum8er"))
self.assertEqual("strip-", to_slug(" strip - "))
self.assertEqual("perche",
to_slug("perch\xc3\xa9".encode("latin-1")))
to_slug(b"perch\xc3\xa9"))
self.assertEqual("strange",
to_slug("\x80strange", errors="ignore"))
@ -250,7 +250,7 @@ class StringToBytesTest(test_base.BaseTestCase):
def test_string_to_bytes(self):
def _get_quantity(sign, magnitude, unit_suffix):
res = float('%s%s' % (sign, magnitude))
res = float('{}{}'.format(sign, magnitude))
if unit_suffix in ['b', 'bit']:
res /= 8
return res
@ -689,7 +689,7 @@ class MaskPasswordTestCase(test_base.BaseTestCase):
class TestMapping(collections.abc.Mapping):
"""Test class for non-dict mappings"""
def __init__(self):
super(TestMapping, self).__init__()
super().__init__()
self.data = {'password': 'shhh',
'foo': 'bar',
}
@ -707,7 +707,7 @@ class TestMapping(collections.abc.Mapping):
class NestedMapping(TestMapping):
"""Test class that contains an instance of TestMapping"""
def __init__(self):
super(NestedMapping, self).__init__()
super().__init__()
self.data = {'nested': TestMapping()}

View File

@ -34,7 +34,7 @@ def monotonic_iter(start=0, incr=0.05):
class TimeUtilsTest(test_base.BaseTestCase):
def setUp(self):
super(TimeUtilsTest, self).setUp()
super().setUp()
self.skynet_self_aware_time_str = '1997-08-29T06:14:00Z'
self.skynet_self_aware_time_ms_str = '1997-08-29T06:14:00.000123Z'
self.skynet_self_aware_time = datetime.datetime(1997, 8, 29, 6, 14, 0)
@ -361,7 +361,7 @@ class TimeItTest(test_base.BaseTestCase):
@timeutils.time_it(fake_logger)
def broken_function():
raise IOError("Broken")
raise OSError("Broken")
self.assertRaises(IOError, broken_function)
self.assertFalse(fake_logger.log.called)

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014 Red Hat, Inc.
# All Rights Reserved.
#
@ -29,19 +27,19 @@ class EncodeUtilsTest(test_base.BaseTestCase):
safe_decode = encodeutils.safe_decode
self.assertRaises(TypeError, safe_decode, True)
self.assertEqual('ni\xf1o',
safe_decode("ni\xc3\xb1o".encode("latin-1"),
safe_decode(b"ni\xc3\xb1o",
incoming="utf-8"))
self.assertEqual("strange",
safe_decode('\x80strange'.encode("latin-1"),
safe_decode(b'\x80strange',
errors='ignore'))
self.assertEqual('\xc0', safe_decode('\xc0'.encode("latin-1"),
self.assertEqual('\xc0', safe_decode(b'\xc0',
incoming='iso-8859-1'))
# Forcing incoming to ascii so it falls back to utf-8
self.assertEqual('ni\xf1o',
safe_decode('ni\xc3\xb1o'.encode("latin-1"),
safe_decode(b'ni\xc3\xb1o',
incoming='ascii'))
self.assertEqual('foo', safe_decode(b'foo'))
@ -67,8 +65,8 @@ class EncodeUtilsTest(test_base.BaseTestCase):
def test_safe_encode_force_incoming_utf8_to_ascii(self):
# Forcing incoming to ascii so it falls back to utf-8
self.assertEqual(
'ni\xc3\xb1o'.encode("latin-1"),
encodeutils.safe_encode('ni\xc3\xb1o'.encode("latin-1"),
b'ni\xc3\xb1o',
encodeutils.safe_encode(b'ni\xc3\xb1o',
incoming='ascii'),
)
@ -91,7 +89,7 @@ class EncodeUtilsTest(test_base.BaseTestCase):
result = encodeutils.safe_encode(
text=text, incoming='utf-8', encoding='iso-8859-1')
self.assertNotEqual(text, result)
self.assertNotEqual("foo\xf1bar".encode("latin-1"), result)
self.assertNotEqual(b"foo\xf1bar", result)
def test_to_utf8(self):
self.assertEqual(encodeutils.to_utf8(b'a\xe9\xff'), # bytes

View File

@ -254,7 +254,7 @@ def is_soon(dt, window):
return normalize_time(dt) <= soon
class Split(object):
class Split:
"""A *immutable* stopwatch split.
See: http://en.wikipedia.org/wiki/Stopwatch for what this is/represents.
@ -280,7 +280,7 @@ class Split(object):
def __repr__(self):
r = reflection.get_class_name(self, fully_qualified=False)
r += "(elapsed=%s, length=%s)" % (self._elapsed, self._length)
r += "(elapsed={}, length={})".format(self._elapsed, self._length)
return r
@ -331,7 +331,7 @@ def time_it(logger, log_level=logging.DEBUG,
return decorator
class StopWatch(object):
class StopWatch:
"""A simple timer/stopwatch helper class.
Inspired by: apache-commons-lang java stopwatch.

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -28,7 +28,7 @@ from oslo_utils import strutils
# http://dl.sileht.net/public/payload.json.gz
infile = 'large_json_payload.txt'
with open(infile, 'r') as f:
with open(infile) as f:
input_str = f.read()
print('payload has %d bytes' % len(input_str))
@ -38,9 +38,9 @@ for pattern in strutils._SANITIZE_PATTERNS_2['admin_pass']:
r"re.sub(pattern, r'\g<1>***\g<2>', payload)",
"""
import re
payload = '''%s'''
pattern = re.compile(r'''%s''')
""" % (input_str, pattern.pattern))
payload = '''{}'''
pattern = re.compile(r'''{}''')
""".format(input_str, pattern.pattern))
print(t.timeit(1))
t = timeit.Timer(