Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-45619: [Python] Use f-string instead of string.format #45629

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion python/pyarrow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ def append_library_dir(library_dir):
if not library_dir.startswith("-L"):
raise ValueError(
"pkg-config --libs-only-L returned unexpected "
"value {!r}".format(library_dir))
f"value {library_dir!r}")
append_library_dir(library_dir[2:])

if _sys.platform == 'win32':
Expand Down
2 changes: 1 addition & 1 deletion python/pyarrow/_acero.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ cdef class Declaration(_Weakrefable):
return frombytes(GetResultValue(DeclarationToString(self.decl)))

def __repr__(self):
return "<pyarrow.acero.Declaration>\n{0}".format(str(self))
return f"<pyarrow.acero.Declaration>\n{str(self)}"

def to_table(self, bint use_threads=True):
"""
Expand Down
37 changes: 11 additions & 26 deletions python/pyarrow/_compute.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,10 @@ def _pas():


def _forbid_instantiation(klass, subclasses_instead=True):
msg = '{} is an abstract class thus cannot be initialized.'.format(
klass.__name__
)
msg = f'{klass.__name__} is an abstract class thus cannot be initialized.'
if subclasses_instead:
subclasses = [cls.__name__ for cls in klass.__subclasses__]
msg += ' Use one of the subclasses instead: {}'.format(
', '.join(subclasses)
)
msg += f' Use one of the subclasses instead: {", ".join(subclasses)}'
raise TypeError(msg)


Expand Down Expand Up @@ -201,8 +197,7 @@ cdef class Kernel(_Weakrefable):
"""

def __init__(self):
raise TypeError("Do not call {}'s constructor directly"
.format(self.__class__.__name__))
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")


cdef class ScalarKernel(Kernel):
Expand All @@ -212,8 +207,7 @@ cdef class ScalarKernel(Kernel):
self.kernel = kernel

def __repr__(self):
return ("ScalarKernel<{}>"
.format(frombytes(self.kernel.signature.get().ToString())))
return f"ScalarKernel<{frombytes(self.kernel.signature.get().ToString())}>"


cdef class VectorKernel(Kernel):
Expand All @@ -223,8 +217,7 @@ cdef class VectorKernel(Kernel):
self.kernel = kernel

def __repr__(self):
return ("VectorKernel<{}>"
.format(frombytes(self.kernel.signature.get().ToString())))
return f"VectorKernel<{frombytes(self.kernel.signature.get().ToString())}>"


cdef class ScalarAggregateKernel(Kernel):
Expand All @@ -234,8 +227,7 @@ cdef class ScalarAggregateKernel(Kernel):
self.kernel = kernel

def __repr__(self):
return ("ScalarAggregateKernel<{}>"
.format(frombytes(self.kernel.signature.get().ToString())))
return f"ScalarAggregateKernel<{frombytes(self.kernel.signature.get().ToString())}>"


cdef class HashAggregateKernel(Kernel):
Expand All @@ -245,8 +237,7 @@ cdef class HashAggregateKernel(Kernel):
self.kernel = kernel

def __repr__(self):
return ("HashAggregateKernel<{}>"
.format(frombytes(self.kernel.signature.get().ToString())))
return f"HashAggregateKernel<{frombytes(self.kernel.signature.get().ToString())}>"


FunctionDoc = namedtuple(
Expand Down Expand Up @@ -298,17 +289,14 @@ cdef class Function(_Weakrefable):
}

def __init__(self):
raise TypeError("Do not call {}'s constructor directly"
.format(self.__class__.__name__))
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")

cdef void init(self, const shared_ptr[CFunction]& sp_func) except *:
self.sp_func = sp_func
self.base_func = sp_func.get()

def __repr__(self):
return ("arrow.compute.Function<name={}, kind={}, "
"arity={}, num_kernels={}>"
.format(self.name, self.kind, self.arity, self.num_kernels))
return f"arrow.compute.Function<name={self.name}, kind={self.kind}, arity={self.arity}, num_kernels={self.num_kernels}>"

def __reduce__(self):
# Reduction uses the global registry
Expand Down Expand Up @@ -2462,9 +2450,7 @@ cdef class Expression(_Weakrefable):
return frombytes(self.expr.ToString())

def __repr__(self):
return "<pyarrow.compute.{0} {1}>".format(
self.__class__.__name__, str(self)
)
return f"<pyarrow.compute.{self.__class__.__name__} {str(self)}>"

@staticmethod
def from_substrait(object message not None):
Expand Down Expand Up @@ -2768,8 +2754,7 @@ cdef class UdfContext:
"""

def __init__(self):
raise TypeError("Do not call {}'s constructor directly"
.format(self.__class__.__name__))
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")

cdef void init(self, const CUdfContext &c_context):
self.c_context = c_context
Expand Down
5 changes: 2 additions & 3 deletions python/pyarrow/_csv.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1150,9 +1150,8 @@ cdef class CSVStreamingReader(RecordBatchReader):
Schema schema

def __init__(self):
raise TypeError("Do not call {}'s constructor directly, "
"use pyarrow.csv.open_csv() instead."
.format(self.__class__.__name__))
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, "
"use pyarrow.csv.open_csv() instead.")

# Note about cancellation: we cannot create a SignalStopHandler
# by default here, as several CSVStreamingReader instances may be
Expand Down
3 changes: 1 addition & 2 deletions python/pyarrow/_cuda.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -841,8 +841,7 @@ cdef class BufferWriter(NativeFile):
offset = offset + position
else:
with gil:
raise ValueError("Invalid value of whence: {0}"
.format(whence))
raise ValueError(f"Invalid value of whence: {whence}")
check_status(self.writer.Seek(offset))
return self.tell()

Expand Down
24 changes: 11 additions & 13 deletions python/pyarrow/_dataset.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1127,8 +1127,8 @@ cdef class FileSystemDataset(Dataset):
root_partition = _true
elif not isinstance(root_partition, Expression):
raise TypeError(
"Argument 'root_partition' has incorrect type (expected "
"Expression, got {0})".format(type(root_partition))
f"Argument 'root_partition' has incorrect type (expected "
f"Expression, got {type(root_partition)})"
)

for fragment in fragments:
Expand Down Expand Up @@ -1220,8 +1220,8 @@ cdef class FileSystemDataset(Dataset):
]:
if not isinstance(arg, class_):
raise TypeError(
"Argument '{0}' has incorrect type (expected {1}, "
"got {2})".format(name, class_.__name__, type(arg))
f"Argument '{name}' has incorrect type (expected {class_.__name__}, "
f"got {type(arg)})"
)

partitions = partitions or [_true] * len(paths)
Expand Down Expand Up @@ -1988,9 +1988,7 @@ cdef class FileFragment(Fragment):
)
if partition:
partition = f" partition=[{partition}]"
return "<pyarrow.dataset.{0}{1} path={2}{3}>".format(
self.__class__.__name__, typ, self.path, partition
)
return f"<pyarrow.dataset.{self.__class__.__name__}{typ} path={self.path}{partition}>"

def __reduce__(self):
buffer = self.buffer
Expand Down Expand Up @@ -3384,8 +3382,8 @@ cdef class FileSystemDatasetFactory(DatasetFactory):
c_options
)
else:
raise TypeError('Must pass either paths or a FileSelector, but '
'passed {}'.format(type(paths_or_selector)))
raise TypeError(f'Must pass either paths or a FileSelector, but '
f'passed {type(paths_or_selector)}')

self.init(GetResultValue(result))

Expand Down Expand Up @@ -3527,8 +3525,8 @@ cdef void _populate_builder(const shared_ptr[CScannerBuilder]& ptr,
for expr in columns.values():
if not isinstance(expr, Expression):
raise TypeError(
"Expected an Expression for a 'column' dictionary "
"value, got {} instead".format(type(expr))
f"Expected an Expression for a 'column' dictionary "
f"value, got {type(expr)} instead"
)
c_exprs.push_back((<Expression> expr).unwrap())

Expand All @@ -3539,8 +3537,8 @@ cdef void _populate_builder(const shared_ptr[CScannerBuilder]& ptr,
check_status(builder.ProjectColumns([tobytes(c) for c in columns]))
else:
raise ValueError(
"Expected a list or a dict for 'columns', "
"got {} instead.".format(type(columns))
f"Expected a list or a dict for 'columns', "
f"got {type(columns)} instead."
)

check_status(builder.BatchSize(batch_size))
Expand Down
6 changes: 2 additions & 4 deletions python/pyarrow/_dataset_parquet.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ class RowGroupInfo:
}

def __repr__(self):
return "RowGroupInfo({})".format(self.id)
return f"RowGroupInfo({self.id})"

def __eq__(self, other):
if isinstance(other, int):
Expand Down Expand Up @@ -671,9 +671,7 @@ cdef class ParquetFileWriteOptions(FileWriteOptions):
self._set_arrow_properties()

def __repr__(self):
return "<pyarrow.dataset.ParquetFileWriteOptions {0}>".format(
" ".join([f"{key}={value}" for key, value in self._properties.items()])
)
return f"<pyarrow.dataset.ParquetFileWriteOptions {self._properties}>"


cdef set _PARQUET_READ_OPTIONS = {
Expand Down
Loading