Skip to content

Commit e026eaf

Browse files
committed
pep8 cleanup for gap interface
1 parent e2e0f8d commit e026eaf

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
@@ -234,7 +234,7 @@ def gap_command(use_workspace_cache=True, local=True):
234234
return gap_cmd, True
235235

236236

237-
############ Classes with methods for both the GAP3 and GAP4 interface
237+
# ########### Classes with methods for both the GAP3 and GAP4 interface
238238

239239
class Gap_generic(ExtraTabCompletion, Expect):
240240
r"""
@@ -277,10 +277,10 @@ def _synchronize(self, timeout=0.5, cmd='%s;'):
277277
E = self._expect
278278
from sage.misc.prandom import randrange
279279
rnd = randrange(2147483647)
280-
cmd = str(rnd)+';'
280+
cmd = str(rnd) + ';'
281281
try:
282282
E.sendline(cmd)
283-
E.expect(r'@[nf][@J\s>]*'+str(rnd), timeout=timeout)
283+
E.expect(r'@[nf][@J\s>]*' + str(rnd), timeout=timeout)
284284
E.send(' ')
285285
E.expect('@i', timeout=timeout)
286286
except pexpect.TIMEOUT:
@@ -443,7 +443,7 @@ def load_package(self, pkg, verbose=False):
443443
print("Loading GAP package {}".format(pkg))
444444
x = self.eval('LoadPackage("{}")'.format(pkg))
445445
if x == 'fail':
446-
raise RuntimeError("Error loading Gap package "+str(pkg)+". " +
446+
raise RuntimeError("Error loading Gap package " + str(pkg) + ". " +
447447
"You may want to install gap_packages SPKG.")
448448

449449
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):
497497
' -\n\\\\-'
498498
"""
499499
# '"
500-
#We remove all of the comments: On each line, we try
501-
#to find a pound sign. If we find it, we check to see if
502-
#it is occurring in a string. If it is not in a string, we
503-
#strip off the comment.
500+
# We remove all of the comments: On each line, we try
501+
# to find a pound sign. If we find it, we check to see if
502+
# it is occurring in a string. If it is not in a string, we
503+
# strip off the comment.
504504
if not split_lines:
505505
input_line = str(x)
506506
else:
@@ -510,17 +510,17 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds):
510510
while pound_position != -1:
511511
if not is_in_string(line, pound_position):
512512
line = line[:pound_position]
513-
pound_position = line.find('#',pound_position+1)
514-
input_line += " "+line
513+
pound_position = line.find('#', pound_position + 1)
514+
input_line += " " + line
515515
if not input_line.endswith(';'):
516516
input_line += ';'
517517
result = Expect.eval(self, input_line, **kwds)
518518
if not newlines:
519-
result = result.replace("\\\n","")
519+
result = result.replace("\\\n", "")
520520
return result.rstrip()
521521

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

588588
def _keyboard_interrupt(self):
@@ -687,8 +687,8 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if
687687
error += "\nRunning gap_reset_workspace()..."
688688
self.quit()
689689
gap_reset_workspace()
690-
error = error.replace('\r','')
691-
raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error,line))
690+
error = error.replace('\r', '')
691+
raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error, line))
692692
if not normal:
693693
return ''
694694

@@ -762,7 +762,7 @@ def _contains(self, v1, v2):
762762
sage: 2 in gap('Integers')
763763
True
764764
"""
765-
return self.eval('%s in %s' % (v1,v2)) == "true"
765+
return self.eval('%s in %s' % (v1, v2)) == "true"
766766

767767
def _true_symbol(self):
768768
"""
@@ -858,20 +858,21 @@ def function_call(self, function, args=None, kwds=None):
858858
args, kwds = self._convert_args_kwds(args, kwds)
859859
self._check_valid_function_name(function)
860860

861-
#Here we have to do some magic because not all GAP
862-
#functions return a value. If you try to store their
863-
#results to a variable, then GAP will complain. Thus, before
864-
#we evaluate the function, we make it so that the marker string
865-
#is in the 'last' variable in GAP. If the function returns a
866-
#value, then that value will be in 'last', otherwise it will
867-
#be the marker.
861+
# Here we have to do some magic because not all GAP
862+
# functions return a value. If you try to store their
863+
# results to a variable, then GAP will complain. Thus, before
864+
# we evaluate the function, we make it so that the marker string
865+
# is in the 'last' variable in GAP. If the function returns a
866+
# value, then that value will be in 'last', otherwise it will
867+
# be the marker.
868868
marker = '__SAGE_LAST__:="__SAGE_LAST__";;'
869869
cmd = "%s(%s);;" % (function, ",".join([s.name() for s in args] +
870-
['%s=%s' % (key,value.name()) for key, value in kwds.items()]))
870+
[f'{key}={value.name()}'
871+
for key, value in kwds.items()]))
871872
if len(marker) + len(cmd) <= self._eval_using_file_cutoff:
872873
# We combine the two commands so we only run eval() once and the
873874
# only output would be from the second command
874-
res = self.eval(marker+cmd)
875+
res = self.eval(marker + cmd)
875876
else:
876877
self.eval(marker)
877878
res = self.eval(cmd)
@@ -1035,7 +1036,8 @@ def _matrix_(self, R):
10351036

10361037
from sage.matrix.matrix_space import MatrixSpace
10371038
M = MatrixSpace(R, n, m)
1038-
entries = [[R(self[r,c]) for c in range(1,m+1)] for r in range(1,n+1)]
1039+
entries = [[R(self[r, c]) for c in range(1, m + 1)]
1040+
for r in range(1, n + 1)]
10391041
return M(entries)
10401042

10411043

@@ -1089,7 +1091,7 @@ def __init__(self, max_workspace_size=None,
10891091
self.__seq = 0
10901092
self._seed = seed
10911093

1092-
def set_seed(self,seed=None):
1094+
def set_seed(self, seed=None):
10931095
"""
10941096
Set the seed for gap interpreter.
10951097
@@ -1194,8 +1196,8 @@ def _start(self):
11941196
self.save_workspace()
11951197
# Now, as self._expect exists, we can compile some useful pattern:
11961198
self._compiled_full_pattern = self._expect.compile_pattern_list([
1197-
r'@p\d+\.','@@','@[A-Z]',r'@[123456!"#$%&][^+]*\+',
1198-
'@e','@c','@f','@h','@i','@m','@n','@r',r'@s\d',r'@w.*\+','@x','@z'])
1199+
r'@p\d+\.', '@@', '@[A-Z]', r'@[123456!"#$%&][^+]*\+',
1200+
'@e', '@c', '@f', '@h', '@i', '@m', '@n', '@r', r'@s\d', r'@w.*\+', '@x', '@z'])
11991201
# read everything up to the first "ready" prompt
12001202
self._expect.expect("@i")
12011203

@@ -1236,10 +1238,9 @@ def cputime(self, t=None):
12361238
"""
12371239
if t is not None:
12381240
return self.cputime() - t
1239-
else:
1240-
self.eval('_r_ := Runtimes();')
1241-
r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]')))
1242-
return r/1000.0
1241+
self.eval('_r_ := Runtimes();')
1242+
r = sum(eval(self.eval('[_r_.user_time, _r_.system_time, _r_.user_time_children, _r_.system_time_children]')))
1243+
return r / 1000.0
12431244

12441245
def save_workspace(self):
12451246
r"""
@@ -1339,7 +1340,7 @@ def set(self, var, value):
13391340
sage: gap.get('x')
13401341
'2'
13411342
"""
1342-
cmd = ('%s:=%s;;' % (var, value)).replace('\n','')
1343+
cmd = ('%s:=%s;;' % (var, value)).replace('\n', '')
13431344
self._eval_line(cmd, allow_use_file=True)
13441345

13451346
def get(self, var, use_file=False):
@@ -1356,10 +1357,10 @@ def get(self, var, use_file=False):
13561357
tmp = self._local_tmpfile()
13571358
if os.path.exists(tmp):
13581359
os.unlink(tmp)
1359-
self.eval('PrintTo("%s", %s);' % (tmp,var), strip=False)
1360+
self.eval('PrintTo("%s", %s);' % (tmp, var), strip=False)
13601361
with open(tmp) as f:
13611362
r = f.read()
1362-
r = r.strip().replace("\\\n","")
1363+
r = r.strip().replace("\\\n", "")
13631364
os.unlink(tmp)
13641365
return r
13651366
else:
@@ -1470,7 +1471,7 @@ def _tab_completion(self):
14701471
True
14711472
"""
14721473
names = eval(self.eval('NamesSystemGVars()')) + \
1473-
eval(self.eval('NamesUserGVars()'))
1474+
eval(self.eval('NamesUserGVars()'))
14741475
return [n for n in names if n[0] in string.ascii_letters]
14751476

14761477

@@ -1572,16 +1573,16 @@ def _latex_(self):
15721573
P = self._check_valid()
15731574
try:
15741575
s = P.eval('LaTeXObj(%s)' % self.name())
1575-
s = s.replace('\\\\','\\').replace('"','')
1576-
s = s.replace('%\\n',' ')
1576+
s = s.replace('\\\\', '\\').replace('"', '')
1577+
s = s.replace('%\\n', ' ')
15771578
return s
15781579
except RuntimeError:
15791580
return str(self)
15801581

15811582
@cached_method
15821583
def _tab_completion(self):
15831584
"""
1584-
Return additional tab completion entries
1585+
Return additional tab completion entries.
15851586
15861587
OUTPUT:
15871588
@@ -1595,10 +1596,11 @@ def _tab_completion(self):
15951596
"""
15961597
P = self.parent()
15971598
v = P.eval(r'\$SAGE.OperationsAdmittingFirstArgument(%s)' % self.name())
1598-
v = v.replace('Tester(','').replace('Setter(','').replace(')','').replace('\n', '')
1599+
v = v.replace('Tester(', '').replace('Setter(', '').replace(')', '').replace('\n', '')
15991600
v = v.split(',')
1600-
v = [ oper.split('"')[1] for oper in v ]
1601-
v = [ oper for oper in v if all(ch in string.ascii_letters for ch in oper) ]
1601+
v = (oper.split('"')[1] for oper in v)
1602+
v = [oper for oper in v
1603+
if all(ch in string.ascii_letters for ch in oper)]
16021604
return sorted(set(v))
16031605

16041606

@@ -1708,13 +1710,13 @@ def gfq_gap_to_sage(x, F):
17081710
return F(0)
17091711
i1 = s.index("(")
17101712
i2 = s.index(")")
1711-
q = eval(s[i1+1:i2].replace('^','**'))
1713+
q = eval(s[i1 + 1:i2].replace('^', '**'))
17121714
if not F.cardinality().is_power_of(q):
17131715
raise ValueError('%r has no subfield of size %r' % (F, q))
17141716
if s.find(')^') == -1:
17151717
e = 1
17161718
else:
1717-
e = int(s[i2+2:])
1719+
e = int(s[i2 + 2:])
17181720
if F.degree() == 1:
17191721
g = F(gap.eval('Int(Z(%s))' % q))
17201722
elif F.is_conway():
@@ -1724,6 +1726,7 @@ def gfq_gap_to_sage(x, F):
17241726
raise ValueError('%r is not prime or defined by a Conway polynomial' % F)
17251727
return g**e
17261728

1729+
17271730
def intmod_gap_to_sage(x):
17281731
r"""
17291732
INPUT:
@@ -1827,5 +1830,5 @@ def gap_console():
18271830
if not get_display_manager().is_in_terminal():
18281831
raise RuntimeError('Can use the console only in the terminal. Try %%gap magics instead.')
18291832
cmd, _ = gap_command(use_workspace_cache=False)
1830-
cmd += ' ' + os.path.join(SAGE_EXTCODE,'gap','console.g')
1833+
cmd += ' ' + os.path.join(SAGE_EXTCODE, 'gap', 'console.g')
18311834
os.system(cmd)

0 commit comments

Comments
 (0)