Skip to content

Commit b0e0b93

Browse files
committed
Always use f-strings
always use f-strings in pure python blocks. Spacing is also changed to better match black.
1 parent 25c0758 commit b0e0b93

38 files changed

+156
-264
lines changed

av/__main__.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,11 @@ def main():
77
parser.add_argument("--version", action="store_true")
88
args = parser.parse_args()
99

10-
# ---
11-
1210
if args.version:
1311
import av
1412
import av._core
1513

16-
print("PyAV v" + av.__version__)
14+
print(f"PyAV v{av.__version__}")
1715

1816
by_config = {}
1917
for libname, config in sorted(av._core.library_meta.items()):
@@ -22,14 +20,13 @@ def main():
2220
by_config.setdefault(
2321
(config["configuration"], config["license"]), []
2422
).append((libname, config))
23+
2524
for (config, license), libs in sorted(by_config.items()):
2625
print("library configuration:", config)
2726
print("library license:", license)
2827
for libname, config in libs:
2928
version = config["version"]
30-
print(
31-
"%-13s %3d.%3d.%3d" % (libname, version[0], version[1], version[2])
32-
)
29+
print(f"{libname:<13} {version[0]:3d}.{version[1]:3d}.{version[2]:3d}")
3330

3431
if args.codecs:
3532
from av.codec.codec import dump_codecs

av/_core.pyx

+2
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ time_base = lib.AV_TIME_BASE
1212
cdef decode_version(v):
1313
if v < 0:
1414
return (-1, -1, -1)
15+
1516
cdef int major = (v >> 16) & 0xff
1617
cdef int minor = (v >> 8) & 0xff
1718
cdef int micro = (v) & 0xff
19+
1820
return (major, minor, micro)
1921

2022
library_meta = {

av/audio/codeccontext.pyx

-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ from av.packet cimport Packet
88

99

1010
cdef class AudioCodecContext(CodecContext):
11-
1211
cdef _init(self, lib.AVCodecContext *ptr, const lib.AVCodec *codec):
1312
CodecContext._init(self, ptr, codec)
1413

av/audio/fifo.pyx

+10-12
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,18 @@ from av.error cimport err_check
33

44

55
cdef class AudioFifo:
6-
76
"""A simple audio sample FIFO (First In First Out) buffer."""
87

98
def __repr__(self):
109
try:
11-
result = "<av.%s %s samples of %dhz %s %s at 0x%x>" % (
12-
self.__class__.__name__,
13-
self.samples,
14-
self.sample_rate,
15-
self.layout,
16-
self.format,
17-
id(self),
10+
result = (
11+
f"<av.{self.__class__.__name__} {self.samples} samples of "
12+
f"{self.sample_rate}hz {self.layout} {self.format} at 0x{id(self):x}>"
1813
)
1914
except AttributeError:
20-
result = "<av.%s uninitialized, use fifo.write(frame), at 0x%x>" % (
21-
self.__class__.__name__,
22-
id(self),
15+
result = (
16+
f"<av.{self.__class__.__name__} uninitialized, use fifo.write(frame),"
17+
f" at 0x{id(self):x}>"
2318
)
2419
return result
2520

@@ -90,7 +85,9 @@ cdef class AudioFifo:
9085
if self.pts_per_sample and frame.ptr.pts != lib.AV_NOPTS_VALUE:
9186
expected_pts = <int64_t>(self.pts_per_sample * self.samples_written)
9287
if frame.ptr.pts != expected_pts:
93-
raise ValueError("Frame.pts (%d) != expected (%d); fix or set to None." % (frame.ptr.pts, expected_pts))
88+
raise ValueError(
89+
"Frame.pts (%d) != expected (%d); fix or set to None." % (frame.ptr.pts, expected_pts)
90+
)
9491

9592
err_check(lib.av_audio_fifo_write(
9693
self.ptr,
@@ -173,6 +170,7 @@ cdef class AudioFifo:
173170
frames.append(frame)
174171
else:
175172
break
173+
176174
return frames
177175

178176
property format:

av/audio/format.pyx

+2-5
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,9 @@ cdef AudioFormat get_audio_format(lib.AVSampleFormat c_format):
1818

1919

2020
cdef class AudioFormat:
21-
2221
"""Descriptor of audio formats."""
2322

2423
def __cinit__(self, name):
25-
2624
if name is _cinit_bypass_sentinel:
2725
return
2826

@@ -33,15 +31,15 @@ cdef class AudioFormat:
3331
sample_fmt = lib.av_get_sample_fmt(name)
3432

3533
if sample_fmt < 0:
36-
raise ValueError("Not a sample format: %r" % name)
34+
raise ValueError(f"Not a sample format: {name!r}")
3735

3836
self._init(sample_fmt)
3937

4038
cdef _init(self, lib.AVSampleFormat sample_fmt):
4139
self.sample_fmt = sample_fmt
4240

4341
def __repr__(self):
44-
return "<av.AudioFormat %s>" % (self.name)
42+
return f"<av.AudioFormat {self.name}>"
4543

4644
property name:
4745
"""Canonical name of the sample format.
@@ -128,7 +126,6 @@ cdef class AudioFormat:
128126
129127
"""
130128
def __get__(self):
131-
132129
if self.is_planar:
133130
raise ValueError("no planar container formats")
134131

av/audio/frame.pyx

+11-21
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ cdef AudioFrame alloc_audio_frame():
3737

3838

3939
cdef class AudioFrame(Frame):
40-
4140
"""A frame of audio."""
4241

4342
def __cinit__(self, format="s16", layout="stereo", samples=0, align=1):
@@ -61,7 +60,6 @@ cdef class AudioFrame(Frame):
6160
self.ptr.channels = self.layout.nb_channels
6261

6362
if self.layout.channels and nb_samples:
64-
6563
# Cleanup the old buffer.
6664
lib.av_freep(&self._buffer)
6765

@@ -95,15 +93,9 @@ cdef class AudioFrame(Frame):
9593
self.format = get_audio_format(<lib.AVSampleFormat>self.ptr.format)
9694

9795
def __repr__(self):
98-
return "<av.%s %d, pts=%s, %d samples at %dHz, %s, %s at 0x%x>" % (
99-
self.__class__.__name__,
100-
self.index,
101-
self.pts,
102-
self.samples,
103-
self.rate,
104-
self.layout.name,
105-
self.format.name,
106-
id(self),
96+
return (
97+
f"<av.{self.__class__.__name__} {self.index} pts={self.pts}, {self.samples} "
98+
f"samples at {self.rate}Hz, {self.layout.name}, {self.format.name} at 0x{id(self):x}"
10799
)
108100

109101
@staticmethod
@@ -117,7 +109,9 @@ cdef class AudioFrame(Frame):
117109
try:
118110
dtype = np.dtype(format_dtypes[format])
119111
except KeyError:
120-
raise ValueError("Conversion from numpy array with format `%s` is not yet supported" % format)
112+
raise ValueError(
113+
f"Conversion from numpy array with format `{format}` is not yet supported"
114+
)
121115

122116
# check input format
123117
nb_channels = len(AudioLayout(layout).channels)
@@ -184,25 +178,21 @@ cdef class AudioFrame(Frame):
184178
"""
185179
import numpy as np
186180

187-
# map avcodec type to numpy type
188181
try:
189182
dtype = np.dtype(format_dtypes[self.format.name])
190183
except KeyError:
191-
raise ValueError("Conversion from {!r} format to numpy array is not supported.".format(self.format.name))
184+
raise ValueError(f"Conversion from {self.format.name!r} format to numpy array is not supported.")
192185

193186
if self.format.is_planar:
194187
count = self.samples
195188
else:
196189
count = self.samples * len(self.layout.channels)
197190

198-
# convert and return data
199191
return np.vstack([np.frombuffer(x, dtype=dtype, count=count) for x in self.planes])
200192

201193
def __getattribute__(self, attribute):
202-
"This method should be deleted when `frame.index` is removed."
203-
if attribute == 'index':
204-
warnings.warn(
205-
"Using `frame.index` is deprecated.",
206-
AVDeprecationWarning
207-
)
194+
# This method should be deleted when `frame.index` is removed
195+
if attribute == "index":
196+
warnings.warn("Using `frame.index` is deprecated.", AVDeprecationWarning)
197+
208198
return Frame.__getattribute__(self, attribute)

av/audio/layout.pyx

+5-7
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,15 @@ cdef dict channel_descriptions = {
6363

6464

6565
cdef class AudioLayout:
66-
6766
def __init__(self, layout):
68-
6967
if layout is _cinit_bypass_sentinel:
7068
return
7169

7270
cdef uint64_t c_layout
7371
if isinstance(layout, int):
7472
if layout < 0 or layout > 8:
75-
raise ValueError("no layout with %d channels" % layout)
73+
raise ValueError(f"no layout with {layout} channels")
74+
7675
c_layout = default_layouts[layout]
7776
elif isinstance(layout, str):
7877
c_layout = lib.av_get_channel_layout(layout)
@@ -82,7 +81,7 @@ cdef class AudioLayout:
8281
raise TypeError("layout must be str or int")
8382

8483
if not c_layout:
85-
raise ValueError("invalid channel layout %r" % layout)
84+
raise ValueError(f"invalid channel layout: {layout}")
8685

8786
self._init(c_layout)
8887

@@ -92,7 +91,7 @@ cdef class AudioLayout:
9291
self.channels = tuple(AudioChannel(self, i) for i in range(self.nb_channels))
9392

9493
def __repr__(self):
95-
return "<av.%s %r>" % (self.__class__.__name__, self.name)
94+
return f"<av.{self.__class__.__name__} {self.name!r}>"
9695

9796
property name:
9897
"""The canonical name of the audio layout."""
@@ -104,12 +103,11 @@ cdef class AudioLayout:
104103

105104

106105
cdef class AudioChannel:
107-
108106
def __cinit__(self, AudioLayout layout, int index):
109107
self.channel = lib.av_channel_layout_extract_channel(layout.layout, index)
110108

111109
def __repr__(self):
112-
return "<av.%s %r (%s)>" % (self.__class__.__name__, self.name, self.description)
110+
return f"<av.{self.__class__.__name__} {self.name!r} ({self.description})>"
113111

114112
property name:
115113
"""The canonical name of the audio channel."""

av/audio/stream.pyx

+4-9
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
11
cdef class AudioStream(Stream):
2-
32
def __repr__(self):
4-
return "<av.%s #%d %s at %dHz, %s, %s at 0x%x>" % (
5-
self.__class__.__name__,
6-
self.index,
7-
self.name,
8-
self.rate,
9-
self.layout.name,
10-
self.format.name if self.format else None,
11-
id(self),
3+
form = self.format.name if self.format else None
4+
return (
5+
f"<av.{self.__class__.__name__} #{self.index} {self.name} at {self.rate}Hz,"
6+
f" {self.layout.name}, {form} at 0x{id(self):x}>"
127
)

av/buffer.pyx

+5-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ from av.bytesource cimport ByteSource, bytesource
66

77

88
cdef class Buffer:
9-
109
"""A base class for PyAV objects which support the buffer protocol, such
1110
as :class:`.Packet` and :class:`.Plane`.
1211
@@ -24,6 +23,7 @@ cdef class Buffer:
2423
def __getbuffer__(self, Py_buffer *view, int flags):
2524
if flags & PyBUF_WRITABLE and not self._buffer_writable():
2625
raise ValueError("buffer is not writable")
26+
2727
PyBuffer_FillInfo(view, self, self._buffer_ptr(), self._buffer_size(), 0, flags)
2828

2929
@property
@@ -59,8 +59,11 @@ cdef class Buffer:
5959
"""
6060
if not self._buffer_writable():
6161
raise ValueError("buffer is not writable")
62+
6263
cdef ByteSource source = bytesource(input)
6364
cdef size_t size = self._buffer_size()
65+
6466
if source.length != size:
65-
raise ValueError("got %d bytes; need %d bytes" % (source.length, size))
67+
raise ValueError(f"got {source.length} bytes; need {size} bytes")
68+
6669
memcpy(self._buffer_ptr(), source.ptr, size)

av/codec/codec.pyx

+16-12
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,8 @@ codec_descriptor = wrap_avclass(lib.avcodec_get_class())
352352
def dump_codecs():
353353
"""Print information about available codecs."""
354354

355-
print """Codecs:
355+
print(
356+
"""Codecs:
356357
D..... = Decoding supported
357358
.E.... = Encoding supported
358359
..V... = Video codec
@@ -362,9 +363,9 @@ def dump_codecs():
362363
....L. = Lossy compression
363364
.....S = Lossless compression
364365
------"""
366+
)
365367

366368
for name in sorted(codecs_available):
367-
368369
try:
369370
e_codec = Codec(name, "w")
370371
except ValueError:
@@ -379,15 +380,18 @@ def dump_codecs():
379380
codec = e_codec or d_codec
380381

381382
try:
382-
print " %s%s%s%s%s%s %-18s %s" % (
383-
".D"[bool(d_codec)],
384-
".E"[bool(e_codec)],
385-
codec.type[0].upper(),
386-
".I"[codec.intra_only],
387-
".L"[codec.lossy],
388-
".S"[codec.lossless],
389-
codec.name,
390-
codec.long_name
383+
print(
384+
" %s%s%s%s%s%s %-18s %s"
385+
% (
386+
".D"[bool(d_codec)],
387+
".E"[bool(e_codec)],
388+
codec.type[0].upper(),
389+
".I"[codec.intra_only],
390+
".L"[codec.lossy],
391+
".S"[codec.lossless],
392+
codec.name,
393+
codec.long_name,
394+
)
391395
)
392396
except Exception as e:
393-
print "...... %-18s ERROR: %s" % (codec.name, e)
397+
print(f"...... {codec.name:<18} ERROR: {e}")

0 commit comments

Comments
 (0)