Skip to content

Commit

Permalink
sagemathgh-36758: Details in interfaces
Browse files Browse the repository at this point in the history
    
Just fixing a few suggestions of `ruff` and `pycodestyle` there

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: sagemath#36758
Reported by: Frédéric Chapoton
Reviewer(s): Matthias Köppe
  • Loading branch information
Release Manager committed Dec 12, 2023
2 parents 71bcb09 + 6b94f66 commit 3d335fa
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 44 deletions.
2 changes: 1 addition & 1 deletion src/sage/interfaces/expect.py
Original file line number Diff line number Diff line change
Expand Up @@ -802,7 +802,7 @@ def _get_tmpfile_from_server(self, local_file=None, remote_file=None):
os.system(cmd)

def _remove_tmpfile_from_server(self):
if not (self.__remote_tmpfile is None):
if self.__remote_tmpfile is not None:
raise NotImplementedError

def _eval_line_using_file(self, line, restart_if_needed=True):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/interfaces/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -1018,7 +1018,7 @@ def __del__(self):
return
if hasattr(self,'_name'):
P = self.parent()
if not (P is None):
if P is not None:
P.clear(self._name)

def _sage_repr(self):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/interfaces/mathematica.py
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,7 @@ def request_wolfram_alpha(input, verbose=False):
resp = opener.open(req)
# the website returns JSON containing the code
page_data = json.loads(resp.read().decode("utf-8"))
if not ("code" in page_data):
if "code" not in page_data:
raise ValueError("Wolfram did not return a code")
proxy_code = page_data['code']
if verbose:
Expand Down
22 changes: 11 additions & 11 deletions src/sage/interfaces/mathics.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ def set(self, var, value):
sage: bool(mathics('u').sage() == 2*x+e) # optional - mathics
True
"""
cmd = '%s=%s;' % (var, value)
cmd = f'{var}={value};'
_ = self.eval(cmd)

def get(self, var):
Expand All @@ -617,7 +617,7 @@ def _function_call_string(self, function, args, kwds):
sage: mathics._function_call_string('Sin', ['x'], [])
'Sin[x]'
"""
return "%s[%s]" % (function, ",".join(args))
return "{}[{}]".format(function, ",".join(args))

def _left_list_delim(self):
r"""
Expand Down Expand Up @@ -904,7 +904,7 @@ def __getitem__(self, n):
x
0.15
"""
return self.parent().new('%s[[%s]]' % (self._name, n))
return self.parent().new(f'{self._name}[[{n}]]')

def __getattr__(self, attrname):
r"""
Expand Down Expand Up @@ -939,7 +939,7 @@ def __float__(self, precision=16):
True
"""
P = self.parent()
return float(P._eval('N[%s,%s]' % (self.name(), precision)).last_eval.to_mpmath())
return float(P._eval(f'N[{self.name()},{precision}]').last_eval.to_mpmath())

def _reduce(self):
r"""
Expand Down Expand Up @@ -1084,9 +1084,9 @@ def _sage_(self, locals={}):
if self is not p and p is not None:
def conv(i):
return self.parent()(i).sage()
if type(p) is list:
if isinstance(p, list):
return [conv(i) for i in p]
elif type(p) is tuple:
elif isinstance(p, tuple):
return tuple([conv(i) for i in p])
elif type(p) is dict:
return {conv(k): conv(v) for k, v in p.items()}
Expand Down Expand Up @@ -1143,7 +1143,7 @@ def save_image(self, filename, ImageSize=600):
if not self._is_graphics():
raise ValueError('mathics expression is not graphics')
filename = os.path.abspath(filename)
s = 'Export["%s", %s, ImageSize->%s]' % (filename, self.name(), ImageSize)
s = f'Export["{filename}", {self.name()}, ImageSize->{ImageSize}]'
P.eval(s)

def _rich_repr_(self, display_manager, **kwds):
Expand Down Expand Up @@ -1228,11 +1228,11 @@ def _richcmp_(self, other, op):
False
"""
P = self.parent()
if str(P("%s < %s" % (self.name(), other.name()))) == P._true_symbol():
if str(P(f"{self.name()} < {other.name()}")) == P._true_symbol():
return rich_to_bool(op, -1)
elif str(P("%s > %s" % (self.name(), other.name()))) == P._true_symbol():
elif str(P(f"{self.name()} > {other.name()}")) == P._true_symbol():
return rich_to_bool(op, 1)
elif str(P("%s == %s" % (self.name(), other.name()))) == P._true_symbol():
elif str(P(f"{self.name()} == {other.name()}")) == P._true_symbol():
return rich_to_bool(op, 0)
return NotImplemented

Expand All @@ -1253,7 +1253,7 @@ def __bool__(self):
True
"""
P = self._check_valid()
cmd = '%s===%s' % (self._name, P._false_symbol())
cmd = f'{self._name}==={P._false_symbol()}'
return not str(P(cmd)) == P._true_symbol()

def n(self, *args, **kwargs):
Expand Down
4 changes: 2 additions & 2 deletions src/sage/interfaces/maxima_abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -918,9 +918,9 @@ def de_solve_laplace(self, de, vars, ics=None):
variables will have these initial conditions automatically
imposed.
"""
if not (ics is None):
if ics is not None:
d = len(ics)
for i in range(0,d-1):
for i in range(d - 1):
ic = 'atvalue(diff(%s(%s), %s, %s), %s = %s, %s)' % (
vars[1], vars[0], vars[0], i, vars[0], ics[0], ics[1+i])
self.eval(ic)
Expand Down
14 changes: 3 additions & 11 deletions src/sage/interfaces/polymake.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,12 @@
import os
import re

from .expect import Expect
from .interface import (Interface, InterfaceElement, InterfaceFunctionElement)
from sage.misc.verbose import get_verbose
from sage.misc.cachefunc import cached_method
from sage.interfaces.tab_completion import ExtraTabCompletion
from sage.structure.richcmp import rich_to_bool

import pexpect
from random import randrange

from time import sleep
import warnings

_name_pattern = re.compile('SAGE[0-9]+')

_available_polymake_answers = {
Expand Down Expand Up @@ -139,7 +132,6 @@ def __init__(self, seed=None):
sage: from sage.interfaces.polymake import PolymakeAbstract
sage: PolymakeAbstract()
Polymake
"""
Interface.__init__(self, "polymake")
self._seed = seed
Expand Down Expand Up @@ -167,7 +159,7 @@ def __reduce__(self):
True
"""
return reduce_load_Polymake, tuple([])
return reduce_load_Polymake, ()

def _object_class(self):
"""
Expand Down Expand Up @@ -281,7 +273,7 @@ def _coerce_impl(self, x, use_special=True):
# Convert dictionaries to hashes.
# This is an adaptation of the list/tuple code from Interface._coerce_impl
A = []
z = dict()
z = {}
cls = self._object_class()

def convert(y):
Expand Down Expand Up @@ -1985,7 +1977,7 @@ def eval(self, code, **kwds):
sage: print(polymake.eval('$tmp="abc";\nprint $tmp;')) # optional - jupymake
abc
When requesting help, polymake sometimes expect the user to choose
When requesting help, polymake sometimes expects the user to choose
from a list. In that situation, we abort with a warning, and show
the list from which the user can choose; we could demonstrate this using
the :meth:`~sage.interfaces.polymake.PolymakeAbstract.help` method,
Expand Down
37 changes: 20 additions & 17 deletions src/sage/interfaces/qepcad.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,7 +640,9 @@ def _qepcad_atoms(formula):
sage: _qepcad_atoms('y^5 + 4 y + 8 >= 0 /\\ y <= 0 /\\ [ y = 0 \\/ y^5 + 4 y + 8 = 0 ]')
{'y <= 0', 'y = 0', 'y^5 + 4 y + 8 = 0', 'y^5 + 4 y + 8 >= 0'}
"""
return set(i.strip() for i in flatten([i.split('\\/') for i in formula.replace('[','').replace(']','').split('/\\')]))
L = flatten([i.split('\\/') for i in formula.replace('[', '').replace(']', '').split('/\\')])
return {i.strip() for i in L}


def _qepcad_cmd(memcells=None):
r"""
Expand All @@ -659,10 +661,10 @@ def _qepcad_cmd(memcells=None):
True
"""
if memcells is not None:
memcells_arg = '+N%s' % memcells
memcells_arg = f'+N{memcells}'
else:
memcells_arg = ''
return "env qe=%s qepcad %s" % (SAGE_LOCAL, memcells_arg)
return f"env qe={SAGE_LOCAL} qepcad {memcells_arg}"


_command_info_cache = None
Expand Down Expand Up @@ -894,7 +896,7 @@ def __repr__(self):
sage: qepcad(x - 1 == 0, interact=True) # optional - qepcad
QEPCAD object in phase 'Before Normalization'
"""
return "QEPCAD object in phase '{}'".format(self.phase())
return f"QEPCAD object in phase '{self.phase()}'"

def assume(self, assume):
r"""
Expand Down Expand Up @@ -1038,7 +1040,7 @@ def set_truth_value(self, index, nv):
sage: qe.set_truth_value(1, 1) # optional - qepcad
"""
index_str = _format_cell_index([index])
self._eval_line('set-truth-value\n%s\n%s' % (index_str, nv))
self._eval_line(f'set-truth-value\n{index_str}\n{nv}')

def phase(self):
r"""
Expand Down Expand Up @@ -1325,7 +1327,7 @@ def _function_call(self, name, args):
name = name.replace('_', '-')
args = [str(_) for _ in args]
pre_phase = self.phase()
result = self._eval_line('%s %s' % (name, ' '.join(args)))
result = self._eval_line('{} {}'.format(name, ' '.join(args)))
post_phase = self.phase()
if len(result) and post_phase != 'EXITED':
return AsciiArtString(result)
Expand All @@ -1334,6 +1336,7 @@ def _function_call(self, name, args):
return self.answer()
return AsciiArtString("QEPCAD object has moved to phase '%s'" % post_phase)


def _format_cell_index(a):
"""
Given a tuple (or list, etc.) containing a QEPCAD cell index, return a
Expand Down Expand Up @@ -1678,7 +1681,7 @@ def qepcad(formula, assume=None, interact=False, solution=None,
"infinitely many points")
return [c.sample_point_dict() for c in cells]
else:
raise ValueError("Unknown solution type ({})".format(solution))
raise ValueError(f"Unknown solution type ({solution})")


def qepcad_console(memcells=None):
Expand Down Expand Up @@ -1727,6 +1730,7 @@ def qepcad_banner():
banner = bytes_to_str(qex.expect().before)
return AsciiArtString(banner)


def qepcad_version():
"""
Return a string containing the current QEPCAD version number.
Expand Down Expand Up @@ -1935,7 +1939,7 @@ def atomic(self, lhs, op='=', rhs=0):

op = self._normalize_op(op)

formula = ('%r %s %r' % (lhs, op, rhs))
formula = f'{lhs!r} {op} {rhs!r}'
formula = formula.replace('*', ' ')
vars = self._varset(lhs) | self._varset(rhs)

Expand Down Expand Up @@ -2290,7 +2294,7 @@ def quantifier(self, kind, v, formula, allow_multi=True):
formula = self.formula(formula)

if allow_multi and isinstance(v, (list, tuple)):
if len(v) == 0:
if not v:
return formula
else:
return self.quantifier(kind, v[0],
Expand All @@ -2300,10 +2304,10 @@ def quantifier(self, kind, v, formula, allow_multi=True):
if form_str[-1] != ']':
form_str = '[' + form_str + ']'
v = str(v)
if not (v in formula.vars):
if v not in formula.vars:
raise ValueError("Attempting to quantify variable which "
"does not occur in formula")
form_str = "(%s %s)%s" % (kind, v, form_str)
form_str = f"({kind} {v}){form_str}"
return qformula(form_str, formula.vars - frozenset([v]),
[v] + formula.qvars)

Expand Down Expand Up @@ -2353,8 +2357,7 @@ def _eval_qepcad_algebraic(text):
if intv.lower().exact_rational() == lbound and intv.upper().exact_rational() == ubound:
return AA.polynomial_root(p, intv)

raise ValueError("%s or %s not an exact floating-point number" % (lbound,
ubound))
raise ValueError(f"{lbound} or {ubound} not an exact floating-point number")


class QepcadCell:
Expand Down Expand Up @@ -2425,7 +2428,7 @@ def __init__(self, parent, lines):
if 'Information about the cell' in line:
tail = line.split('(')[1]
index = tail.split(')')[0]
if index == '':
if not index:
index = ()
else:
index = sage_eval(index)
Expand All @@ -2443,7 +2446,7 @@ def __init__(self, parent, lines):
else:
self._number_of_children = None
if 'Truth value' in line:
pass # might change
pass # might change
if 'Degrees after substitution' in line:
if self._level == max_level or self._level == 0:
self._degrees = None
Expand All @@ -2457,7 +2460,7 @@ def __init__(self, parent, lines):
(lev, n, colon, signs) = line.split()
assert lev == 'Level' and colon == ':'
assert int(n) == len(all_signs) + 1
signs = signs.replace('+','1').replace('-','-1').replace(')',',)')
signs = signs.replace('+', '1').replace('-', '-1').replace(')', ',)')
all_signs.append(sage_eval(signs))
if 'PRIMITIVE' in line:
saw_primitive = True
Expand Down Expand Up @@ -2757,4 +2760,4 @@ def sample_point_dict(self):
"""
points = self.sample_point()
vars = self._parent._varlist
return dict([(vars[i], points[i]) for i in range(len(points))])
return {vars[i]: points[i] for i in range(len(points))}

0 comments on commit 3d335fa

Please sign in to comment.