Skip to content

Commit

Permalink
Update syntax with pyupgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
WyattBlue committed Oct 15, 2023
1 parent 7d7065d commit 54aaeab
Show file tree
Hide file tree
Showing 26 changed files with 75 additions and 81 deletions.
6 changes: 3 additions & 3 deletions av/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def cached_download(url, name):

clean_name = os.path.normpath(name)
if clean_name != name:
raise ValueError("{} is not normalized.".format(name))
raise ValueError(f"{name} is not normalized.")

for dir_ in iter_data_dirs():
path = os.path.join(dir_, name)
Expand All @@ -72,11 +72,11 @@ def cached_download(url, name):
dir_ = next(iter_data_dirs(True))
path = os.path.join(dir_, name)

log.info("Downloading {} to {}".format(url, path))
log.info(f"Downloading {url} to {path}")

response = urlopen(url)
if response.getcode() != 200:
raise ValueError("HTTP {}".format(response.getcode()))
raise ValueError(f"HTTP {response.getcode()}")

dir_ = os.path.dirname(path)
try:
Expand Down
6 changes: 3 additions & 3 deletions av/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class MethodDeprecationWarning(AVDeprecationWarning):
warnings.filterwarnings("default", "", AVDeprecationWarning)


class renamed_attr(object):
class renamed_attr:

"""Proxy for renamed attributes (or methods) on classes.
Getting and setting values will be redirected to the provided name,
Expand Down Expand Up @@ -68,14 +68,14 @@ def __set__(self, instance, value):
setattr(instance, self.new_name, value)


class method(object):
class method:
def __init__(self, func):
functools.update_wrapper(self, func, ("__name__", "__doc__"))
self.func = func

def __get__(self, instance, cls):
warning = MethodDeprecationWarning(
"{}.{} is deprecated.".format(cls.__name__, self.func.__name__)
f"{cls.__name__}.{self.func.__name__} is deprecated."
)
warnings.warn(warning, stacklevel=2)
return self.func.__get__(instance, cls)
5 changes: 2 additions & 3 deletions docs/api/error_table.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import av


Expand All @@ -21,8 +20,8 @@

rows.append((
#'{} ({})'.format(enum.tag, code),
'``av.{}``'.format(cls.__name__),
'``av.error.{}``'.format(enum.name),
f'``av.{cls.__name__}``',
f'``av.error.{enum.name}``',
enum.strerror,
))

Expand Down
15 changes: 7 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# PyAV documentation build configuration file, created by
# sphinx-quickstart on Fri Dec 7 22:13:16 2012.
Expand Down Expand Up @@ -29,7 +28,7 @@


if sphinx.version_info < (1, 8):
print("Sphinx {} is too old; we require >= 1.8.".format(sphinx.__version__), file=sys.stderr)
print(f"Sphinx {sphinx.__version__} is too old; we require >= 1.8.", file=sys.stderr)
exit(1)


Expand Down Expand Up @@ -72,8 +71,8 @@
master_doc = 'index'

# General information about the project.
project = u'PyAV'
copyright = u'2017, Mike Boers'
project = 'PyAV'
copyright = '2017, Mike Boers'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -350,8 +349,8 @@ def makerow(*texts):
return row

thead += makerow(
'{} Attribute'.format(cls.__name__) if cls else None,
'{} Name'.format(enum.__name__),
f'{cls.__name__} Attribute' if cls else None,
f'{enum.__name__} Name',
'Flag Value',
'Meaning in FFmpeg',
)
Expand All @@ -371,7 +370,7 @@ def makerow(*texts):
continue
attr = None

value = '0x{:X}'.format(item.value)
value = f'0x{item.value:X}'

doc = item.__doc__ or '-'

Expand Down Expand Up @@ -420,7 +419,7 @@ def doxylink_create_handler(app, file_name, url_base):
parent = parent_map.get(node)
parent_name = parent.find('name') if parent else None
if parent_name is not None:
name = '{}.{}'.format(parent_name.text, name)
name = f'{parent_name.text}.{name}'

filenode = node.find('filename')
if filenode is not None:
Expand Down
20 changes: 10 additions & 10 deletions docs/development/includes.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
class Visitor(TreeVisitor):

def __init__(self, state=None):
super(Visitor, self).__init__()
super().__init__()
self.state = dict(state or {})
self.events = []

Expand Down Expand Up @@ -160,14 +160,14 @@ def inspect_member(node, name_prefix=''):
anchorfile = node.find('anchorfile').text
anchor = node.find('anchor').text

url = '%s/%s#%s' % (doxygen_base, anchorfile, anchor)
url = '{}/{}#{}'.format(doxygen_base, anchorfile, anchor)

doxygen[name] = {'url': url}

if node.attrib['kind'] == 'function':
ret_type = node.find('type').text
arglist = node.find('arglist').text
sig = '%s %s%s' % (ret_type, name, arglist)
sig = '{} {}{}'.format(ret_type, name, arglist)
doxygen[name]['sig'] = sig

for struct in root.iter('compound'):
Expand All @@ -190,7 +190,7 @@ def inspect_member(node, name_prefix=''):
try:
events = extract(path)
except Exception as e:
print(" %s in %s" % (e.__class__.__name__, path), file=sys.stderr)
print(" {} in {}".format(e.__class__.__name__, path), file=sys.stderr)
print(" %s" % e, file=sys.stderr)
continue
for event in events:
Expand Down Expand Up @@ -249,7 +249,7 @@ def inspect_member(node, name_prefix=''):
elif event['type'] == 'variable':
struct = event.get('struct')
if struct:
event['_headline'] = '.. c:member:: %s %s' % (event['vartype'], event['name'])
event['_headline'] = '.. c:member:: {} {}'.format(event['vartype'], event['name'])
event['_sort_key'] = 1.1
else:
event['_headline'] = '.. c:var:: %s' % event['name']
Expand All @@ -258,14 +258,14 @@ def inspect_member(node, name_prefix=''):
elif event['type'] == 'struct':
event['_headline'] = '.. c:type:: struct %s' % event['name']
event['_sort_key'] = 1
event['_doxygen_url'] = '%s/struct%s.html' % (doxygen_base, event['name'])
event['_doxygen_url'] = '{}/struct{}.html'.format(doxygen_base, event['name'])

else:
print('Unknown event type %s' % event['type'], file=sys.stderr)

name = event['name']
if event.get('struct'):
name = '%s.%s' % (event['struct'], name)
name = '{}.{}'.format(event['struct'], name)

# Doxygen URLs
event.setdefault('_doxygen_url', doxygen.get(name, {}).get('url'))
Expand All @@ -285,13 +285,13 @@ def inspect_member(node, name_prefix=''):
prefix = '.'.join(chunks) + '.' if chunks else ''

if ref.get('property'):
ref_pairs.append((ref['property'], ':attr:`%s%s`' % (prefix, ref['property'])))
ref_pairs.append((ref['property'], ':attr:`{}{}`'.format(prefix, ref['property'])))
elif ref.get('function'):
name = ref['function']
if name in ('__init__', '__cinit__', '__dealloc__'):
ref_pairs.append((name, ':class:`%s%s <%s>`' % (prefix, name, prefix.rstrip('.'))))
ref_pairs.append((name, ':class:`{}{} <{}>`'.format(prefix, name, prefix.rstrip('.'))))
else:
ref_pairs.append((name, ':func:`%s%s`' % (prefix, name)))
ref_pairs.append((name, ':func:`{}{}`'.format(prefix, name)))
else:
continue

Expand Down
2 changes: 1 addition & 1 deletion examples/basics/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
chunk = fh.read(1 << 16)

packets = codec.parse(chunk)
print("Parsed {} packets from {} bytes:".format(len(packets), len(chunk)))
print(f"Parsed {len(packets)} packets from {len(chunk)} bytes:")

for packet in packets:

Expand Down
2 changes: 1 addition & 1 deletion examples/basics/save_keyframes.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@

# We use `frame.pts` as `frame.index` won't make must sense with the `skip_frame`.
frame.to_image().save(
"night-sky.{:04d}.jpg".format(frame.pts),
f"night-sky.{frame.pts:04d}.jpg",
quality=80,
)
4 changes: 2 additions & 2 deletions examples/basics/thread_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@
container.close()


print("Decoded with default threading in {:.2f}s.".format(default_time))
print("Decoded with auto threading in {:.2f}s.".format(auto_time))
print(f"Decoded with default threading in {default_time:.2f}s.")
print(f"Decoded with auto threading in {auto_time:.2f}s.")
2 changes: 1 addition & 1 deletion scratchpad/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def print_data(frame):
try:
for frame in frames:
ffplay.stdin.write(bytes(frame.planes[0]))
except IOError as e:
except OSError as e:
print(e)
exit()

Expand Down
2 changes: 1 addition & 1 deletion scratchpad/audio_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def decode_iter():
bytes_buffered = output.bufferSize() - output.bytesFree()
us_processed = output.processedUSecs()
us_buffered = 1000000 * bytes_buffered / (2 * 16 / 8) / 48000
print('pts: %.3f, played: %.3f, buffered: %.3f' % (frame.time or 0, us_processed / 1000000.0, us_buffered / 1000000.0))
print('pts: {:.3f}, played: {:.3f}, buffered: {:.3f}'.format(frame.time or 0, us_processed / 1000000.0, us_buffered / 1000000.0))


data = bytes(frame.planes[0])
Expand Down
2 changes: 1 addition & 1 deletion scratchpad/cctx_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
print(cc)


fh = open('test.mp4', 'r')
fh = open('test.mp4')

frame_count = 0

Expand Down
8 changes: 4 additions & 4 deletions scratchpad/decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
def format_time(time, time_base):
if time is None:
return 'None'
return '%.3fs (%s or %s/%s)' % (time_base * time, time_base * time, time_base.numerator * time, time_base.denominator)
return '{:.3f}s ({} or {}/{})'.format(time_base * time, time_base * time, time_base.numerator * time, time_base.denominator)


arg_parser = argparse.ArgumentParser()
Expand Down Expand Up @@ -45,7 +45,7 @@ def format_time(time, time_base):
print('\tduration:', float(container.duration) / time_base)
print('\tmetadata:')
for k, v in sorted(container.metadata.items()):
print('\t\t%s: %r' % (k, v))
print('\t\t{}: {!r}'.format(k, v))
print()

print(len(container.streams), 'stream(s):')
Expand Down Expand Up @@ -79,7 +79,7 @@ def format_time(time, time_base):

print('\t\tmetadata:')
for k, v in sorted(stream.metadata.items()):
print('\t\t\t%s: %r' % (k, v))
print('\t\t\t{}: {!r}'.format(k, v))

print()

Expand Down Expand Up @@ -145,7 +145,7 @@ def format_time(time, time_base):
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
try:
proc.stdin.write(bytes(frame.planes[0]))
except IOError as e:
except OSError as e:
print(e)
exit()

Expand Down
6 changes: 3 additions & 3 deletions scratchpad/filter_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def init_filter_graph():
OUTPUT_SAMPLE_RATE,
OUTPUT_CHANNEL_LAYOUT
)
print('Output format: {}'.format(output_format))
print(f'Output format: {output_format}')

# initialize filters
filter_chain = [
Expand All @@ -52,7 +52,7 @@ def init_filter_graph():
# link up the filters into a chain
print('Filter graph:')
for c, n in zip(filter_chain, filter_chain[1:]):
print('\t{} -> {}'.format(c, n))
print(f'\t{c} -> {n}')
c.link_to(n)

# initialize the filter graph
Expand Down Expand Up @@ -86,7 +86,7 @@ def process_output(frame):
data = frame.to_ndarray()
for i in range(data.shape[0]):
m = hashlib.md5(data[i, :].tobytes())
print('Plane: {:0d} checksum: {}'.format(i, m.hexdigest()))
print(f'Plane: {i:0d} checksum: {m.hexdigest()}')


def main(duration):
Expand Down
14 changes: 7 additions & 7 deletions scratchpad/frame_seek_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class FrameGrabber(QtCore.QObject):
update_frame_range = QtCore.pyqtSignal(object)

def __init__(self, parent=None):
super(FrameGrabber, self).__init__(parent)
super().__init__(parent)
self.file = None
self.stream = None
self.frame = None
Expand Down Expand Up @@ -263,7 +263,7 @@ def set_file(self, path):

class DisplayWidget(QtGui.QLabel):
def __init__(self, parent=None):
super(DisplayWidget, self).__init__(parent)
super().__init__(parent)
#self.setScaledContents(True)
self.setMinimumSize(1920 / 10, 1080 / 10)

Expand All @@ -286,15 +286,15 @@ def setPixmap(self, img, index):
self.pixmap = QtGui.QPixmap.fromImage(img)

#super(DisplayWidget, self).setPixmap(self.pixmap)
super(DisplayWidget, self).setPixmap(self.pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
super().setPixmap(self.pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

def sizeHint(self):
width = self.width()
return QtCore.QSize(width, self.heightForWidth(width))

def resizeEvent(self, event):
if self.pixmap:
super(DisplayWidget, self).setPixmap(self.pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
super().setPixmap(self.pixmap.scaled(self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

def sizeHint(self):
return QtCore.QSize(1920 / 2.5, 1080 / 2.5)
Expand All @@ -307,7 +307,7 @@ class VideoPlayerWidget(QtGui.QWidget):
load_file = QtCore.pyqtSignal(object)

def __init__(self, parent=None):
super(VideoPlayerWidget, self).__init__(parent)
super().__init__(parent)
self.display = DisplayWidget()
self.timeline = QtGui.QScrollBar(Qt.Horizontal)
self.frame_grabber = FrameGrabber()
Expand Down Expand Up @@ -378,15 +378,15 @@ def keyPressEvent(self, event):
self.timeline.setValue(self.timeline.value() + direction)

else:
super(VideoPlayerWidget, self).keyPressEvent(event)
super().keyPressEvent(event)

def mousePressEvent(self, event):
# clear focus of spinbox
focused_widget = QtGui.QApplication.focusWidget()
if focused_widget:
focused_widget.clearFocus()

super(VideoPlayerWidget, self).mousePressEvent(event)
super().mousePressEvent(event)

def dragEnterEvent(self, event):
event.accept()
Expand Down
2 changes: 1 addition & 1 deletion scratchpad/glproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
'''.strip().split()


class ModuleProxy(object):
class ModuleProxy:

def __init__(self, name, module):
self.name = name
Expand Down
2 changes: 1 addition & 1 deletion scratchpad/qtproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from PyQt4 import QtCore, QtGui, QtOpenGL, QtMultimedia


class QtProxy(object):
class QtProxy:

def __init__(self, *modules):
self._modules = modules
Expand Down
2 changes: 1 addition & 1 deletion scratchpad/resource_use.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ def format_bytes(n):
for i in range(len(usage) - 1):
before = usage[i]
after = usage[i + 1]
print('%s (%s)' % (format_bytes(after.ru_maxrss), format_bytes(after.ru_maxrss - before.ru_maxrss)))
print('{} ({})'.format(format_bytes(after.ru_maxrss), format_bytes(after.ru_maxrss - before.ru_maxrss)))
Loading

0 comments on commit 54aaeab

Please sign in to comment.