From e026eafdcad640be9e44185ae9f238c9a2d411a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Fri, 15 Dec 2023 13:50:59 +0100 Subject: [PATCH] pep8 cleanup for gap interface --- src/sage/interfaces/gap.py | 137 +++++++++++++++++++------------------ 1 file changed, 70 insertions(+), 67 deletions(-) diff --git a/src/sage/interfaces/gap.py b/src/sage/interfaces/gap.py index 0a8087a20d5..b3d3fcae855 100644 --- a/src/sage/interfaces/gap.py +++ b/src/sage/interfaces/gap.py @@ -177,7 +177,7 @@ gap(...), x.[tab], and docs, e.g., gap.function? and x.function? """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2005 William Stein # # Distributed under the terms of the GNU General Public License (GPL) @@ -189,8 +189,8 @@ # # The full text of the GPL is available at: # -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from .expect import Expect, ExpectElement, FunctionElement, ExpectFunction from .gap_workspace import gap_workspace_file, prepare_workspace_dir @@ -234,7 +234,7 @@ def gap_command(use_workspace_cache=True, local=True): return gap_cmd, True -############ Classes with methods for both the GAP3 and GAP4 interface +# ########### Classes with methods for both the GAP3 and GAP4 interface class Gap_generic(ExtraTabCompletion, Expect): r""" @@ -277,10 +277,10 @@ def _synchronize(self, timeout=0.5, cmd='%s;'): E = self._expect from sage.misc.prandom import randrange rnd = randrange(2147483647) - cmd = str(rnd)+';' + cmd = str(rnd) + ';' try: E.sendline(cmd) - E.expect(r'@[nf][@J\s>]*'+str(rnd), timeout=timeout) + E.expect(r'@[nf][@J\s>]*' + str(rnd), timeout=timeout) E.send(' ') E.expect('@i', timeout=timeout) except pexpect.TIMEOUT: @@ -443,7 +443,7 @@ def load_package(self, pkg, verbose=False): print("Loading GAP package {}".format(pkg)) x = self.eval('LoadPackage("{}")'.format(pkg)) if x == 'fail': - raise RuntimeError("Error loading Gap package "+str(pkg)+". " + + raise RuntimeError("Error loading Gap package " + str(pkg) + ". " + "You may want to install gap_packages SPKG.") def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds): @@ -497,10 +497,10 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds): ' -\n\\\\-' """ # '" - #We remove all of the comments: On each line, we try - #to find a pound sign. If we find it, we check to see if - #it is occurring in a string. If it is not in a string, we - #strip off the comment. + # We remove all of the comments: On each line, we try + # to find a pound sign. If we find it, we check to see if + # it is occurring in a string. If it is not in a string, we + # strip off the comment. if not split_lines: input_line = str(x) else: @@ -510,17 +510,17 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds): while pound_position != -1: if not is_in_string(line, pound_position): line = line[:pound_position] - pound_position = line.find('#',pound_position+1) - input_line += " "+line + pound_position = line.find('#', pound_position + 1) + input_line += " " + line if not input_line.endswith(';'): input_line += ';' result = Expect.eval(self, input_line, **kwds) if not newlines: - result = result.replace("\\\n","") + result = result.replace("\\\n", "") return result.rstrip() def _execute_line(self, line, wait_for_prompt=True, expect_eof=False): - if self._expect is None: # interface is down + if self._expect is None: # interface is down self._start() E = self._expect try: @@ -530,9 +530,9 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False): except OSError: raise RuntimeError("Error evaluating %s in %s" % (line, self)) if not wait_for_prompt: - return (b'',b'') + return (b'', b'') if len(line) == 0: - return (b'',b'') + return (b'', b'') try: terminal_echo = [] # to be discarded normal_outputs = [] # GAP stdout @@ -546,43 +546,43 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False): warnings.warn( "possibly wrong version of GAP package " "interface. Crossing fingers and continuing.") - elif x == 1: #@@ + elif x == 1: # @@ current_outputs.append(b'@') - elif x == 2: #special char + elif x == 2: # special char c = ord(E.after[1:2]) - ord(b'A') + 1 s = bytes([c]) current_outputs.append(s) - elif x == 3: # garbage collection info, ignore + elif x == 3: # garbage collection info, ignore pass - elif x == 4: # @e -- break loop + elif x == 4: # @e -- break loop E.sendline("quit;") - elif x == 5: # @c completion, doesn't seem to happen when -p is in use + elif x == 5: # @c completion, doesn't seem to happen when -p is in use warnings.warn("I didn't think GAP could do this") - elif x == 6: # @f GAP error message + elif x == 6: # @f GAP error message current_outputs = error_outputs - elif x == 7: # @h help text, but this stopped happening with new help + elif x == 7: # @h help text, but this stopped happening with new help warnings.warn("I didn't think GAP could do this") - elif x == 8: # @i awaiting normal input + elif x == 8: # @i awaiting normal input break - elif x == 9: # @m finished running a child + elif x == 9: # @m finished running a child pass # there is no need to do anything - elif x == 10: #@n normal output line + elif x == 10: # @n normal output line current_outputs = normal_outputs - elif x == 11: #@r echoing input + elif x == 11: # @r echoing input current_outputs = terminal_echo - elif x == 12: #@sN shouldn't happen + elif x == 12: # @sN shouldn't happen warnings.warn("this should never happen") - elif x == 13: #@w GAP is trying to send a Window command + elif x == 13: # @w GAP is trying to send a Window command warnings.warn("this should never happen") - elif x == 14: #@x seems to be safely ignorable + elif x == 14: # @x seems to be safely ignorable pass - elif x == 15:#@z GAP starting a subprocess + elif x == 15: # @z GAP starting a subprocess pass # there is no need to do anything except pexpect.EOF: if not expect_eof: - raise RuntimeError("Unexpected EOF from %s executing %s" % (self,line)) + raise RuntimeError("Unexpected EOF from %s executing %s" % (self, line)) except IOError: - raise RuntimeError("IO Error from %s executing %s" % (self,line)) + raise RuntimeError("IO Error from %s executing %s" % (self, line)) return (b"".join(normal_outputs), b"".join(error_outputs)) def _keyboard_interrupt(self): @@ -687,8 +687,8 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if error += "\nRunning gap_reset_workspace()..." self.quit() gap_reset_workspace() - error = error.replace('\r','') - raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error,line)) + error = error.replace('\r', '') + raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error, line)) if not normal: return '' @@ -762,7 +762,7 @@ def _contains(self, v1, v2): sage: 2 in gap('Integers') True """ - return self.eval('%s in %s' % (v1,v2)) == "true" + return self.eval('%s in %s' % (v1, v2)) == "true" def _true_symbol(self): """ @@ -858,20 +858,21 @@ def function_call(self, function, args=None, kwds=None): args, kwds = self._convert_args_kwds(args, kwds) self._check_valid_function_name(function) - #Here we have to do some magic because not all GAP - #functions return a value. If you try to store their - #results to a variable, then GAP will complain. Thus, before - #we evaluate the function, we make it so that the marker string - #is in the 'last' variable in GAP. If the function returns a - #value, then that value will be in 'last', otherwise it will - #be the marker. + # Here we have to do some magic because not all GAP + # functions return a value. If you try to store their + # results to a variable, then GAP will complain. Thus, before + # we evaluate the function, we make it so that the marker string + # is in the 'last' variable in GAP. If the function returns a + # value, then that value will be in 'last', otherwise it will + # be the marker. marker = '__SAGE_LAST__:="__SAGE_LAST__";;' cmd = "%s(%s);;" % (function, ",".join([s.name() for s in args] + - ['%s=%s' % (key,value.name()) for key, value in kwds.items()])) + [f'{key}={value.name()}' + for key, value in kwds.items()])) if len(marker) + len(cmd) <= self._eval_using_file_cutoff: # We combine the two commands so we only run eval() once and the # only output would be from the second command - res = self.eval(marker+cmd) + res = self.eval(marker + cmd) else: self.eval(marker) res = self.eval(cmd) @@ -1035,7 +1036,8 @@ def _matrix_(self, R): from sage.matrix.matrix_space import MatrixSpace M = MatrixSpace(R, n, m) - entries = [[R(self[r,c]) for c in range(1,m+1)] for r in range(1,n+1)] + entries = [[R(self[r, c]) for c in range(1, m + 1)] + for r in range(1, n + 1)] return M(entries) @@ -1089,7 +1091,7 @@ def __init__(self, max_workspace_size=None, self.__seq = 0 self._seed = seed - def set_seed(self,seed=None): + def set_seed(self, seed=None): """ Set the seed for gap interpreter. @@ -1194,8 +1196,8 @@ def _start(self): self.save_workspace() # Now, as self._expect exists, we can compile some useful pattern: self._compiled_full_pattern = self._expect.compile_pattern_list([ - r'@p\d+\.','@@','@[A-Z]',r'@[123456!"#$%&][^+]*\+', - '@e','@c','@f','@h','@i','@m','@n','@r',r'@s\d',r'@w.*\+','@x','@z']) + r'@p\d+\.', '@@', '@[A-Z]', r'@[123456!"#$%&][^+]*\+', + '@e', '@c', '@f', '@h', '@i', '@m', '@n', '@r', r'@s\d', r'@w.*\+', '@x', '@z']) # read everything up to the first "ready" prompt self._expect.expect("@i") @@ -1236,10 +1238,9 @@ def cputime(self, t=None): """ if t is not None: return self.cputime() - t - else: - self.eval('_r_ := Runtimes();') - r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]'))) - return r/1000.0 + self.eval('_r_ := Runtimes();') + r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]'))) + return r / 1000.0 def save_workspace(self): r""" @@ -1339,7 +1340,7 @@ def set(self, var, value): sage: gap.get('x') '2' """ - cmd = ('%s:=%s;;' % (var, value)).replace('\n','') + cmd = ('%s:=%s;;' % (var, value)).replace('\n', '') self._eval_line(cmd, allow_use_file=True) def get(self, var, use_file=False): @@ -1356,10 +1357,10 @@ def get(self, var, use_file=False): tmp = self._local_tmpfile() if os.path.exists(tmp): os.unlink(tmp) - self.eval('PrintTo("%s", %s);' % (tmp,var), strip=False) + self.eval('PrintTo("%s", %s);' % (tmp, var), strip=False) with open(tmp) as f: r = f.read() - r = r.strip().replace("\\\n","") + r = r.strip().replace("\\\n", "") os.unlink(tmp) return r else: @@ -1470,7 +1471,7 @@ def _tab_completion(self): True """ names = eval(self.eval('NamesSystemGVars()')) + \ - eval(self.eval('NamesUserGVars()')) + eval(self.eval('NamesUserGVars()')) return [n for n in names if n[0] in string.ascii_letters] @@ -1572,8 +1573,8 @@ def _latex_(self): P = self._check_valid() try: s = P.eval('LaTeXObj(%s)' % self.name()) - s = s.replace('\\\\','\\').replace('"','') - s = s.replace('%\\n',' ') + s = s.replace('\\\\', '\\').replace('"', '') + s = s.replace('%\\n', ' ') return s except RuntimeError: return str(self) @@ -1581,7 +1582,7 @@ def _latex_(self): @cached_method def _tab_completion(self): """ - Return additional tab completion entries + Return additional tab completion entries. OUTPUT: @@ -1595,10 +1596,11 @@ def _tab_completion(self): """ P = self.parent() v = P.eval(r'\$SAGE.OperationsAdmittingFirstArgument(%s)' % self.name()) - v = v.replace('Tester(','').replace('Setter(','').replace(')','').replace('\n', '') + v = v.replace('Tester(', '').replace('Setter(', '').replace(')', '').replace('\n', '') v = v.split(',') - v = [ oper.split('"')[1] for oper in v ] - v = [ oper for oper in v if all(ch in string.ascii_letters for ch in oper) ] + v = (oper.split('"')[1] for oper in v) + v = [oper for oper in v + if all(ch in string.ascii_letters for ch in oper)] return sorted(set(v)) @@ -1708,13 +1710,13 @@ def gfq_gap_to_sage(x, F): return F(0) i1 = s.index("(") i2 = s.index(")") - q = eval(s[i1+1:i2].replace('^','**')) + q = eval(s[i1 + 1:i2].replace('^', '**')) if not F.cardinality().is_power_of(q): raise ValueError('%r has no subfield of size %r' % (F, q)) if s.find(')^') == -1: e = 1 else: - e = int(s[i2+2:]) + e = int(s[i2 + 2:]) if F.degree() == 1: g = F(gap.eval('Int(Z(%s))' % q)) elif F.is_conway(): @@ -1724,6 +1726,7 @@ def gfq_gap_to_sage(x, F): raise ValueError('%r is not prime or defined by a Conway polynomial' % F) return g**e + def intmod_gap_to_sage(x): r""" INPUT: @@ -1827,5 +1830,5 @@ def gap_console(): if not get_display_manager().is_in_terminal(): raise RuntimeError('Can use the console only in the terminal. Try %%gap magics instead.') cmd, _ = gap_command(use_workspace_cache=False) - cmd += ' ' + os.path.join(SAGE_EXTCODE,'gap','console.g') + cmd += ' ' + os.path.join(SAGE_EXTCODE, 'gap', 'console.g') os.system(cmd)