Skip to content

Commit 74f82be

Browse files
author
Release Manager
committed
gh-36890: pep8 cleanup for gap interface full pep8 cleanup for the gap interface ### 📝 Checklist - [x] The title is concise, informative, and self-explanatory. - [x] The description explains in detail what this PR is about. URL: #36890 Reported by: Frédéric Chapoton Reviewer(s): David Coudert
2 parents 7ef39dd + e026eaf commit 74f82be

File tree

1 file changed

+70
-67
lines changed

1 file changed

+70
-67
lines changed

src/sage/interfaces/gap.py

Lines changed: 70 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@
177177
gap(...), x.[tab], and docs, e.g., gap.function? and x.function?
178178
"""
179179

180-
#*****************************************************************************
180+
# ****************************************************************************
181181
# Copyright (C) 2005 William Stein <[email protected]>
182182
#
183183
# Distributed under the terms of the GNU General Public License (GPL)
@@ -189,8 +189,8 @@
189189
#
190190
# The full text of the GPL is available at:
191191
#
192-
# http://www.gnu.org/licenses/
193-
#*****************************************************************************
192+
# https://www.gnu.org/licenses/
193+
# ****************************************************************************
194194

195195
from .expect import Expect, ExpectElement, FunctionElement, ExpectFunction
196196
from .gap_workspace import gap_workspace_file, prepare_workspace_dir
@@ -244,7 +244,7 @@ def gap_command(use_workspace_cache=True, local=True):
244244
return gap_cmd, True
245245

246246

247-
############ Classes with methods for both the GAP3 and GAP4 interface
247+
# ########### Classes with methods for both the GAP3 and GAP4 interface
248248

249249
class Gap_generic(ExtraTabCompletion, Expect):
250250
r"""
@@ -287,10 +287,10 @@ def _synchronize(self, timeout=0.5, cmd='%s;'):
287287
E = self._expect
288288
from sage.misc.prandom import randrange
289289
rnd = randrange(2147483647)
290-
cmd = str(rnd)+';'
290+
cmd = str(rnd) + ';'
291291
try:
292292
E.sendline(cmd)
293-
E.expect(r'@[nf][@J\s>]*'+str(rnd), timeout=timeout)
293+
E.expect(r'@[nf][@J\s>]*' + str(rnd), timeout=timeout)
294294
E.send(' ')
295295
E.expect('@i', timeout=timeout)
296296
except pexpect.TIMEOUT:
@@ -453,7 +453,7 @@ def load_package(self, pkg, verbose=False):
453453
print("Loading GAP package {}".format(pkg))
454454
x = self.eval('LoadPackage("{}")'.format(pkg))
455455
if x == 'fail':
456-
raise RuntimeError("Error loading Gap package "+str(pkg)+". " +
456+
raise RuntimeError("Error loading Gap package " + str(pkg) + ". " +
457457
"You may want to install gap_packages SPKG.")
458458

459459
def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
@@ -507,10 +507,10 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
507507
' -\n\\\\-'
508508
"""
509509
# '"
510-
#We remove all of the comments: On each line, we try
511-
#to find a pound sign. If we find it, we check to see if
512-
#it is occurring in a string. If it is not in a string, we
513-
#strip off the comment.
510+
# We remove all of the comments: On each line, we try
511+
# to find a pound sign. If we find it, we check to see if
512+
# it is occurring in a string. If it is not in a string, we
513+
# strip off the comment.
514514
if not split_lines:
515515
input_line = str(x)
516516
else:
@@ -520,17 +520,17 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
520520
while pound_position != -1:
521521
if not is_in_string(line, pound_position):
522522
line = line[:pound_position]
523-
pound_position = line.find('#',pound_position+1)
524-
input_line += " "+line
523+
pound_position = line.find('#', pound_position + 1)
524+
input_line += " " + line
525525
if not input_line.endswith(';'):
526526
input_line += ';'
527527
result = Expect.eval(self, input_line, **kwds)
528528
if not newlines:
529-
result = result.replace("\\\n","")
529+
result = result.replace("\\\n", "")
530530
return result.rstrip()
531531

532532
def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
533-
if self._expect is None: # interface is down
533+
if self._expect is None: # interface is down
534534
self._start()
535535
E = self._expect
536536
try:
@@ -540,9 +540,9 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
540540
except OSError:
541541
raise RuntimeError("Error evaluating %s in %s" % (line, self))
542542
if not wait_for_prompt:
543-
return (b'',b'')
543+
return (b'', b'')
544544
if len(line) == 0:
545-
return (b'',b'')
545+
return (b'', b'')
546546
try:
547547
terminal_echo = [] # to be discarded
548548
normal_outputs = [] # GAP stdout
@@ -556,43 +556,43 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False):
556556
warnings.warn(
557557
"possibly wrong version of GAP package "
558558
"interface. Crossing fingers and continuing.")
559-
elif x == 1: #@@
559+
elif x == 1: # @@
560560
current_outputs.append(b'@')
561-
elif x == 2: #special char
561+
elif x == 2: # special char
562562
c = ord(E.after[1:2]) - ord(b'A') + 1
563563
s = bytes([c])
564564
current_outputs.append(s)
565-
elif x == 3: # garbage collection info, ignore
565+
elif x == 3: # garbage collection info, ignore
566566
pass
567-
elif x == 4: # @e -- break loop
567+
elif x == 4: # @e -- break loop
568568
E.sendline("quit;")
569-
elif x == 5: # @c completion, doesn't seem to happen when -p is in use
569+
elif x == 5: # @c completion, doesn't seem to happen when -p is in use
570570
warnings.warn("I didn't think GAP could do this")
571-
elif x == 6: # @f GAP error message
571+
elif x == 6: # @f GAP error message
572572
current_outputs = error_outputs
573-
elif x == 7: # @h help text, but this stopped happening with new help
573+
elif x == 7: # @h help text, but this stopped happening with new help
574574
warnings.warn("I didn't think GAP could do this")
575-
elif x == 8: # @i awaiting normal input
575+
elif x == 8: # @i awaiting normal input
576576
break
577-
elif x == 9: # @m finished running a child
577+
elif x == 9: # @m finished running a child
578578
pass # there is no need to do anything
579-
elif x == 10: #@n normal output line
579+
elif x == 10: # @n normal output line
580580
current_outputs = normal_outputs
581-
elif x == 11: #@r echoing input
581+
elif x == 11: # @r echoing input
582582
current_outputs = terminal_echo
583-
elif x == 12: #@sN shouldn't happen
583+
elif x == 12: # @sN shouldn't happen
584584
warnings.warn("this should never happen")
585-
elif x == 13: #@w GAP is trying to send a Window command
585+
elif x == 13: # @w GAP is trying to send a Window command
586586
warnings.warn("this should never happen")
587-
elif x == 14: #@x seems to be safely ignorable
587+
elif x == 14: # @x seems to be safely ignorable
588588
pass
589-
elif x == 15:#@z GAP starting a subprocess
589+
elif x == 15: # @z GAP starting a subprocess
590590
pass # there is no need to do anything
591591
except pexpect.EOF:
592592
if not expect_eof:
593-
raise RuntimeError("Unexpected EOF from %s executing %s" % (self,line))
593+
raise RuntimeError("Unexpected EOF from %s executing %s" % (self, line))
594594
except IOError:
595-
raise RuntimeError("IO Error from %s executing %s" % (self,line))
595+
raise RuntimeError("IO Error from %s executing %s" % (self, line))
596596
return (b"".join(normal_outputs), b"".join(error_outputs))
597597

598598
def _keyboard_interrupt(self):
@@ -697,8 +697,8 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if
697697
error += "\nRunning gap_reset_workspace()..."
698698
self.quit()
699699
gap_reset_workspace()
700-
error = error.replace('\r','')
701-
raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error,line))
700+
error = error.replace('\r', '')
701+
raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error, line))
702702
if not normal:
703703
return ''
704704

@@ -772,7 +772,7 @@ def _contains(self, v1, v2):
772772
sage: 2 in gap('Integers')
773773
True
774774
"""
775-
return self.eval('%s in %s' % (v1,v2)) == "true"
775+
return self.eval('%s in %s' % (v1, v2)) == "true"
776776

777777
def _true_symbol(self):
778778
"""
@@ -868,20 +868,21 @@ def function_call(self, function, args=None, kwds=None):
868868
args, kwds = self._convert_args_kwds(args, kwds)
869869
self._check_valid_function_name(function)
870870

871-
#Here we have to do some magic because not all GAP
872-
#functions return a value. If you try to store their
873-
#results to a variable, then GAP will complain. Thus, before
874-
#we evaluate the function, we make it so that the marker string
875-
#is in the 'last' variable in GAP. If the function returns a
876-
#value, then that value will be in 'last', otherwise it will
877-
#be the marker.
871+
# Here we have to do some magic because not all GAP
872+
# functions return a value. If you try to store their
873+
# results to a variable, then GAP will complain. Thus, before
874+
# we evaluate the function, we make it so that the marker string
875+
# is in the 'last' variable in GAP. If the function returns a
876+
# value, then that value will be in 'last', otherwise it will
877+
# be the marker.
878878
marker = '__SAGE_LAST__:="__SAGE_LAST__";;'
879879
cmd = "%s(%s);;" % (function, ",".join([s.name() for s in args] +
880-
['%s=%s' % (key,value.name()) for key, value in kwds.items()]))
880+
[f'{key}={value.name()}'
881+
for key, value in kwds.items()]))
881882
if len(marker) + len(cmd) <= self._eval_using_file_cutoff:
882883
# We combine the two commands so we only run eval() once and the
883884
# only output would be from the second command
884-
res = self.eval(marker+cmd)
885+
res = self.eval(marker + cmd)
885886
else:
886887
self.eval(marker)
887888
res = self.eval(cmd)
@@ -1045,7 +1046,8 @@ def _matrix_(self, R):
10451046

10461047
from sage.matrix.matrix_space import MatrixSpace
10471048
M = MatrixSpace(R, n, m)
1048-
entries = [[R(self[r,c]) for c in range(1,m+1)] for r in range(1,n+1)]
1049+
entries = [[R(self[r, c]) for c in range(1, m + 1)]
1050+
for r in range(1, n + 1)]
10491051
return M(entries)
10501052

10511053

@@ -1099,7 +1101,7 @@ def __init__(self, max_workspace_size=None,
10991101
self.__seq = 0
11001102
self._seed = seed
11011103

1102-
def set_seed(self,seed=None):
1104+
def set_seed(self, seed=None):
11031105
"""
11041106
Set the seed for gap interpreter.
11051107
@@ -1204,8 +1206,8 @@ def _start(self):
12041206
self.save_workspace()
12051207
# Now, as self._expect exists, we can compile some useful pattern:
12061208
self._compiled_full_pattern = self._expect.compile_pattern_list([
1207-
r'@p\d+\.','@@','@[A-Z]',r'@[123456!"#$%&][^+]*\+',
1208-
'@e','@c','@f','@h','@i','@m','@n','@r',r'@s\d',r'@w.*\+','@x','@z'])
1209+
r'@p\d+\.', '@@', '@[A-Z]', r'@[123456!"#$%&][^+]*\+',
1210+
'@e', '@c', '@f', '@h', '@i', '@m', '@n', '@r', r'@s\d', r'@w.*\+', '@x', '@z'])
12091211
# read everything up to the first "ready" prompt
12101212
self._expect.expect("@i")
12111213

@@ -1246,10 +1248,9 @@ def cputime(self, t=None):
12461248
"""
12471249
if t is not None:
12481250
return self.cputime() - t
1249-
else:
1250-
self.eval('_r_ := Runtimes();')
1251-
r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]')))
1252-
return r/1000.0
1251+
self.eval('_r_ := Runtimes();')
1252+
r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]')))
1253+
return r / 1000.0
12531254

12541255
def save_workspace(self):
12551256
r"""
@@ -1349,7 +1350,7 @@ def set(self, var, value):
13491350
sage: gap.get('x')
13501351
'2'
13511352
"""
1352-
cmd = ('%s:=%s;;' % (var, value)).replace('\n','')
1353+
cmd = ('%s:=%s;;' % (var, value)).replace('\n', '')
13531354
self._eval_line(cmd, allow_use_file=True)
13541355

13551356
def get(self, var, use_file=False):
@@ -1366,10 +1367,10 @@ def get(self, var, use_file=False):
13661367
tmp = self._local_tmpfile()
13671368
if os.path.exists(tmp):
13681369
os.unlink(tmp)
1369-
self.eval('PrintTo("%s", %s);' % (tmp,var), strip=False)
1370+
self.eval('PrintTo("%s", %s);' % (tmp, var), strip=False)
13701371
with open(tmp) as f:
13711372
r = f.read()
1372-
r = r.strip().replace("\\\n","")
1373+
r = r.strip().replace("\\\n", "")
13731374
os.unlink(tmp)
13741375
return r
13751376
else:
@@ -1480,7 +1481,7 @@ def _tab_completion(self):
14801481
True
14811482
"""
14821483
names = eval(self.eval('NamesSystemGVars()')) + \
1483-
eval(self.eval('NamesUserGVars()'))
1484+
eval(self.eval('NamesUserGVars()'))
14841485
return [n for n in names if n[0] in string.ascii_letters]
14851486

14861487

@@ -1582,16 +1583,16 @@ def _latex_(self):
15821583
P = self._check_valid()
15831584
try:
15841585
s = P.eval('LaTeXObj(%s)' % self.name())
1585-
s = s.replace('\\\\','\\').replace('"','')
1586-
s = s.replace('%\\n',' ')
1586+
s = s.replace('\\\\', '\\').replace('"', '')
1587+
s = s.replace('%\\n', ' ')
15871588
return s
15881589
except RuntimeError:
15891590
return str(self)
15901591

15911592
@cached_method
15921593
def _tab_completion(self):
15931594
"""
1594-
Return additional tab completion entries
1595+
Return additional tab completion entries.
15951596
15961597
OUTPUT:
15971598
@@ -1605,10 +1606,11 @@ def _tab_completion(self):
16051606
"""
16061607
P = self.parent()
16071608
v = P.eval(r'\$SAGE.OperationsAdmittingFirstArgument(%s)' % self.name())
1608-
v = v.replace('Tester(','').replace('Setter(','').replace(')','').replace('\n', '')
1609+
v = v.replace('Tester(', '').replace('Setter(', '').replace(')', '').replace('\n', '')
16091610
v = v.split(',')
1610-
v = [ oper.split('"')[1] for oper in v ]
1611-
v = [ oper for oper in v if all(ch in string.ascii_letters for ch in oper) ]
1611+
v = (oper.split('"')[1] for oper in v)
1612+
v = [oper for oper in v
1613+
if all(ch in string.ascii_letters for ch in oper)]
16121614
return sorted(set(v))
16131615

16141616

@@ -1718,13 +1720,13 @@ def gfq_gap_to_sage(x, F):
17181720
return F(0)
17191721
i1 = s.index("(")
17201722
i2 = s.index(")")
1721-
q = eval(s[i1+1:i2].replace('^','**'))
1723+
q = eval(s[i1 + 1:i2].replace('^', '**'))
17221724
if not F.cardinality().is_power_of(q):
17231725
raise ValueError('%r has no subfield of size %r' % (F, q))
17241726
if s.find(')^') == -1:
17251727
e = 1
17261728
else:
1727-
e = int(s[i2+2:])
1729+
e = int(s[i2 + 2:])
17281730
if F.degree() == 1:
17291731
g = F(gap.eval('Int(Z(%s))' % q))
17301732
elif F.is_conway():
@@ -1734,6 +1736,7 @@ def gfq_gap_to_sage(x, F):
17341736
raise ValueError('%r is not prime or defined by a Conway polynomial' % F)
17351737
return g**e
17361738

1739+
17371740
def intmod_gap_to_sage(x):
17381741
r"""
17391742
INPUT:
@@ -1837,5 +1840,5 @@ def gap_console():
18371840
if not get_display_manager().is_in_terminal():
18381841
raise RuntimeError('Can use the console only in the terminal. Try %%gap magics instead.')
18391842
cmd, _ = gap_command(use_workspace_cache=False)
1840-
cmd += ' ' + os.path.join(SAGE_EXTCODE,'gap','console.g')
1843+
cmd += ' ' + os.path.join(SAGE_EXTCODE, 'gap', 'console.g')
18411844
os.system(cmd)

0 commit comments

Comments
 (0)