From ce1186d91d9994dba3719743f5da9f58901b1120 Mon Sep 17 00:00:00 2001 From: EmilyBourne Date: Tue, 18 Jul 2023 14:21:28 +0200 Subject: [PATCH] [PYLINT] consider-using-f-string --- pyccel/ast/basic.py | 4 +- pyccel/ast/bitwise_operators.py | 18 +- pyccel/ast/builtins.py | 43 ++-- pyccel/ast/core.py | 110 ++++----- pyccel/ast/cwrapper.py | 10 +- pyccel/ast/datatypes.py | 7 +- pyccel/ast/headers.py | 6 +- pyccel/ast/internals.py | 8 +- pyccel/ast/literals.py | 4 +- pyccel/ast/macros.py | 11 +- pyccel/ast/numpy_wrapper.py | 6 +- pyccel/ast/numpyext.py | 26 +- pyccel/ast/operators.py | 64 ++--- pyccel/ast/utilities.py | 4 +- pyccel/ast/variable.py | 35 +-- pyccel/codegen/codegen.py | 6 +- pyccel/codegen/pipeline.py | 8 +- pyccel/codegen/printing/codeprinter.py | 5 +- pyccel/codegen/printing/cwrappercode.py | 158 +++++------- pyccel/codegen/printing/pycode.py | 296 +++++++++++------------ pyccel/codegen/python_wrapper.py | 6 +- pyccel/commands/console.py | 7 +- pyccel/compilers/default_compilers.py | 2 +- pyccel/epyccel.py | 4 +- pyccel/errors/errors.py | 12 +- pyccel/naming/fortrannameclashchecker.py | 2 +- pyccel/parser/base.py | 12 +- pyccel/parser/parser.py | 6 +- pyccel/parser/scope.py | 8 +- pyccel/parser/syntactic.py | 14 +- 30 files changed, 430 insertions(+), 472 deletions(-) diff --git a/pyccel/ast/basic.py b/pyccel/ast/basic.py index 965f4950f4..1673bb8560 100644 --- a/pyccel/ast/basic.py +++ b/pyccel/ast/basic.py @@ -70,7 +70,7 @@ def __init__(self): setattr(self, c_name, c) elif not isinstance(c, Basic): - raise TypeError("Basic child must be a Basic or a tuple not {}".format(type(c))) + raise TypeError(f"Basic child must be a Basic or a tuple not {type(c)}") if isinstance(c, tuple): @@ -310,7 +310,7 @@ def is_atomic(self): def set_fst(self, fst): """Sets the python.ast fst.""" if not isinstance(fst, ast.AST): - raise TypeError("Fst must be an AST object, not {}".format(type(fst))) + raise TypeError(f"Fst must be an AST object, not {type(fst)}") if self.fst: if hasattr(fst, 'lineno'): diff --git a/pyccel/ast/bitwise_operators.py b/pyccel/ast/bitwise_operators.py index fc59dc6d73..17074dd73f 100644 --- a/pyccel/ast/bitwise_operators.py +++ b/pyccel/ast/bitwise_operators.py @@ -47,14 +47,14 @@ def _calculate_dtype(self, *args): dtype = NativeInteger() a = args[0] if a.dtype not in (NativeInteger(), NativeBool()): - raise TypeError('unsupported operand type(s): {}'.format(args)) + raise TypeError(f'unsupported operand type(s): {args}') self._args = (PythonInt(a) if a.dtype is NativeBool() else a,) precision = a.precision return dtype, precision def __repr__(self): - return '~{}'.format(repr(self.args[0])) + return f'~{repr(self.args[0])}' #============================================================================== @@ -93,11 +93,11 @@ def _calculate_dtype(self, *args): strs = [a for a in args if a.dtype is NativeString()] if strs or complexes or floats: - raise TypeError('unsupported operand type(s): {}'.format(args)) + raise TypeError(f'unsupported operand type(s): {args}') elif integers: return self._handle_integer_type(integers) else: - raise TypeError('cannot determine the type of {}'.format(args)) + raise TypeError(f'cannot determine the type of {args}') def _set_shape_rank(self): pass @@ -135,7 +135,7 @@ class PyccelRShift(PyccelBitOperator): _precedence = 11 def __repr__(self): - return '{} >> {}'.format(self.args[0], self.args[1]) + return f'{self.args[0]} >> {self.args[1]}' #============================================================================== @@ -158,7 +158,7 @@ class PyccelLShift(PyccelBitOperator): _precedence = 11 def __repr__(self): - return '{} << {}'.format(self.args[0], self.args[1]) + return f'{self.args[0]} << {self.args[1]}' #============================================================================== @@ -206,7 +206,7 @@ class PyccelBitXor(PyccelBitComparisonOperator): _precedence = 9 def __repr__(self): - return '{} ^ {}'.format(self.args[0], self.args[1]) + return f'{self.args[0]} ^ {self.args[1]}' #============================================================================== @@ -229,7 +229,7 @@ class PyccelBitOr(PyccelBitComparisonOperator): _precedence = 8 def __repr__(self): - return '{} | {}'.format(self.args[0], self.args[1]) + return f'{self.args[0]} | {self.args[1]}' #============================================================================== @@ -252,4 +252,4 @@ class PyccelBitAnd(PyccelBitComparisonOperator): _precedence = 10 def __repr__(self): - return '{} & {}'.format(self.args[0], self.args[1]) + return f'{self.args[0]} & {self.args[1]}' diff --git a/pyccel/ast/builtins.py b/pyccel/ast/builtins.py index 4931c4fd30..d366a8f694 100644 --- a/pyccel/ast/builtins.py +++ b/pyccel/ast/builtins.py @@ -101,7 +101,7 @@ def __new__(cls, arg): return super().__new__(cls) def __str__(self): - return 'Real({0})'.format(str(self.internal_var)) + return f'Real({self.internal_var})' #============================================================================== class PythonImag(PythonComplexProperty): @@ -123,7 +123,7 @@ def __new__(cls, arg): return super().__new__(cls) def __str__(self): - return 'Imag({0})'.format(str(self.internal_var)) + return f'Imag({self.internal_var})' #============================================================================== class PythonConjugate(PyccelInternalFunction): @@ -169,7 +169,7 @@ def internal_var(self): return self._args[0] def __str__(self): - return 'Conjugate({0})'.format(str(self.internal_var)) + return f'Conjugate({self.internal_var})' #============================================================================== class PythonBool(PyccelAstNode): @@ -201,7 +201,7 @@ def arg(self): return self._arg def __str__(self): - return 'Bool({})'.format(str(self.arg)) + return f'Bool({self.arg})' #============================================================================== class PythonComplex(PyccelAstNode): @@ -303,7 +303,7 @@ def internal_var(self): return self._internal_var def __str__(self): - return "complex({}, {})".format(str(self.real), str(self.imag)) + return f"complex({self.real}, {self.imag})" #============================================================================== class PythonEnumerate(Basic): @@ -373,7 +373,7 @@ def arg(self): return self._arg def __str__(self): - return 'float({0})'.format(str(self.arg)) + return f'float({self.arg})' #============================================================================== class PythonInt(PyccelAstNode): @@ -458,7 +458,7 @@ def __init__(self, *args): self._dtype = NativeBool() self._precision = max_precision(bools) else: - raise TypeError('cannot determine the type of {}'.format(self)) + raise TypeError(f'cannot determine the type of {self}') inner_shape = [() if a.rank == 0 else a.shape for a in args] @@ -499,7 +499,7 @@ def to_int(a): elif self.is_homogeneous: return IndexedElement(self, i) else: - raise NotImplementedError("Can't index PythonTuple with type {}".format(type(i))) + raise NotImplementedError(f"Can't index PythonTuple with type {type(i)}") def __add__(self,other): return PythonTuple(*(self._args + other._args)) @@ -511,10 +511,12 @@ def __len__(self): return len(self._args) def __str__(self): - return '({})'.format(', '.join(str(a) for a in self)) + args = ', '.join(str(a) for a in self) + return f'({args})' def __repr__(self): - return 'PythonTuple({})'.format(', '.join(str(a) for a in self)) + args = ', '.join(str(a) for a in self) + return f'PythonTuple({args})' @property def is_homogeneous(self): @@ -560,7 +562,7 @@ def arg(self): return self._args[0] def __str__(self): - return 'len({})'.format(str(self.arg)) + return f'len({self.arg})' #============================================================================== class PythonList(PythonTuple): @@ -766,7 +768,7 @@ class PythonSum(PyccelInternalFunction): def __init__(self, arg): if not isinstance(arg, PyccelAstNode): - raise TypeError('Unknown type of %s.' % type(arg)) + raise TypeError(f'Unknown type of {type(arg)}.' ) self._dtype = arg.dtype self._precision = -1 super().__init__(arg) @@ -794,11 +796,11 @@ def __init__(self, *x): if isinstance(x, (list, tuple)): x = PythonTuple(*x) elif not isinstance(x, (PythonTuple, PythonList)): - raise TypeError('Unknown type of %s.' % type(x)) + raise TypeError(f'Unknown type of {type(x)}.' ) if not x.is_homogeneous: - types = ', '.join('{}({})'.format(xi.dtype,xi.precision) for xi in x) + types = ', '.join('{xi.dtype}({xi.precision})' for xi in x) raise PyccelError("Cannot determine final dtype of 'max' call with arguments of different " - "types ({}). Please cast arguments to the desired dtype".format(types)) + f"types ({types}). Please cast arguments to the desired dtype") self._dtype = x.dtype self._precision = x.precision super().__init__(x) @@ -822,11 +824,11 @@ def __init__(self, *x): if isinstance(x, (list, tuple)): x = PythonTuple(*x) elif not isinstance(x, (PythonTuple, PythonList)): - raise TypeError('Unknown type of %s.' % type(x)) + raise TypeError(f'Unknown type of {type(x)}.' ) if not x.is_homogeneous: - types = ', '.join('{}({})'.format(xi.dtype,xi.precision) for xi in x) + types = ', '.join(f'{xi.dtype}({xi.precision})' for xi in x) raise PyccelError("Cannot determine final dtype of 'min' call with arguments of different " - "types ({}). Please cast arguments to the desired dtype".format(types)) + f"types ({types}). Please cast arguments to the desired dtype") self._dtype = x.dtype self._precision = x.precision super().__init__(x) @@ -871,8 +873,7 @@ def __call__(self, *args): return self.expr.subs(self.variables, args) def __str__(self): - return "{args} -> {expr}".format(args=self.variables, - expr = self.expr) + return f"{self.variables} -> {self.expr}" #============================================================================== class PythonType(Basic): @@ -896,7 +897,7 @@ class PythonType(Basic): def __init__(self, obj): if not isinstance (obj, PyccelAstNode): - raise PyccelError("Python's type function is not implemented for {} object".format(type(obj))) + raise PyccelError(f"Python's type function is not implemented for {type(obj)} object") self._dtype = obj.dtype self._precision = obj.precision self._obj = obj diff --git a/pyccel/ast/core.py b/pyccel/ast/core.py index 4e3af08989..ee8550c547 100644 --- a/pyccel/ast/core.py +++ b/pyccel/ast/core.py @@ -261,10 +261,10 @@ def object(self): return self._obj def __repr__(self): - return '{0} as {1}'.format(str(self.name), str(self.target)) + return f'{self.name} as {self.target}' def __str__(self): - return '{0} as {1}'.format(str(self.name), str(self.target)) + return f'{self.name} as {self.target}' def __eq__(self, string): if isinstance(string, str): @@ -315,10 +315,10 @@ def length(self): return self._length def __str__(self): - return '{} * {}'.format(str(self.val), str(self.length)) + return f'{self.val} * {self.length}' def __repr__(self): - return '{} * {}'.format(repr(self.val), repr(self.length)) + return f'{repr(self.val)} * {repr(self.length)}' class Concatenate(PyccelAstNode): @@ -417,10 +417,10 @@ def __init__( self.set_fst(fst) def __str__(self): - return '{0} := {1}'.format(str(self.lhs), str(self.rhs)) + return f'{self.lhs} := {self.rhs}' def __repr__(self): - return '({0} := {1})'.format(repr(self.lhs), repr(self.rhs)) + return f'({repr(self.lhs)} := {repr(self.rhs)})' @property def lhs(self): @@ -513,14 +513,14 @@ class Allocate(Basic): def __init__(self, variable, *, shape, order, status): if not isinstance(variable, Variable): - raise TypeError("Can only allocate a 'Variable' object, got {} instead".format(type(variable))) + raise TypeError(f"Can only allocate a 'Variable' object, got {type(variable)} instead") if variable.on_stack: # Variable may only be a pointer in the wrapper raise ValueError("Variable must be allocatable") if shape and not isinstance(shape, (int, tuple, list)): - raise TypeError("Cannot understand 'shape' parameter of type '{}'".format(type(shape))) + raise TypeError(f"Cannot understand 'shape' parameter of type '{type(shape)}'") if variable.rank != len(shape): raise ValueError("Incompatible rank in variable allocation") @@ -530,10 +530,10 @@ def __init__(self, variable, *, shape, order, status): raise ValueError("Incompatible order in variable allocation") if not isinstance(status, str): - raise TypeError("Cannot understand 'status' parameter of type '{}'".format(type(status))) + raise TypeError(f"Cannot understand 'status' parameter of type '{type(status)}'") if status not in ('allocated', 'unallocated', 'unknown'): - raise ValueError("Value of 'status' not allowed: '{}'".format(status)) + raise ValueError(f"Value of 'status' not allowed: '{status}'") self._variable = variable self._shape = shape @@ -559,8 +559,7 @@ def status(self): return self._status def __str__(self): - return 'Allocate({}, shape={}, order={}, status={})'.format( - str(self.variable), str(self.shape), str(self.order), str(self.status)) + return 'Allocate({self.variable}, shape={self.shape}, order={self.order}, status={self.status})' def __eq__(self, other): if isinstance(other, Allocate): @@ -599,7 +598,7 @@ class Deallocate(Basic): def __init__(self, variable): if not isinstance(variable, Variable): - raise TypeError("Can only allocate a 'Variable' object, got {} instead".format(type(variable))) + raise TypeError("Can only allocate a 'Variable' object, got {type(variable)} instead") self._variable = variable super().__init__() @@ -674,7 +673,7 @@ def insert2body(self, *obj, back=True): self._body = tuple([*obj, *self.body]) def __repr__(self): - return 'CodeBlock({})'.format(self.body) + return f'CodeBlock({self.body})' def __reduce_ex__(self, i): """ Used by pickle to create an object of this class. @@ -745,7 +744,7 @@ def __init__(self, lhs, rhs): super().__init__() def __str__(self): - return '{0} := {1}'.format(str(self.lhs), str(self.rhs)) + return f'{self.lhs} := {self.rhs}' @property def lhs(self): @@ -786,7 +785,7 @@ def __init__(self, lhs, rhs): super().__init__() def __str__(self): - return '{0} := {1}'.format(str(self.lhs), str(self.rhs)) + return f'{self.lhs} := {self.rhs}' @property def lhs(self): @@ -864,10 +863,10 @@ def __init__( super().__init__(lhs, rhs, status, like, fst=fst) def __repr__(self): - return '{0} {1}= {2}'.format(str(self.lhs), self.op, str(self.rhs)) + return f'{self.lhs} {self.op}= {self.rhs}' def __str__(self): - return '{0} {1}= {2}'.format(str(self.lhs), self.op, str(self.rhs)) + return f'{self.lhs} {self.op}= {self.rhs}' @property def op(self): @@ -1523,7 +1522,7 @@ def __init__(self, iterable): elif hasattr(iterable, 'n_indices') and hasattr(iterable, 'to_range'): self._num_indices_required = iterable.n_indices else: - raise TypeError("Unknown iterator type {}".format(type(iterable))) + raise TypeError(f"Unknown iterator type {type(iterable)}") super().__init__() @@ -1805,7 +1804,7 @@ def __str__(self): args = '' if not self.arguments is None: args = ', '.join(str(i) for i in self.arguments) - return '{0}({1})'.format(name, args) + return f'{name}({args})' @property def func(self): @@ -1865,15 +1864,15 @@ def has_keyword(self): def __repr__(self): if self.has_keyword: - return 'FunctionCallArgument({} = {})'.format(self.keyword, repr(self.value)) + return f'FunctionCallArgument({self.keyword} = {repr(self.value)})' else: - return 'FunctionCallArgument({})'.format(repr(self.value)) + return f'FunctionCallArgument({repr(self.value)})' def __str__(self): if self.has_keyword: - return '{} = {}'.format(self.keyword, str(self.value)) + return f'{self.keyword} = {self.value}' else: - return '{}'.format(str(self.value)) + return str(self.value) class FunctionDefArgument(PyccelAstNode): """ @@ -2000,19 +1999,15 @@ def make_const(self): def __str__(self): if self.has_default: - argument = str(self.name) - value = str(self.value) - return '{0}={1}'.format(argument, value) + return f'{self.name}={self.value}' else: return str(self.name) def __repr__(self): if self.has_default: - argument = str(self.name) - value = str(self.value) - return 'FunctionDefArgument({0}={1})'.format(argument, value) + return f'FunctionDefArgument({self.name}={self.value})' else: - return 'FunctionDefArgument({})'.format(repr(self.name)) + return f'FunctionDefArgument({repr(self.name)})' class FunctionDefResult(PyccelAstNode): """ @@ -2090,7 +2085,7 @@ def is_argument(self): return self._is_argument def __repr__(self): - return 'FunctionDefResult({})'.format(repr(self.var)) + return f'FunctionDefResult({repr(self.var)})' def __str__(self): return str(self.var) @@ -2225,7 +2220,8 @@ def interface_name(self): return self._interface_name def __repr__(self): - return '{}({})'.format(self.func_name, ', '.join(str(a) for a in self.args)) + args = ', '.join(str(a) for a in self.args) + return f'{self.func_name}({args})' @classmethod def _ignore(cls, c): @@ -2315,7 +2311,8 @@ def __repr__(self): code = repr(self.stmt)+';' else: code = '' - return code+"Return({})".format(','.join([repr(e) for e in self.expr])) + expr = ','.join(repr(e) for e in self.expr) + return code+f"Return({expr})" class FunctionDef(ScopedNode): @@ -2786,10 +2783,7 @@ def __str__(self): result = 'None' if len(self.results) == 0 else \ ', '.join(str(r) for r in self.results) args = ', '.join(str(a) for a in self.arguments) - return '{name}({args}) -> {result}'.format( - name = self.name, - args = args, - result = result) + return f'{self.name}({args}) -> {result}' @property def is_unused(self): @@ -3020,7 +3014,7 @@ def point(self, args, use_final_precision = False): if found: return self._functions[j] else: - errors.report('Arguments types provided to {} are incompatible'.format(self.name), + errors.report(f'Arguments types provided to {self.name} are incompatible', severity='fatal') class FunctionAddress(FunctionDef): @@ -3335,8 +3329,7 @@ def get_attribute(self, O, attr): attributes[i.name] = i if not attr in attributes: - raise ValueError('{0} is not an attribute of {1}'.format(attr, - str(self))) + raise ValueError(f'{attr} is not an attribute of {self}') var = attributes[attr] name = DottedName(cls_name, var.name) @@ -3459,7 +3452,7 @@ def _format(i): if isinstance(i, (DottedName, AsName, PyccelSymbol)): return i else: - raise TypeError('Expecting a string, PyccelSymbol DottedName, given {}'.format(type(i))) + raise TypeError(f'Expecting a string, PyccelSymbol DottedName, given {type(i)}') @property def target(self): @@ -3482,11 +3475,10 @@ def ignore(self, to_ignore): def __str__(self): source = str(self.source) if len(self.target) == 0: - return 'import {source}'.format(source=source) + return f'import {source}' else: - target = ', '.join([str(i) for i in self.target]) - return 'from {source} import {target}'.format(source=source, - target=target) + target = ', '.join(str(i) for i in self.target) + return f'from {source} import {target}' def define_target(self, new_target): """ @@ -3559,7 +3551,7 @@ def __init__( ): if not isinstance(variable, FunctionAddress): - raise TypeError('variable must be of type FunctionAddress, given {0}'.format(variable)) + raise TypeError(f'variable must be of type FunctionAddress, given {variable}') if intent: if not intent in ['in', 'out', 'inout']: @@ -3655,7 +3647,7 @@ def __init__( raise TypeError('datatype must be an instance of DataType.') if not isinstance(variable, Variable): - raise TypeError('var must be of type Variable, given {0}'.format(variable)) + raise TypeError(f'var must be of type Variable, given {variable}') if variable.dtype != dtype: raise ValueError('All variables must have the same dtype') @@ -3723,7 +3715,7 @@ def module_variable(self): return self._module_variable def __repr__(self): - return 'Declare({})'.format(repr(self.variable)) + return f'Declare({repr(self.variable)})' class Break(Basic): @@ -3774,7 +3766,7 @@ def __init__(self, expr): for i in expr: if not isinstance(i, (Lambda, SymbolicAssign, SympyFunction)): - raise TypeError('Expecting Lambda, SymbolicAssign, SympyFunction for {}'.format(i)) + raise TypeError(f'Expecting Lambda, SymbolicAssign, SympyFunction for {i}') self._expr = expr @@ -3872,7 +3864,7 @@ def text(self): return self._text def __str__(self): - return '# {0}'.format(str(self.text)) + return f'# {self.text}' def __reduce_ex__(self, i): """ Used by pickle to create an object of this class. @@ -4086,7 +4078,7 @@ def __iter__(self): return iter((self.condition, self.body)) def __str__(self): - return "IfSec({},{})".format(str(self.condition), str(self.body)) + return f"IfSec({self.condition},{self.body})" class If(Basic): @@ -4130,7 +4122,8 @@ def bodies(self): return [b.body for b in self._blocks] def __str__(self): - return "If({})".format(','.join(str(b) for b in self.blocks)) + blocks = ','.join(str(b) for b in self.blocks) + return f"If({blocks})" class StarredArguments(Basic): __slots__ = ('_starred_obj',) @@ -4189,14 +4182,13 @@ def get_iterable_ranges(it, var_name=None): if isinstance(it, Variable): if it.cls_base is None: - raise TypeError('iterable must be an iterable Variable object' - ) + raise TypeError('iterable must be an iterable Variable object') # ... def _construct_arg_Range(name): if not isinstance(name, DottedName): - raise TypeError('Expecting a DottedName, given {0}'.format(type(name))) + raise TypeError(f'Expecting a DottedName, given {type(name)}') if not var_name: return DottedName(it.name.name[0], name.name[1]) @@ -4209,7 +4201,7 @@ def _construct_arg_Range(name): if isinstance(cls_base, PythonRange): if not isinstance(it.name, DottedName): - raise TypeError('Expecting a DottedName, given {0}'.format(type(it.name))) + raise TypeError(f'Expecting a DottedName, given {type(it.name)}') args = [] for i in [cls_base.start, cls_base.stop, cls_base.step]: @@ -4222,7 +4214,7 @@ def _construct_arg_Range(name): indices = i.indices arg = base[indices] else: - raise TypeError('Wrong type, given {0}'.format(type(i))) + raise TypeError(f'Wrong type, given {type(i)}') args += [arg] return [PythonRange(*args)] @@ -4239,7 +4231,7 @@ def _construct_arg_Range(name): # we add '_' tp be conform with the private variables convention - kwargs['{0}'.format(a['key'])] = a['value'] + kwargs[str(a['key'])] = a['value'] else: args.append(a) diff --git a/pyccel/ast/cwrapper.py b/pyccel/ast/cwrapper.py index 289d0020df..020fb99ad7 100644 --- a/pyccel/ast/cwrapper.py +++ b/pyccel/ast/cwrapper.py @@ -502,13 +502,13 @@ def generate_datatype_error(variable): elif isinstance(dtype, NativeBool): precision = '' elif isinstance(dtype, NativeComplex): - precision = '{} bit '.format(variable.precision * 2 * 8) + nbit = variable.precision * 2 * 8 + precision = f'{nbit} bit ' else: - precision = '{} bit '.format(variable.precision * 8) + nbit = variable.precision * 8 + precision = f'{nbit} bit ' - message = '"Argument must be {precision}{dtype}"'.format( - precision = precision, - dtype = variable.dtype) + message = f'"Argument must be {precision}{variable.dtype}"' return set_python_error_message('PyExc_TypeError', message) diff --git a/pyccel/ast/datatypes.py b/pyccel/ast/datatypes.py index b25086f384..973b6d6e8e 100644 --- a/pyccel/ast/datatypes.py +++ b/pyccel/ast/datatypes.py @@ -249,15 +249,14 @@ def __init__(self, **kwargs): # here, the argnames variable is the one passed to the # DataTypeFactory call if key not in argnames: - raise TypeError("Argument %s not valid for %s" - % (key, self.__class__.__name__)) + raise TypeError(f"Argument {key} not valid for {self.__class__.__name__}") setattr(self, key, value) BaseClass.__init__(self, name=name[:-len("Class")]) if prefix is None: prefix = 'Pyccel' else: - prefix = 'Pyccel{0}'.format(prefix) + prefix = f'Pyccel{prefix}' newclass = type(prefix + name, (BaseClass,), {"__init__": __init__, @@ -344,4 +343,4 @@ def str_dtype(dtype): elif isinstance(dtype, NativeBool): return 'bool' else: - raise TypeError('Unknown datatype {0}'.format(str(dtype))) + raise TypeError(f'Unknown datatype {dtype}') diff --git a/pyccel/ast/headers.py b/pyccel/ast/headers.py index 5f2639d091..61610ede5e 100644 --- a/pyccel/ast/headers.py +++ b/pyccel/ast/headers.py @@ -407,11 +407,11 @@ def find_templates(signature, templates): _name, _count = create_incremented_string(used_names, 'out', _count) var, annotation = build_argument(_name, dc) results.append(FunctionDefResult(var, annotation=annotation)) - arg_name = 'arg_{0}'.format(str(i)) + arg_name = f'arg_{i}' arg = FunctionDefArgument(FunctionAddress(arg_name, decs, results, [])) else: - arg_name = 'arg_{0}'.format(str(i)) + arg_name = f'arg_{i}' var, annotation = build_argument(arg_name, d) arg = FunctionDefArgument(var, annotation=annotation) args.append(arg) @@ -421,7 +421,7 @@ def find_templates(signature, templates): for i,d_var in enumerate(self.results): is_func = d_var.pop('is_func') dtype = d_var.pop('datatype') - var = Variable(dtype, 'res_{}'.format(i), **d_var, is_temp = True) + var = Variable(dtype, f'res_{i}', **d_var, is_temp = True) results.append(FunctionDefResult(var, annotation = str(dtype))) # we put back dtype otherwise macro will crash when it tries to # call create_definition diff --git a/pyccel/ast/internals.py b/pyccel/ast/internals.py index 6c255ae136..f90f48aba3 100644 --- a/pyccel/ast/internals.py +++ b/pyccel/ast/internals.py @@ -79,11 +79,11 @@ def __init__(self, arg, index): if not isinstance(arg, (list, tuple, PyccelAstNode)): - raise TypeError('Unknown type of %s.' % type(arg)) + raise TypeError(f'Unknown type of type(arg).') if isinstance(index, int): index = LiteralInteger(index) elif not isinstance(index, PyccelAstNode): - raise TypeError('Unknown type of %s.' % type(index)) + raise TypeError(f'Unknown type of type(index).') self._arg = arg self._index = index @@ -102,7 +102,7 @@ def index(self): return self._index def __str__(self): - return 'Shape({},{})'.format(str(self.arg), str(self.index)) + return f'Shape({self.arg},{self.index})' def __eq__(self, other): if isinstance(other, PyccelArraySize): @@ -196,7 +196,7 @@ def __str__(self): stop = '' else: stop = str(self.stop) - return '{0} : {1}'.format(start, stop) + return f'{start} : {stop}' class PyccelSymbol(str, Immutable): """Symbolic placeholder for a Python variable, which has a name but no type yet. diff --git a/pyccel/ast/literals.py b/pyccel/ast/literals.py index 0a3a6ad5d1..aeb1d96264 100644 --- a/pyccel/ast/literals.py +++ b/pyccel/ast/literals.py @@ -52,7 +52,7 @@ def python_value(self): """ Get python literal represented by this instance """ def __repr__(self): - return "Literal({})".format(repr(self.python_value)) + return f"Literal({repr(self.python_value)})" def __str__(self): return str(self.python_value) @@ -209,7 +209,7 @@ def arg(self): return self._string def __repr__(self): - return "'{}'".format(str(self.python_value)) + return f"'{self.python_value}'" def __str__(self): return str(self.python_value) diff --git a/pyccel/ast/macros.py b/pyccel/ast/macros.py index 4645491127..16cf6d2f52 100644 --- a/pyccel/ast/macros.py +++ b/pyccel/ast/macros.py @@ -33,7 +33,7 @@ class Macro(PyccelAstNode): def __init__(self, argument): if not isinstance(argument, (PyccelSymbol, Variable)): - raise TypeError("Argument must be a Pyccelsymbol or a Variable not {}".format(type(argument))) + raise TypeError("Argument must be a Pyccelsymbol or a Variable not {type(argument)}") self._argument = argument super().__init__() @@ -74,10 +74,9 @@ def index(self): def __str__(self): if self.index is None: - return 'MacroShape({})'.format(str(self.argument)) + return 'MacroShape({self.argument})' else: - return 'MacroShape({}, {})'.format(str(self.argument), - str(self.index)) + return 'MacroShape({self.argument}, {self.index})' #============================================================================== class MacroType(Macro): @@ -91,7 +90,7 @@ class MacroType(Macro): _order = None def __str__(self): - return 'MacroType({})'.format(str(self.argument)) + return 'MacroType({self.argument})' #============================================================================== class MacroCount(Macro): @@ -105,7 +104,7 @@ class MacroCount(Macro): _order = None def __str__(self): - return 'MacroCount({})'.format(str(self.argument)) + return 'MacroCount({self.argument})' diff --git a/pyccel/ast/numpy_wrapper.py b/pyccel/ast/numpy_wrapper.py index 10d3f6543f..4b4fc235c7 100644 --- a/pyccel/ast/numpy_wrapper.py +++ b/pyccel/ast/numpy_wrapper.py @@ -58,8 +58,8 @@ def get_numpy_max_acceptable_version_file(): numpy_max_acceptable_version = [1, 19] numpy_current_version = [int(v) for v in np.version.version.split('.')[:2]] numpy_api_acceptable_version = min(numpy_max_acceptable_version, numpy_current_version) - numpy_api_macro = '# define NPY_NO_DEPRECATED_API NPY_{}_{}_API_VERSION\n'.format( - *numpy_api_acceptable_version) + numpy_api_macro = '# define NPY_NO_DEPRECATED_API NPY_' + \ + f'{numpy_api_acceptable_version[0]}_{numpy_api_acceptable_version[1]}_API_VERSION\n' return '#ifndef NPY_NO_DEPRECATED_API\n'+ \ numpy_api_macro+\ @@ -227,7 +227,7 @@ def find_in_numpy_dtype_registry(var): return numpy_dtype_registry[(dtype, prec)] except KeyError: return errors.report(PYCCEL_RESTRICTION_TODO, - symbol = "{}[kind = {}]".format(dtype, prec), + symbol = f"{dtype}[kind = {prec}]", severity='fatal') def array_type_check(py_variable, c_variable, raise_error): diff --git a/pyccel/ast/numpyext.py b/pyccel/ast/numpyext.py index e4dc4d214a..d717ee3e7f 100644 --- a/pyccel/ast/numpyext.py +++ b/pyccel/ast/numpyext.py @@ -415,7 +415,7 @@ def _process_order(rank, order): order = str(order).strip('\'"') if order not in ('C', 'F'): - raise ValueError('unrecognized order = {}'.format(order)) + raise ValueError(f'unrecognized order = {order}') return order #============================================================================== @@ -436,7 +436,7 @@ class NumpyArray(NumpyNewArray): def __init__(self, arg, dtype=None, order='C'): if not isinstance(arg, (PythonTuple, PythonList, Variable)): - raise TypeError('Unknown type of %s.' % type(arg)) + raise TypeError(f'Unknown type of {type(arg)}.') is_homogeneous_tuple = isinstance(arg, (PythonTuple, PythonList, HomogeneousTupleVariable)) and arg.is_homogeneous is_array = isinstance(arg, Variable) and arg.is_ndarray @@ -566,7 +566,7 @@ class NumpySum(PyccelInternalFunction): def __init__(self, arg): if not isinstance(arg, PyccelAstNode): - raise TypeError('Unknown type of %s.' % type(arg)) + raise TypeError(f'Unknown type of {type(arg)}.') super().__init__(arg) if isinstance(arg.dtype, NativeBool): self._dtype = NativeInteger() @@ -592,7 +592,7 @@ class NumpyProduct(PyccelInternalFunction): def __init__(self, arg): if not isinstance(arg, PyccelAstNode): - raise TypeError('Unknown type of %s.' % type(arg)) + raise TypeError(f'Unknown type of {type(arg)}.' ) super().__init__(arg) self._arg = PythonList(arg) if arg.rank == 0 else self._args[0] self._arg = NumpyInt(self._arg) if (isinstance(arg.dtype, NativeBool) or \ @@ -620,9 +620,9 @@ def __init__(self, a ,b): return if not isinstance(a, PyccelAstNode): - raise TypeError('Unknown type of %s.' % type(a)) + raise TypeError(f'Unknown type of {type(a)}.') if not isinstance(b, PyccelAstNode): - raise TypeError('Unknown type of %s.' % type(a)) + raise TypeError(f'Unknown type of {type(a)}.') args = (a, b) integers = [e for e in args if e.dtype is NativeInteger()] @@ -643,7 +643,7 @@ def __init__(self, a ,b): self._dtype = NativeBool() self._precision = max_precision(booleans, allow_native = False) else: - raise TypeError('cannot determine the type of {}'.format(self)) + raise TypeError(f'cannot determine the type of {self}') if not (a.shape is None or b.shape is None): @@ -745,7 +745,7 @@ def __init__(self, start, stop, num=None, endpoint=True, dtype=None): self._dtype = NativeFloat() self._precision = default_precision['float'] else: - raise TypeError('cannot determine the type of {}'.format(self)) + raise TypeError(f'cannot determine the type of {self}') self._index = Variable('int', 'linspace_index') self._start = start @@ -866,7 +866,7 @@ def __init__(self, condition, x = None, y = None): self._dtype = NativeInteger() self._precision = max_precision(args, allow_native = False) else: - raise TypeError('cannot determine the type of {}'.format(self)) + raise TypeError(f'cannot determine the type of {self}') shape = broadcast(x.shape, y.shape) shape = broadcast(condition.shape, shape) @@ -1411,7 +1411,7 @@ def _set_dtype_precision(self, x1, x2): others = [a for a in args if a not in integers+floats] if others: - raise TypeError('{} not supported'.format(others[0].dtype)) + raise TypeError(f'{others[0].dtype} not supported') if floats: self._dtype = NativeFloat() @@ -1424,7 +1424,7 @@ def _set_dtype_precision(self, x1, x2): else: self._precision = 1 else: - raise TypeError('cannot determine the type of {}'.format(self)) + raise TypeError(f'cannot determine the type of {self}') class NumpyAmin(NumpyUfuncUnary): """Represent a call to the amin function in the Numpy library""" @@ -1707,7 +1707,7 @@ def __new__(cls, a, axis = None): elif not isinstance(a, (list, tuple, PyccelAstNode)): - raise TypeError('Unknown type of %s.' % type(a)) + raise TypeError(f'Unknown type of {type(a)}.') elif all(isinstance(s, LiteralInteger) for s in a.shape): return LiteralInteger(reduce(operator.mul, [s.python_value for s in a.shape])) else: @@ -1724,7 +1724,7 @@ def arg(self): return self._arg def __str__(self): - return 'Size({})'.format(str(self.arg)) + return f'Size({self.arg})' #============================================================================== # TODO split numpy_functions into multiple dictionaries following diff --git a/pyccel/ast/operators.py b/pyccel/ast/operators.py index d863a85d00..f4825cce44 100644 --- a/pyccel/ast/operators.py +++ b/pyccel/ast/operators.py @@ -278,7 +278,7 @@ def _handle_precedence(self, args): return args def __repr__(self): - return '+{}'.format(repr(self.args[0])) + return f'+{repr(self.args[0])}' #============================================================================== @@ -298,7 +298,7 @@ class PyccelUnarySub(PyccelUnary): __slots__ = () def __repr__(self): - return '-{}'.format(repr(self.args[0])) + return f'-{repr(self.args[0])}' #============================================================================== @@ -339,7 +339,7 @@ def _calculate_shape_rank(*args): return shape, rank def __repr__(self): - return 'not {}'.format(repr(self.args[0])) + return f'not {repr(self.args[0])}' #============================================================================== @@ -358,7 +358,7 @@ def _handle_precedence(self, args): return args def __repr__(self): - return '({})'.format(repr(self.args[0])) + return f'({repr(self.args[0])})' #============================================================================== @@ -404,7 +404,7 @@ def _calculate_dtype(cls, *args): elif integers: return cls._handle_integer_type(args) else: - raise TypeError('cannot determine the type of {}'.format(args)) + raise TypeError(f'cannot determine the type of {args}') @staticmethod def _handle_str_type(strs): @@ -507,7 +507,7 @@ class PyccelPow(PyccelArithmeticOperator): _precedence = 15 def __repr__(self): - return '{} ** {}'.format(self.args[0], self.args[1]) + return f'{self.args[0]} ** {self.args[1]}' def _handle_precedence(self, args): precedence = [getattr(a, 'precedence', 17) for a in args] @@ -578,7 +578,7 @@ def _handle_str_type(strs): return dtype, precision def __repr__(self): - return '{} + {}'.format(self.args[0], self.args[1]) + return f'{self.args[0]} + {self.args[1]}' #============================================================================== @@ -592,9 +592,9 @@ class PyccelMul(PyccelArithmeticOperator): Parameters ---------- - arg1: PyccelAstNode + arg1 : PyccelAstNode The first argument passed to the operator - arg2: PyccelAstNode + arg2 : PyccelAstNode The second argument passed to the operator """ __slots__ = () @@ -620,7 +620,7 @@ def __new__(cls, arg1, arg2, simplify = False): return super().__new__(cls) def __repr__(self): - return '{} * {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} * {repr(self.args[1])}' #============================================================================== @@ -662,7 +662,7 @@ def __new__(cls, arg1, arg2, simplify = False): return super().__new__(cls) def __repr__(self): - return '{} - {}'.format(repr(self.args[0]), repr(self.args[1])) + return f'{repr(self.args[0])} - {repr(self.args[1])}' #============================================================================== @@ -676,9 +676,9 @@ class PyccelDiv(PyccelArithmeticOperator): Parameters ---------- - arg1: PyccelAstNode + arg1 : PyccelAstNode The first argument passed to the operator - arg2: PyccelAstNode + arg2 : PyccelAstNode The second argument passed to the operator """ __slots__ = () @@ -697,7 +697,7 @@ def _handle_integer_type(integers): return dtype, precision def __repr__(self): - return '{} / {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} / {repr(self.args[1])}' #============================================================================== @@ -711,16 +711,16 @@ class PyccelMod(PyccelArithmeticOperator): Parameters ---------- - arg1: PyccelAstNode + arg1 : PyccelAstNode The first argument passed to the operator - arg2: PyccelAstNode + arg2 : PyccelAstNode The second argument passed to the operator """ __slots__ = () _precedence = 13 def __repr__(self): - return '{} % {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} % {repr(self.args[1])}' #============================================================================== @@ -734,16 +734,16 @@ class PyccelFloorDiv(PyccelArithmeticOperator): Parameters ---------- - arg1: PyccelAstNode + arg1 : PyccelAstNode The first argument passed to the operator - arg2: PyccelAstNode + arg2 : PyccelAstNode The second argument passed to the operator """ __slots__ = () _precedence = 13 def __repr__(self): - return '{} // {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} // {repr(self.args[1])}' #============================================================================== @@ -753,9 +753,9 @@ class PyccelComparisonOperator(PyccelBinaryOperator): Parameters ---------- - arg1: PyccelAstNode + arg1 : PyccelAstNode The first argument passed to the operator - arg2: PyccelAstNode + arg2 : PyccelAstNode The second argument passed to the operator """ __slots__ = () @@ -792,7 +792,7 @@ def __new__(cls, arg1, arg2, simplify = False): return super().__new__(cls) def __repr__(self): - return '{} == {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} == {repr(self.args[1])}' class PyccelNe(PyccelComparisonOperator): """ @@ -818,7 +818,7 @@ def __new__(cls, arg1, arg2, simplify = False): return super().__new__(cls) def __repr__(self): - return '{} != {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} != {repr(self.args[1])}' class PyccelLt(PyccelComparisonOperator): """ @@ -838,7 +838,7 @@ class PyccelLt(PyccelComparisonOperator): __slots__ = () def __repr__(self): - return '{} < {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} < {repr(self.args[1])}' class PyccelLe(PyccelComparisonOperator): """ @@ -858,7 +858,7 @@ class PyccelLe(PyccelComparisonOperator): __slots__ = () def __repr__(self): - return '{} <= {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} <= {repr(self.args[1])}' class PyccelGt(PyccelComparisonOperator): """ @@ -878,7 +878,7 @@ class PyccelGt(PyccelComparisonOperator): __slots__ = () def __repr__(self): - return '{} > {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} > {repr(self.args[1])}' class PyccelGe(PyccelComparisonOperator): """ @@ -898,7 +898,7 @@ class PyccelGe(PyccelComparisonOperator): __slots__ = () def __repr__(self): - return '{} >= {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} >= {repr(self.args[1])}' #============================================================================== @@ -955,7 +955,7 @@ def _handle_precedence(self, args): return args def __repr__(self): - return '{} and {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} and {repr(self.args[1])}' #============================================================================== @@ -982,7 +982,7 @@ def _handle_precedence(self, args): return args def __repr__(self): - return '{} or {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} or {repr(self.args[1])}' #============================================================================== @@ -1013,7 +1013,7 @@ def rhs(self): return self._args[1] def __repr__(self): - return '{} is {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} is {repr(self.args[1])}' def eval(self): """ Determines the value of the expression `x is None` when `x` is known. @@ -1049,7 +1049,7 @@ class PyccelIsNot(PyccelIs): __slots__ = () def __repr__(self): - return '{} is not {}'.format(self.args[0], self.args[1]) + return f'{repr(self.args[0])} is not {repr(self.args[1])}' def eval(self): """ Determines the value of the expression `x is not None` when `x` is known. diff --git a/pyccel/ast/utilities.py b/pyccel/ast/utilities.py index 82cb8833e7..e1fe52f5a8 100644 --- a/pyccel/ast/utilities.py +++ b/pyccel/ast/utilities.py @@ -198,7 +198,7 @@ def get_function_from_ast(ast, func_name): break if node is None: - print('> could not find {}'.format(func_name)) + print(f'> could not find {func_name}') return node @@ -345,7 +345,7 @@ def insert_index(expr, pos, index_var): return expr[index_var] else: - raise NotImplementedError("Expansion not implemented for type : {}".format(type(expr))) + raise NotImplementedError(f"Expansion not implemented for type : {type(expr)}") #============================================================================== diff --git a/pyccel/ast/variable.py b/pyccel/ast/variable.py index 3c84a7cf2d..7ebee8825e 100644 --- a/pyccel/ast/variable.py +++ b/pyccel/ast/variable.py @@ -148,7 +148,7 @@ def __init__( raise ValueError("Variable name can't be empty") if not isinstance(name, (str, DottedName)): - raise TypeError('Expecting a string or DottedName, given {0}'.format(type(name))) + raise TypeError(f'Expecting a string or DottedName, given {type(name)}') self._name = name if memory_handling not in ('heap', 'stack', 'alias'): @@ -412,7 +412,8 @@ def __str__(self): return str(self.name) def __repr__(self): - return '{}({}, dtype={})'.format(type(self).__name__, repr(self.name), repr(self.dtype)) + type_name = type(self).__name__ + return f'{type_name}({repr(self.name)}, dtype={repr(self.dtype)})' def __eq__(self, other): if type(self) is type(other): @@ -426,16 +427,16 @@ def inspect(self): """inspects the variable.""" print('>>> Variable') - print( ' name = {}'.format(self.name)) - print( ' dtype = {}'.format(self.dtype)) - print( ' precision = {}'.format(get_final_precision(self))) - print( ' rank = {}'.format(self.rank)) - print( ' order = {}'.format(self.order)) - print( ' memory_handling = {}'.format(self.memory_handling)) - print( ' shape = {}'.format(self.shape)) - print( ' cls_base = {}'.format(self.cls_base)) - print( ' is_target = {}'.format(self.is_target)) - print( ' is_optional = {}'.format(self.is_optional)) + print(f' name = {self.name}') + print(f' dtype = {self.dtype}') + print(f' precision = {get_final_precision(self)}') + print(f' rank = {self.rank}') + print(f' order = {self.order}') + print(f' memory_handling = {self.memory_handling}') + print(f' shape = {self.shape}') + print(f' cls_base = {self.cls_base}') + print(f' is_target = {self.is_target}') + print(f' is_optional = {self.is_optional}') print( '<<<') def use_exact_precision(self): @@ -767,9 +768,7 @@ def value(self): return self._value def __str__(self): - name = str(self.name) - value = str(self.value) - return '{0}={1}'.format(name, value) + return f'{self.name}={self.value}' @@ -874,10 +873,12 @@ def indices(self): return self._indices def __str__(self): - return '{}[{}]'.format(self.base, ','.join(str(i) for i in self.indices)) + indices = ','.join(str(i) for i in self.indices) + return f'{self.base}[{indices}]' def __repr__(self): - return '{}[{}]'.format(repr(self.base), ','.join(repr(i) for i in self.indices)) + indices = ','.join(repr(i) for i in self.indices) + return f'{repr(self.base)}[{indices}]' def __getitem__(self, *args): diff --git a/pyccel/codegen/codegen.py b/pyccel/codegen/codegen.py index 1a5568bf96..17fdb0c129 100644 --- a/pyccel/codegen/codegen.py +++ b/pyccel/codegen/codegen.py @@ -141,7 +141,7 @@ def set_printer(self, **settings): # Set language if not language in ['fortran', 'c', 'python']: - raise ValueError('{} language is not available'.format(language)) + raise ValueError(f'{language} language is not available') self._language = language # instantiate codePrinter @@ -191,8 +191,8 @@ def export(self, filename=None, **settings): header_ext = _header_extension_registry[self._language] if filename is None: filename = self.name - header_filename = '{name}.{ext}'.format(name=filename, ext=header_ext) - filename = '{name}.{ext}'.format(name=filename, ext=ext) + header_filename = f'{filename}.{header_ext}' + filename = f'{filename}.{ext}' # print module header if header_ext is not None: diff --git a/pyccel/codegen/pipeline.py b/pyccel/codegen/pipeline.py index 78fd3cc69c..7d86834ba7 100644 --- a/pyccel/codegen/pipeline.py +++ b/pyccel/codegen/pipeline.py @@ -139,7 +139,7 @@ def execute_pyccel(fname, *, # Unified way to handle errors: print formatted error message, then move # to original working directory. Caller should then raise exception. def handle_error(stage): - print('\nERROR at {} stage'.format(stage)) + print(f'\nERROR at {stage} stage') errors.check() os.chdir(base_dirpath) @@ -261,7 +261,7 @@ def handle_error(stage): output_file = (output_name + '.py') if output_name else os.path.basename(fname) new_location = os.path.join(folder, output_file) if verbose: - print("cp {} {}".format(fname, new_location)) + print(f"cp {fname} {new_location}") shutil.copyfile(fname, new_location) # Change working directory back to starting point @@ -399,7 +399,7 @@ def get_module_dependencies(parser, deps): shutil.move(generated_filepath, target) generated_filepath = target if verbose: - print( '> Shared library has been created: {}'.format(generated_filepath)) + print( '> Shared library has been created:', generated_filepath) if codegen.is_program: generated_program_filename = os.path.basename(generated_program_filepath) @@ -408,7 +408,7 @@ def get_module_dependencies(parser, deps): generated_program_filepath = target if verbose: - print( '> Executable has been created: {}'.format(generated_program_filepath)) + print( '> Executable has been created:', generated_program_filepath) # Print all warnings now if errors.has_warnings(): diff --git a/pyccel/codegen/printing/codeprinter.py b/pyccel/codegen/printing/codeprinter.py index f0e71a0af7..237125357b 100644 --- a/pyccel/codegen/printing/codeprinter.py +++ b/pyccel/codegen/printing/codeprinter.py @@ -42,8 +42,7 @@ def doprint(self, expr, assign_to=None): if isinstance(assign_to, str): assign_to = PyccelSymbol(assign_to) elif not isinstance(assign_to, (Basic, type(None))): - raise TypeError("{0} cannot assign to object of type {1}".format( - type(self).__name__, type(assign_to))) + raise TypeError(f"{type(self).__name__} cannot assign to object of type {type(assign_to)}") if assign_to: expr = Assign(assign_to, expr) @@ -122,7 +121,7 @@ def _print_str(self, expr): def _print_not_supported(self, expr): """ Print an error message if the print function for the type is not implemented """ - msg = '_print_{} is not yet implemented for language : {}\n'.format(type(expr).__name__, self.language) + msg = f'_print_{type(expr).__name__} is not yet implemented for language : {self.language}\n' errors.report(msg+PYCCEL_RESTRICTION_TODO, symbol = expr, severity='fatal') diff --git a/pyccel/codegen/printing/cwrappercode.py b/pyccel/codegen/printing/cwrappercode.py index a62e9871b8..862321f569 100644 --- a/pyccel/codegen/printing/cwrappercode.py +++ b/pyccel/codegen/printing/cwrappercode.py @@ -275,7 +275,7 @@ def get_default_assign(self, arg, func_arg, value): elif isinstance(arg.dtype, PyccelPyObject): return AliasAssign(arg, Py_None) else: - raise NotImplementedError('Default values are not implemented for this datatype : {}'.format(func_arg.dtype)) + raise NotImplementedError(f'Default values are not implemented for this datatype : {func_arg.dtype}') def static_function_signature(self, expr): """ @@ -1356,29 +1356,19 @@ def _print_PyArg_ParseTupleNode(self, expr): pykwarg = expr.pykwarg flags = expr.flags # All args are modified so even pointers are passed by address - args = ', '.join(['&{}'.format(a.name) for a in expr.args]) + args = ', '.join(f'&{a.name}' for a in expr.args) if expr.args: - code = '{name}({pyarg}, {pykwarg}, "{flags}", {kwlist}, {args})'.format( - name=name, - pyarg=pyarg, - pykwarg=pykwarg, - flags = flags, - kwlist = expr.arg_names.name, - args = args) + code = f'{name}({pyarg}, {pykwarg}, "{flags}", {expr.arg_names.name}, {args})' else : - code ='{name}({pyarg}, {pykwarg}, "", {kwlist})'.format( - name=name, - pyarg=pyarg, - pykwarg=pykwarg, - kwlist = expr.arg_names.name) + code =f'{name}({pyarg}, {pykwarg}, "", {expr.arg_names.name})' return code def _print_PyBuildValueNode(self, expr): name = 'Py_BuildValue' flags = expr.flags - args = ', '.join(['{}'.format(self._print(a)) for a in expr.args]) + args = ', '.join(self._print(a) for a in expr.args) #to change for args rank 1 + if expr.args: code = f'(*{name}("{flags}", {args}))' @@ -1387,16 +1377,15 @@ def _print_PyBuildValueNode(self, expr): return code def _print_PyArgKeywords(self, expr): - arg_names = ',\n'.join(['"{}"'.format(a) for a in expr.arg_names] + [self._print(Nil())]) - return ('static char *{name}[] = {{\n' - '{arg_names}\n' - '}};\n'.format(name=expr.name, arg_names = arg_names)) + arg_names = ',\n'.join([f'"{a}"' for a in expr.arg_names] + [self._print(Nil())]) + return (f'static char *{expr.name}[] = {{\n' + f'{arg_names}\n' + '}};\n') def _print_PyModule_AddObject(self, expr): - return 'PyModule_AddObject({}, {}, {})'.format( - expr.mod_name, - self._print(expr.name), - self._print(expr.variable)) + name = self._print(expr.name) + var = self._print(expr.variable) + return f'PyModule_AddObject({expr.mod_name}, {name}, {var})' def _print_FunctionDef(self, expr): self.set_scope(self.scope.new_child_scope(expr.name)) @@ -1579,56 +1568,52 @@ def _print_Module(self, expr): function_defs = '\n'.join(self._print(f) for f in funcs) cast_functions = '\n'.join(CCodePrinter._print_FunctionDef(self, f) for f in self._cast_functions_dict.values()) + + name = self.get_python_name(expr.scope, f) + wrapper_name = self._function_wrapper_names[f.name] + doc_string = self._print(LiteralString('\n'.join(f.doc_string.comments))) \ + if f.doc_string else '""' + method_def_func = ''.join(('{{\n' - '"{name}",\n' - '(PyCFunction){wrapper_name},\n' + f'"{name}",\n' + f'(PyCFunction){wrapper_name},\n' 'METH_VARARGS | METH_KEYWORDS,\n' - '{doc_string}\n' - '}},\n').format( - name = self.get_python_name(expr.scope, f), - wrapper_name = self._function_wrapper_names[f.name], - doc_string = self._print(LiteralString('\n'.join(f.doc_string.comments))) \ - if f.doc_string else '""') + f'{doc_string}\n' + '}},\n') for f in funcs if f is not expr.init_func) - slots_name = self.scope.get_new_name('{}_slots'.format(expr.name)) + slots_name = self.scope.get_new_name(f'{expr.name}_slots') exec_func_name = self.scope.get_new_name('exec_func') - slots_def = ('static PyModuleDef_Slot {name}[] = {{\n' - '{{Py_mod_exec, {exec_func}}},\n' - '{{0, NULL}},\n' - '}};\n').format(name = slots_name, - exec_func = exec_func_name) - - method_def_name = self.scope.get_new_name('{}_methods'.format(expr.name)) - method_def = ('static PyMethodDef {method_def_name}[] = {{\n' - '{method_def_func}' - '{{ NULL, NULL, 0, NULL}}\n' - '}};\n'.format(method_def_name = method_def_name, - method_def_func = method_def_func)) - - module_def_name = self.scope.get_new_name('{}_module'.format(expr.name)) - module_def = ('static struct PyModuleDef {module_def_name} = {{\n' - 'PyModuleDef_HEAD_INIT,\n' - '/* name of module */\n' - '\"{mod_name}\",\n' - '/* module documentation, may be NULL */\n' - 'NULL,\n' #TODO: Add documentation - '/* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */\n' - '0,\n' - '{method_def_name},\n' - '{slots_name}\n' - '}};\n'.format(module_def_name = module_def_name, - mod_name = self._module_name, - method_def_name = method_def_name, - slots_name = slots_name)) + slots_def = (f'static PyModuleDef_Slot {slots_name}[] = {{\n' + f'{{Py_mod_exec, {exec_func_name}}},\n' + '{{0, NULL}},\n' + '}};\n') + + method_def_name = self.scope.get_new_name(f'{expr.name}_methods') + method_def = (f'static PyMethodDef {method_def_name}[] = {{\n' + f'{method_def_func}' + '{{ NULL, NULL, 0, NULL}}\n' + '}};\n') + + module_def_name = self.scope.get_new_name('{expr.name}_module') + module_def = (f'static struct PyModuleDef {module_def_name} = {{\n' + 'PyModuleDef_HEAD_INIT,\n' + '/* name of module */\n' + f'\"{self._module_name}\",\n' + '/* module documentation, may be NULL */\n' + 'NULL,\n' #TODO: Add documentation + '/* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */\n' + '0,\n' + f'{method_def_name},\n' + f'{slots_name}\n' + '}};\n') exec_func = self.get_module_exec_function(expr, exec_func_name) - init_func = ('PyMODINIT_FUNC PyInit_{mod_name}(void)\n{{\n' - 'import_array();\n' - 'return PyModuleDef_Init(&{module_def_name});\n' - '}}\n'.format(mod_name=self._module_name, - module_def_name = module_def_name)) + init_func = (f'PyMODINIT_FUNC PyInit_{self._module_name}(void)\n{{\n' + 'import_array();\n' + f'return PyModuleDef_Init(&{module_def_name});\n' + '}}\n') # Print imports last to be sure that all additional_imports have been collected imports = module_imports.copy() @@ -1638,33 +1623,22 @@ def _print_Module(self, expr): self.exit_scope() return ('#define PY_ARRAY_UNIQUE_SYMBOL CWRAPPER_ARRAY_API\n' - '{imports}\n' - '{variable_declarations}\n' - '{function_signatures}\n' - '{sep}\n' - '{cast_functions}\n' - '{sep}\n' - '{function_defs}\n' - '{exec_func}\n' - '{sep}\n' - '{method_def}\n' - '{sep}\n' - '{slots_def}\n' - '{sep}\n' - '{module_def}\n' - '{sep}\n' - '{init_func}'.format( - imports = imports, - variable_declarations = decs, - function_signatures = function_signatures, - sep = sep, - cast_functions = cast_functions, - function_defs = function_defs, - exec_func = exec_func, - method_def = method_def, - slots_def = slots_def, - module_def = module_def, - init_func = init_func)) + f'{imports}\n' + f'{decs}\n' + f'{function_signatures}\n' + f'{sep}\n' + f'{cast_functions}\n' + f'{sep}\n' + f'{function_defs}\n' + f'{exec_func}\n' + f'{sep}\n' + f'{method_def}\n' + f'{sep}\n' + f'{slots_def}\n' + f'{sep}\n' + f'{module_def}\n' + f'{sep}\n' + f'{init_func}') def cwrappercode(expr, filename, target_language, assign_to=None, **settings): """Converts an expr to a string of c wrapper code diff --git a/pyccel/codegen/printing/pycode.py b/pyccel/codegen/printing/pycode.py index f58e957543..86f74edee0 100644 --- a/pyccel/codegen/printing/pycode.py +++ b/pyccel/codegen/printing/pycode.py @@ -148,7 +148,7 @@ def _find_functional_expr_and_iterables(self, expr): body, it = self._find_functional_expr_and_iterables(body) iterables.extend(it) else: - raise NotImplementedError("Type {} not handled in a FunctionalFor".format(type(body))) + raise NotImplementedError(f"Type {type(body)} not handled in a FunctionalFor") return body, iterables #---------------------------------------------------------------------- @@ -158,7 +158,7 @@ def _print_Header(self, expr): def _print_tuple(self, expr): fs = ', '.join(self._print(f) for f in expr) - return '({0})'.format(fs) + return f'({fs})' def _print_NativeBool(self, expr): return 'bool' @@ -193,7 +193,7 @@ def _print_FunctionDefArgument(self, expr): def _print_FunctionCallArgument(self, expr): if expr.keyword: - return '{} = {}'.format(expr.keyword, self._print(expr.value)) + return f'{expr.keyword} = {self._print(expr.value)}' else: return self._print(expr.value) @@ -217,7 +217,7 @@ def _print_IndexedElement(self, expr): severity='fatal') base = self._print(expr.base) - return '{base}[{indices}]'.format(base=base, indices=indices) + return f'{base}[{indices}]' def _print_Interface(self, expr): # TODO: Improve. See #885 @@ -246,11 +246,8 @@ def _print_FunctionDef(self, expr): body = ''.join([doc_string, functions, interfaces, imports, body]) - code = ('def {name}({args}):\n' - '{body}\n').format( - name=name, - args=args, - body=body) + code = (f'def {name}({args}):\n' + f'{body}\n') decorators = expr.decorators if decorators: if decorators['template']: @@ -276,16 +273,16 @@ def _print_FunctionDef(self, expr): continue if args: args = ', '.join(self._print(i) for i in args) - dec += '@{name}({args})\n'.format(name=n, args=args) + dec += f'@{n}({args})\n' else: - dec += '@{name}\n'.format(name=n) + dec += f'@{n}\n' - code = '{dec}{code}'.format(dec=dec, code=code) + code = dec + code headers = expr.headers if headers: headers = self._print(headers) - code = '{header}\n{code}'.format(header=headers, code=code) + code = f'{headers}\n{code}' self.exit_scope() return code @@ -303,7 +300,9 @@ def _print_Return(self, expr): prelude = '' expr_return_vars = [assigns.get(a,a) for a in expr.expr] - return prelude+'return {}\n'.format(','.join(self._print(i) for i in expr_return_vars)) + return_vars_str = ','.join(self._print(i) for i in expr_return_vars) + + return prelude+f'return {return_vars_str}\n' def _print_Program(self, expr): mod_scope = self.scope @@ -319,7 +318,7 @@ def _print_Program(self, expr): if mod_scope: self.set_scope(mod_scope) return ('if __name__ == "__main__":\n' - '{body}\n').format(body=body) + f'{body}\n') def _print_AsName(self, expr): @@ -328,7 +327,7 @@ def _print_AsName(self, expr): if name == target: return name else: - return '{name} as {target}'.format(name = name, target = target) + return f'{name} as {target}' def _print_PythonTuple(self, expr): args = ', '.join(self._print(i) for i in expr.args) @@ -341,7 +340,7 @@ def _print_PythonList(self, expr): return '['+args+']' def _print_PythonBool(self, expr): - return 'bool({})'.format(self._print(expr.arg)) + return f'bool({self._print(expr.arg)})' def _print_PythonInt(self, expr): name = 'int' @@ -353,7 +352,7 @@ def _print_PythonInt(self, expr): self.insert_new_import( source = 'numpy', target = AsName(cls, name)) - return '{}({})'.format(name, self._print(expr.arg)) + return f'{name}({self._print(expr.arg)})' def _print_PythonFloat(self, expr): name = 'float' @@ -365,14 +364,14 @@ def _print_PythonFloat(self, expr): self.insert_new_import( source = 'numpy', target = AsName(cls, name)) - return '{}({})'.format(name, self._print(expr.arg)) + return f'{name}({self._print(expr.arg)})' def _print_PythonComplex(self, expr): name = self._aliases.get(type(expr), expr.name) if expr.is_cast: - return '{}({})'.format(name, self._print(expr.internal_var)) + return f'{name}({self._print(expr.internal_var)})' else: - return '{}({}, {})'.format(name, self._print(expr.real), self._print(expr.imag)) + return f'{name}({self._print(expr.real)}, {self._print(expr.imag)})' def _print_NumpyComplex(self, expr): if expr.precision != -1: @@ -385,44 +384,44 @@ def _print_NumpyComplex(self, expr): else: name = 'complex' if expr.is_cast: - return '{}({})'.format(name, self._print(expr.internal_var)) + return f'{name}({self._print(expr.internal_var)})' else: - return '{}({}+{}*1j)'.format(name, self._print(expr.real), self._print(expr.imag)) + return f'{name}({self._print(expr.real)}+{self._print(expr.imag)}*1j)' def _print_Iterable(self, expr): return self._print(expr.iterable) def _print_PythonRange(self, expr): - return 'range({start}, {stop}, {step})'.format( - start = self._print(expr.start), - stop = self._print(expr.stop ), - step = self._print(expr.step )) + start = self._print(expr.start) + stop = self._print(expr.stop ) + step = self._print(expr.step ) + return f'range({start}, {stop}, {step})' def _print_PythonEnumerate(self, expr): + elem = self._print(expr.element) if expr.start == 0: - return 'enumerate({elem})'.format( - elem = self._print(expr.element)) + return f'enumerate({elem})' else: - return 'enumerate({elem},{start})'.format( - elem = self._print(expr.element), - start = self._print(expr.start)) + start = self._print(expr.start) + return f'enumerate({elem},{start})' def _print_PythonMap(self, expr): - return 'map({func}, {args})'.format( - func = self._print(expr.func.name), - args = self._print(expr.func_args)) + func = self._print(expr.func.name) + args = self._print(expr.func_args) + return f'map({func}, {args})' def _print_PythonReal(self, expr): - return '({}).real'.format(self._print(expr.internal_var)) + return f'({self._print(expr.internal_var)}).real' def _print_PythonImag(self, expr): - return '({}).imag'.format(self._print(expr.internal_var)) + return f'({self._print(expr.internal_var)}).imag' def _print_PythonConjugate(self, expr): - return '({}).conjugate()'.format(self._print(expr.internal_var)) + return f'({self._print(expr.internal_var)}).conjugate()' def _print_PythonPrint(self, expr): - return 'print({})\n'.format(', '.join(self._print(a) for a in expr.expr)) + args = ', '.join(self._print(a) for a in expr.expr) + return f'print({args})\n' def _print_PyccelArraySize(self, expr): arg = self._print(expr.arg) @@ -432,19 +431,19 @@ def _print_PyccelArraySize(self, expr): self.insert_new_import( source = 'numpy', target = AsName(type(expr),expr.name)) - return '{0}({1})[{2}]'.format(name, arg, index) + return f'{name}({arg})[{index}]' def _print_Comment(self, expr): txt = self._print(expr.text) - return '# {0} \n'.format(txt) + return f'# {txt} \n' def _print_CommentBlock(self, expr): txt = '\n'.join(self._print(c) for c in expr.comments) - return '"""{0}"""\n'.format(txt) + return f'"""{txt}"""\n' def _print_Assert(self, expr): condition = self._print(expr.test) - return "assert {0}\n".format(condition) + return f"assert {condition}\n" def _print_EmptyNode(self, expr): return '' @@ -460,7 +459,7 @@ def _print_FunctionCall(self, expr): else: func_name = expr.funcdef.name args = ', '.join(self._print(i) for i in expr.args) - code = '{func}({args})'.format(func=func_name, args=args) + code = f'{func_name}({args})' if expr.funcdef.results: return code else: @@ -488,7 +487,7 @@ def _print_Import(self, expr): target = [t for t in expr.target if not isinstance(t.object, Module)] if not target: - return 'import {source}\n'.format(source=source) + return f'import {source}\n' else: if source in import_object_swap: target = [AsName(import_object_swap[source].get(i.object,i.object), i.target) for i in target] @@ -510,7 +509,7 @@ def _print_Import(self, expr): self._ignore_funcs.append(expr.source_module.free_func) target = [self._print(t) for t in target if t.name not in (init_func_name, free_func_name)] target = ', '.join(target) - return 'from {source} import {target}\n'.format(source=source, target=target) + return f'from {source} import {target}\n' def _print_CodeBlock(self, expr): if len(expr.body)==0: @@ -528,8 +527,8 @@ def _print_For(self, expr): target = ','.join(self._print(i) for i in target) body = self._print(expr.body) body = self._indent_codestring(body) - code = ('for {0} in {1}:\n' - '{2}').format(target,iterable,body) + code = (f'for {target} in {iterable}:\n' + f'{body}') self.exit_scope() return code @@ -538,8 +537,8 @@ def _print_FunctionalFor(self, expr): body, iterators = self._find_functional_expr_and_iterables(expr) lhs = self._print(expr.lhs) body = self._print(body.rhs) - for_loops = ' '.join(['for {} in {}'.format(self._print(idx), self._print(iters)) - for idx, iters in zip(expr.indices, iterators)]) + for_loops = ' '.join(f'for {self._print(idx)} in {self._print(iters)}' + for idx, iters in zip(expr.indices, iterators)) name = self._aliases.get(type(expr),'array') if name == 'array': @@ -547,7 +546,7 @@ def _print_FunctionalFor(self, expr): source = 'numpy', target = AsName(NumpyArray, 'array')) - return '{} = {}([{} {}])\n'.format(lhs, name, body, for_loops) + return f'{lhs} = {name}([{body} {for_loops}])\n' def _print_GeneratorComprehension(self, expr): body, iterators = self._find_functional_expr_and_iterables(expr) @@ -563,23 +562,21 @@ def _print_GeneratorComprehension(self, expr): rhs = type(body.rhs)(*args) body = self._print(rhs) - for_loops = ' '.join(['for {} in {}'.format(self._print(idx), self._print(iters)) - for idx, iters in zip(expr.indices, iterators)]) + for_loops = ' '.join(f'for {self._print(idx)} in {self._print(iters)}' + for idx, iters in zip(expr.indices, iterators)) if expr.get_user_nodes(FunctionalFor): - return '{}({} {})'.format(expr.name, body, for_loops) + return f'{expr.name}({body} {for_loops})' else: lhs = self._print(expr.lhs) - return '{} = {}({} {})\n'.format(lhs, expr.name, body, for_loops) + return f'{lhs} = {expr.name}({body} {for_loops})\n' def _print_While(self, expr): cond = self._print(expr.test) self.set_scope(expr.scope) body = self._indent_codestring(self._print(expr.body)) self.exit_scope() - return 'while {cond}:\n{body}'.format( - cond = cond, - body = body) + return f'while {cond}:\n{body}' def _print_Break(self, expr): return 'break\n' @@ -594,9 +591,9 @@ def _print_Assign(self, expr): lhs_code = self._print(lhs) rhs_code = self._print(rhs) if isinstance(rhs, Variable) and rhs.rank>1 and rhs.order != lhs.order: - return'{0} = {1}.T\n'.format(lhs_code,rhs_code) + return f'{lhs_code} = {rhs_code}.T\n' else: - return'{0} = {1}\n'.format(lhs_code,rhs_code) + return f'{lhs_code} = {rhs_code}\n' def _print_AliasAssign(self, expr): lhs = expr.lhs @@ -605,22 +602,22 @@ def _print_AliasAssign(self, expr): lhs_code = self._print(lhs) rhs_code = self._print(rhs) if isinstance(rhs, Variable) and rhs.order!= lhs.order: - return'{0} = {1}.T\n'.format(lhs_code,rhs_code) + return f'{lhs_code} = {rhs_code}.T\n' else: - return'{0} = {1}\n'.format(lhs_code,rhs_code) + return f'{lhs_code} = {rhs_code}\n' def _print_AugAssign(self, expr): lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) op = self._print(expr.op) - return'{0} {1}= {2}\n'.format(lhs,op,rhs) + return f'{lhs} {op}= {rhs}\n' def _print_PythonRange(self, expr): name = self._aliases.get(type(expr), expr.name) start = self._print(expr.start) stop = self._print(expr.stop) step = self._print(expr.step) - return '{}({}, {}, {})'.format(name,start,stop,step) + return f'{name}({start}, {stop}, {step})' def _print_Allocate(self, expr): return '' @@ -636,12 +633,10 @@ def _print_NumpyArray(self, expr): name = self._aliases.get(type(expr), expr.name) arg = self._print(expr.arg) - dtype = "dtype={}".format(dtype) - order = "order='{}'".format(expr.order) if expr.order else '' - args = [arg, dtype, order] - return "{name}({args})".format( - name = name, - args = ', '.join(a for a in args if a)) + dtype = f"dtype={dtype}" + order = f"order='{expr.order}'" if expr.order else '' + args = ', '.join(a for a in [arg, dtype, order] if a) + return f"{name}({args})" def _print_NumpyAutoFill(self, expr): func_name = self._aliases.get(type(expr), expr.name) @@ -652,12 +647,10 @@ def _print_NumpyAutoFill(self, expr): dtype += str(expr.precision*factor) shape = self._print(expr.shape) - dtype = "dtype={}".format(dtype) - order = "order='{}'".format(expr.order) if expr.order else '' - args = [shape, dtype, order] - return "{func_name}({args})".format( - func_name = func_name, - args = ', '.join(a for a in args if a)) + dtype = f"dtype={dtype}" + order = f"order='{expr.order}'" if expr.order else '' + args = ', '.join(a for a in [shape, dtype, order] if a) + return f"{func_name}({args})" def _print_NumpyLinspace(self, expr): name = self._aliases.get(type(expr), expr.name) @@ -665,20 +658,16 @@ def _print_NumpyLinspace(self, expr): factor = 16 if dtype == 'complex' else 8 dtype += str(expr.precision*factor) - return "{0}({1}, {2}, num={3}, endpoint={4}, dtype='{5}')".format( - name, - self._print(expr.start), - self._print(expr.stop), - self._print(expr.num), - self._print(expr.endpoint), - dtype) + start = self._print(expr.start) + stop = self._print(expr.stop) + num = self._print(expr.num) + endpoint = self._print(expr.endpoint) + + return f"{name}({start}, {stop}, num={num}, endpoint={endpoint}, dtype='{dtype}')" def _print_NumpyMatmul(self, expr): name = self._aliases.get(type(expr), expr.name) - return "{0}({1}, {2})".format( - name, - self._print(expr.a), - self._print(expr.b)) + return f"{name}({self._print(expr.a)}, {self._print(expr.b)})" def _print_NumpyFull(self, expr): @@ -690,26 +679,23 @@ def _print_NumpyFull(self, expr): shape = self._print(expr.shape) fill_value = self._print(expr.fill_value) - dtype = "dtype={}".format(dtype) - order = "order='{}'".format(expr.order) if expr.order else '' - args = [shape, fill_value, dtype, order] - return "{name}({args})".format( - name = name, - args = ', '.join(a for a in args if a)) + dtype = f"dtype={dtype}" + order = f"order='{expr.order}'" if expr.order else '' + args = ', '.join(a for a in [shape, fill_value, dtype, order] if a) + return f"{name}({args})" def _print_NumpyArange(self, expr): name = self._aliases.get(type(expr), expr.name) - return "{name}({start}, {stop}, {step}, dtype={dtype})".format( - name = name, - start = self._print(expr.start), - stop = self._print(expr.stop), - step = self._print(expr.step), - dtype = self._print(expr.dtype)) + start = self._print(expr.start) + stop = self._print(expr.stop) + step = self._print(expr.step) + dtype = self._print(expr.dtype) + return f"{name}({start}, {stop}, {step}, dtype={dtype})" def _print_PyccelInternalFunction(self, expr): name = self._aliases.get(type(expr),expr.name) args = ', '.join(self._print(a) for a in expr.args) - return "{}({})".format(name, args) + return f"{name}({args})" def _print_NumpyArray(self, expr): name = self._aliases.get(type(expr),'array') @@ -718,26 +704,26 @@ def _print_NumpyArray(self, expr): source = 'numpy', target = AsName(NumpyArray, 'array')) arg = self._print(expr.arg) - return "{}({})".format(name, arg) + return f"{name}({arg})" def _print_NumpyRandint(self, expr): name = self._aliases.get(type(expr), expr.name) if expr.low: - args = "{}, ".format(self._print(expr.low)) + args = self._print(expr.low) + ", " else: args = "" - args += "{}".format(self._print(expr.high)) + args += self._print(expr.high) if expr.rank != 0: size = self._print(expr.shape) - args += ", size = {}".format(size) - return "{}({})".format(name, args) + args += f", size = {size}" + return f"{name}({args})" def _print_NumpyNorm(self, expr): name = self._aliases.get(type(expr), expr.name) axis = self._print(expr.axis) if expr.axis else None if axis: - return "{name}({arg},axis={axis})".format(name = name, arg = self._print(expr.python_arg), axis=axis) - return "{name}({arg})".format(name = name, arg = self._print(expr.python_arg)) + return f"{name}({self._print(expr.python_arg)},axis={axis})" + return f"{name}({self._print(expr.python_arg)})" def _print_NumpyNonZero(self, expr): name = self._aliases.get(type(expr),'nonzero') @@ -746,7 +732,7 @@ def _print_NumpyNonZero(self, expr): source = 'numpy', target = AsName(NumpyNonZero, 'nonzero')) arg = self._print(expr.array) - return "{}({})".format(name, arg) + return f"{name}({arg})" def _print_NumpyCountNonZero(self, expr): name = self._aliases.get(type(expr),'count_nonzero') @@ -759,20 +745,17 @@ def _print_NumpyCountNonZero(self, expr): arr = self._print(expr.array) axis = '' if axis_arg is None else (self._print(axis_arg) + ', ') - keep_dims = 'keepdims = {}'.format(self._print(expr.keep_dims)) + keep_dims = 'keepdims = ' + self._print(expr.keep_dims) - arg = '{}, {}{}'.format(arr, axis, keep_dims) + arg = f'{arr}, {axis}{keep_dims}' - return "{}({})".format(name, arg) + return "{name}({arg})" def _print_Slice(self, expr): start = self._print(expr.start) if expr.start else '' stop = self._print(expr.stop) if expr.stop else '' step = self._print(expr.step) if expr.step else '' - return '{start}:{stop}:{step}'.format( - start = start, - stop = stop, - step = step) + return f'{start}:{stop}:{step}' def _print_Nil(self, expr): return 'None' @@ -783,24 +766,24 @@ def _print_Pass(self, expr): def _print_PyccelIs(self, expr): lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) - return'{0} is {1}'.format(lhs,rhs) + return '{lhs} is {rhs}' def _print_PyccelIsNot(self, expr): lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) - return'{0} is not {1}'.format(lhs,rhs) + return '{lhs} is not {rhs}' def _print_If(self, expr): lines = [] for i, (c, e) in enumerate(expr.blocks): if i == 0: - lines.append("if %s:\n" % self._print(c)) + lines.append("if {self._print(c):\n") elif i == len(expr.blocks) - 1 and isinstance(c, LiteralTrue): lines.append("else:\n") else: - lines.append("elif %s:\n" % self._print(c)) + lines.append("elif {self._print(c)}:\n" % ) if isinstance(e, CodeBlock): body = self._indent_codestring(self._print(e)) @@ -813,7 +796,7 @@ def _print_IfTernaryOperator(self, expr): cond = self._print(expr.cond) value_true = self._print(expr.value_true) value_false = self._print(expr.value_false) - return '{true} if {cond} else {false}'.format(cond = cond, true =value_true, false = value_false) + return f'{value_true} if {cond} else {value_false}' def _print_Literal(self, expr): dtype = expr.dtype @@ -832,13 +815,13 @@ def _print_Literal(self, expr): self.insert_new_import( source = 'numpy', target = AsName(cast_func, cast_name)) - return '{}({})'.format(name, repr(expr.python_value)) + return f'{name}({repr(expr.python_value)})' def _print_Print(self, expr): args = [] for f in expr.expr: if isinstance(f, str): - args.append("'{}'".format(f)) + args.append(f"'{f}'") elif isinstance(f, tuple): for i in f: @@ -849,7 +832,7 @@ def _print_Print(self, expr): fs = ', '.join(i for i in args) - return 'print({0})\n'.format(fs) + return f'print({fs})\n' def _print_Module(self, expr): self.set_scope(expr.scope) @@ -888,17 +871,14 @@ def _print_Module(self, expr): prog = '' self.exit_scope() - return ('{imports}\n' - '{body}' - '{prog}').format( - imports = imports, - body = body, - prog = prog) + return (f'{imports}\n' + f'{body}' + f'{prog}') def _print_PyccelPow(self, expr): base = self._print(expr.args[0]) e = self._print(expr.args[1]) - return '{} ** {}'.format(base, e) + return f'{base} ** {e}' def _print_PyccelAdd(self, expr): return ' + '.join(self._print(a) for a in expr.args) @@ -919,13 +899,13 @@ def _print_PyccelFloorDiv(self, expr): return '//'.join(self._print(a) for a in expr.args) def _print_PyccelAssociativeParenthesis(self, expr): - return '({})'.format(self._print(expr.args[0])) + return f'({self._print(expr.args[0])})' def _print_PyccelUnary(self, expr): - return '+{}'.format(self._print(expr.args[0])) + return '+' + self._print(expr.args[0]) def _print_PyccelUnarySub(self, expr): - return '-{}'.format(self._print(expr.args[0])) + return '-' + self._print(expr.args[0]) def _print_PyccelAnd(self, expr): return ' and '.join(self._print(a) for a in expr.args) @@ -936,66 +916,78 @@ def _print_PyccelOr(self, expr): def _print_PyccelEq(self, expr): lhs = self._print(expr.args[0]) rhs = self._print(expr.args[1]) - return '{0} == {1} '.format(lhs, rhs) + return f'{lhs} == {rhs} ' def _print_PyccelNe(self, expr): lhs = self._print(expr.args[0]) rhs = self._print(expr.args[1]) - return '{0} != {1} '.format(lhs, rhs) + return f'{lhs} != {rhs} ' def _print_PyccelLt(self, expr): lhs = self._print(expr.args[0]) rhs = self._print(expr.args[1]) - return '{0} < {1}'.format(lhs, rhs) + return f'{lhs} < {rhs}' def _print_PyccelLe(self, expr): lhs = self._print(expr.args[0]) rhs = self._print(expr.args[1]) - return '{0} <= {1}'.format(lhs, rhs) + return f'{lhs} <= {rhs}' def _print_PyccelGt(self, expr): lhs = self._print(expr.args[0]) rhs = self._print(expr.args[1]) - return '{0} > {1}'.format(lhs, rhs) + return f'{lhs} > {rhs}' def _print_PyccelGe(self, expr): lhs = self._print(expr.args[0]) rhs = self._print(expr.args[1]) - return '{0} >= {1}'.format(lhs, rhs) + return f'{lhs} >= {rhs}' def _print_PyccelNot(self, expr): a = self._print(expr.args[0]) - return 'not {}'.format(a) + return f'not {a}' def _print_PyccelInvert(self, expr): - return '~{}'.format(self._print(expr.args[0])) + return '~' + self._print(expr.args[0]) def _print_PyccelRShift(self, expr): - return '{} >> {}'.format(self._print(expr.args[0]), self._print(expr.args[1])) + lhs = self._print(expr.args[0]) + rhs = self._print(expr.args[1]) + return f'{lhs} >> {rhs}' def _print_PyccelLShift(self, expr): - return '{} << {}'.format(self._print(expr.args[0]), self._print(expr.args[1])) + lhs = self._print(expr.args[0]) + rhs = self._print(expr.args[1]) + return f'{lhs} << {rhs}' def _print_PyccelBitXor(self, expr): - return '{} ^ {}'.format(self._print(expr.args[0]), self._print(expr.args[1])) + lhs = self._print(expr.args[0]) + rhs = self._print(expr.args[1]) + return f'{lhs} ^ {rhs}' def _print_PyccelBitOr(self, expr): - return '{} | {}'.format(self._print(expr.args[0]), self._print(expr.args[1])) + lhs = self._print(expr.args[0]) + rhs = self._print(expr.args[1]) + return f'{lhs} | {rhs}' def _print_PyccelBitAnd(self, expr): - return '{} & {}'.format(self._print(expr.args[0]), self._print(expr.args[1])) + lhs = self._print(expr.args[0]) + rhs = self._print(expr.args[1]) + return f'{lhs} & {rhs}' def _print_Duplicate(self, expr): - return '{} * {}'.format(self._print(expr.val), self._print(expr.length)) + lhs = self._print(expr.args[0]) + rhs = self._print(expr.args[1]) + return f'{lhs} * {rhs}' def _print_Concatenate(self, expr): - return ' + '.join([self._print(a) for a in expr.args]) + return ' + '.join(self._print(a) for a in expr.args) def _print_PyccelSymbol(self, expr): return expr def _print_PythonType(self, expr): - return 'type({})'.format(self._print(expr.arg)) + return f'type({self._print(expr.arg)})' #------------------OmpAnnotatedComment Printer------------------ @@ -1004,15 +996,15 @@ def _print_OmpAnnotatedComment(self, expr): if expr.combined: clauses = ' ' + expr.combined - omp_expr = '#$omp {}'.format(expr.name) + omp_expr = f'#$omp {expr.name}' clauses += str(expr.txt) - omp_expr = '{}{}\n'.format(omp_expr, clauses) + omp_expr = f'{omp_expr}{clauses}\n' return omp_expr def _print_Omp_End_Clause(self, expr): omp_expr = str(expr.txt) - omp_expr = '#$omp {}\n'.format(omp_expr) + omp_expr = f'#$omp {omp_expr}\n' return omp_expr #============================================================================== diff --git a/pyccel/codegen/python_wrapper.py b/pyccel/codegen/python_wrapper.py index 88cb8abbd8..d56fabfa4e 100644 --- a/pyccel/codegen/python_wrapper.py +++ b/pyccel/codegen/python_wrapper.py @@ -102,8 +102,8 @@ def create_shared_library(codegen, if sharedlib_modname is None: sharedlib_modname = module_name - wrapper_filename_root = '{}_wrapper'.format(module_name) - wrapper_filename = '{}.c'.format(wrapper_filename_root) + wrapper_filename_root = f'{module_name}_wrapper' + wrapper_filename = f'{wrapper_filename_root}.c' wrapper_compile_obj = CompileObj(wrapper_filename, pyccel_dirpath, flags = wrapper_flags, @@ -115,7 +115,7 @@ def create_shared_library(codegen, wrapper = FortranToCWrapper() bind_c_mod = wrapper.wrap(codegen.ast) bind_c_code = fcode(bind_c_mod, bind_c_mod.name) - bind_c_filename = '{}.f90'.format(bind_c_mod.name) + bind_c_filename = f'{bind_c_mod.name}.f90' with open(bind_c_filename, 'w') as f: f.writelines(bind_c_code) diff --git a/pyccel/commands/console.py b/pyccel/commands/console.py index 3acbb92ddc..ebfc2ffd80 100644 --- a/pyccel/commands/console.py +++ b/pyccel/commands/console.py @@ -18,7 +18,7 @@ class MyParser(argparse.ArgumentParser): See http://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu """ def error(self, message): - sys.stderr.write('error: %s\n' % message) + sys.stderr.write(f'error: {message}\n') self.print_help() sys.exit(2) @@ -59,8 +59,9 @@ def pyccel(files=None, mpi=None, openmp=None, openacc=None, output_dir=None, com import pyccel version = pyccel.__version__ libpath = pyccel.__path__[0] - python = 'python {}.{}'.format(*sys.version_info) - message = "pyccel {} from {} ({})".format(version, libpath, python) + py_version = '.'.join(sys.version_info) + python = f'python {py_version}' + message = f"pyccel {version} from {libpath} ({python})" parser.add_argument('-V', '--version', action='version', version=message) # ... diff --git a/pyccel/compilers/default_compilers.py b/pyccel/compilers/default_compilers.py index 50ac871e49..42ac77673c 100644 --- a/pyccel/compilers/default_compilers.py +++ b/pyccel/compilers/default_compilers.py @@ -201,7 +201,7 @@ def change_to_lib_flag(lib): end = end-3 if lib.endswith('.dylib'): end = end-5 - return '-l{}'.format(lib[3:end]) + return '-l'+lib[3:end] else: return lib diff --git a/pyccel/epyccel.py b/pyccel/epyccel.py index 491ba28429..c55b7bb747 100644 --- a/pyccel/epyccel.py +++ b/pyccel/epyccel.py @@ -44,7 +44,7 @@ def get_source_function(func): line = a[leading_spaces:] else: line = a - code = '{code}{line}'.format(code=code, line=line) + code = f'{code}{line}' return code @@ -191,7 +191,7 @@ def epyccel_seq(function_or_module, *, # Try is necessary to ensure lock is released try: - pymod_filename = '{}.py'.format(module_name) + pymod_filename = f'{module_name}.py' pymod_filepath = os.path.join(dirpath, pymod_filename) # ... diff --git a/pyccel/errors/errors.py b/pyccel/errors/errors.py index 59affe6548..b25293a523 100644 --- a/pyccel/errors/errors.py +++ b/pyccel/errors/errors.py @@ -123,15 +123,15 @@ def __str__(self): if self.line: if self.column: - info['location'] = ' [{line},{column}]'.format(line=self.line, column=self.column) + info['location'] = f' [{self.line},{self.column}]' else: - info['location'] = ' [{line}]'.format(line=self.line) + info['location'] = f' [{self.line}]' if self.symbol: if self.traceback: - info['symbol'] = ' ({})'.format(repr(self.symbol)) + info['symbol'] = f' ({repr(symbol)})' else: - info['symbol'] = ' ({})'.format(self.symbol) + info['symbol'] = f' ({self.symbol})' return pattern.format(**info) @@ -348,11 +348,11 @@ def check(self): def __str__(self): print_path = (len(self.error_info_map.keys()) > 1) - text = '{}:\n'.format(PYCCEL) + text = f'{PYCCEL}:\n' for path in self.error_info_map.keys(): errors = self.error_info_map[path] - if print_path: text += ' filename :: {path}\n'.format(path=path) + if print_path: text += f' filename :: {path}\n' for err in errors: text += ' ' + str(err) + '\n' diff --git a/pyccel/naming/fortrannameclashchecker.py b/pyccel/naming/fortrannameclashchecker.py index 62a518e5d0..724df71d78 100644 --- a/pyccel/naming/fortrannameclashchecker.py +++ b/pyccel/naming/fortrannameclashchecker.py @@ -81,5 +81,5 @@ def get_collisionless_name(self, name, symbols): name = 'private'+name name = self._get_collisionless_name(name, symbols) if len(name) > 96: - warnings.warn("Name {} is too long for Fortran. This may cause compiler errors".format(name)) + warnings.warn(f"Name {name} is too long for Fortran. This may cause compiler errors") return name diff --git a/pyccel/parser/base.py b/pyccel/parser/base.py index c55deeab95..9518224a32 100644 --- a/pyccel/parser/base.py +++ b/pyccel/parser/base.py @@ -69,8 +69,8 @@ def get_filename_from_import(module,input_folder=''): while filename.startswith('/'): filename = folder_above + filename[1:] - filename_pyh = '{}.pyh'.format(filename) - filename_py = '{}.py'.format(filename) + filename_pyh = f'{filename}.pyh' + filename_py = f'{filename}.py' folders = input_folder.split(""".""") for i in range(len(folders)): poss_dirname = os.path.join( *folders[:i+1] ) @@ -88,8 +88,8 @@ def get_filename_from_import(module,input_folder=''): source = """.""".join(i for i in module.split(""".""")[:-1]) _module = module.split(""".""")[-1] - filename_pyh = '{}.pyh'.format(_module) - filename_py = '{}.py'.format(_module) + filename_pyh = f'{_module}.pyh' + filename_py = f'{_module}.py' try: package = importlib.import_module(source) @@ -405,7 +405,7 @@ def dump(self, filename=None): if ext != '.pyh': return - name = '{}.pyccel'.format(name) + name = f'{name}.pyccel' filename = os.path.join(path, name) # check extension @@ -455,7 +455,7 @@ def load(self, filename=None): if ext != '.pyh': return - name = '{}.pyccel'.format(name) + name = f'{name}.pyccel' filename = os.path.join(path, name) if not filename.split(""".""")[-1] == 'pyccel': diff --git a/pyccel/parser/parser.py b/pyccel/parser/parser.py index 5f5b85a1ca..b07c622353 100644 --- a/pyccel/parser/parser.py +++ b/pyccel/parser/parser.py @@ -207,7 +207,7 @@ def parse_sons(self, d_parsers_by_filename, verbose=False): not_treated = [i for i in source_to_filename.values() if i not in treated] for filename in not_treated: if verbose: - print ('>>> treating :: {}'.format(filename)) + print ('>>> treating :: ', filename) # get the absolute path corresponding to source if filename in d_parsers_by_filename: @@ -237,7 +237,7 @@ def _annotate_sons(self, **settings): for p in self.sons: if not p.sons: if verbose: - print ('>>> treating :: {}'.format(p.filename)) + print ('>>> treating :: ', p.filename) p.annotate(**settings) # finally we treat the remaining sons recursively @@ -245,7 +245,7 @@ def _annotate_sons(self, **settings): for p in self.sons: if p.sons: if verbose: - print ('>>> treating :: {}'.format(p.filename)) + print ('>>> treating :: ', p.filename) p.annotate(**settings) #============================================================================== diff --git a/pyccel/parser/scope.py b/pyccel/parser/scope.py index 74d79df50d..f97a960682 100644 --- a/pyccel/parser/scope.py +++ b/pyccel/parser/scope.py @@ -123,7 +123,7 @@ def new_child_scope(self, name, **kwargs): """ ps = kwargs.pop('parent_scope', self) if ps is not self: - raise ValueError("A child of {} cannot have a parent {}".format(self, ps)) + raise ValueError(f"A child of {self} cannot have a parent {ps}") child = Scope(**kwargs, parent_scope = self) @@ -293,7 +293,7 @@ def insert_variable(self, var, name = None): self.parent_scope.insert_variable(var, name) else: if name in self._locals['variables']: - raise RuntimeError('New variable {} already exists in scope'.format(name)) + raise RuntimeError(f'New variable {name} already exists in scope') if name == '_': self._temporary_variables.append(var) else: @@ -528,7 +528,7 @@ def get_expected_name(self, start_name): elif self.parent_scope: return self.parent_scope.get_expected_name(start_name) else: - raise RuntimeError("{} does not exist in scope".format(start_name)) + raise RuntimeError(f"{start_name} does not exist in scope") def create_product_loop_scope(self, inner_scope, n_loops): """ Create a n_loops loop scopes such that the innermost loop @@ -608,7 +608,7 @@ def get_python_name(self, name): elif self.parent_scope: return self.parent_scope.get_python_name(name) else: - raise RuntimeError("Can't find {} in scope".format(name)) + raise RuntimeError(f"Can't find {name} in scope") @property def python_names(self): diff --git a/pyccel/parser/syntactic.py b/pyccel/parser/syntactic.py index d24fcfa667..c98b851d95 100644 --- a/pyccel/parser/syntactic.py +++ b/pyccel/parser/syntactic.py @@ -303,7 +303,7 @@ def _visit_Num(self, stmt): elif isinstance(val, complex): return LiteralComplex(val.real, val.imag) else: - raise NotImplementedError('Num type {} not recognised'.format(type(val))) + raise NotImplementedError(f'Num type {type(val)} not recognised') def _visit_Assign(self, stmt): @@ -398,7 +398,7 @@ def _visit_Constant(self, stmt): return self._visit_Str(stmt) else: - raise NotImplementedError('Constant type {} not recognised'.format(type(stmt.value))) + raise NotImplementedError(f'Constant type {type(stmt.value)} not recognised') def _visit_NameConstant(self, stmt): if stmt.value is None: @@ -411,7 +411,7 @@ def _visit_NameConstant(self, stmt): return LiteralFalse() else: - raise NotImplementedError("Unknown NameConstant : {}".format(stmt.value)) + raise NotImplementedError(f"Unknown NameConstant : {stmt.value}") def _visit_Name(self, stmt): @@ -633,7 +633,7 @@ def fill_types(ls): arg = arg.strip("'").strip('"') container.append(arg) else: - msg = 'Invalid argument of type {} passed to types decorator'.format(type(arg)) + msg = f'Invalid argument of type {type(arg)} passed to types decorator' errors.report(msg, bounding_box = (stmt.lineno, stmt.col_offset), severity='error') @@ -710,7 +710,7 @@ def fill_types(ls): txt = '#$ header template ' + tp_name txt += '(' + '|'.join(types) + ')' if tp_name in template['template_dict']: - msg = 'The template "{}" is duplicated'.format(tp_name) + msg = f'The template "{tp_name}" is duplicated' errors.report(msg, bounding_box = (stmt.lineno, stmt.col_offset), severity='warning') @@ -733,7 +733,7 @@ def fill_types(ls): if len(ls) > 0 and ls[-1].has_keyword: arg_name = ls[-1].keyword if not arg_name == 'results': - msg = 'Argument "{}" provided to the types decorator is not valid'.format(arg_name) + msg = f'Argument "{arg_name}" provided to the types decorator is not valid' errors.report(msg, symbol = comb_types, bounding_box = (stmt.lineno, stmt.col_offset), @@ -922,7 +922,7 @@ def _visit_Call(self, stmt): func_attr = FunctionCall(func.name[-1], args) func = DottedName(*func.name[:-1], func_attr) else: - raise NotImplementedError(' Unknown function type {}'.format(str(type(func)))) + raise NotImplementedError(f' Unknown function type {type(func)}') return func