diff --git a/src/sage/geometry/cone.py b/src/sage/geometry/cone.py index 933f3341613..459d5ac58ef 100644 --- a/src/sage/geometry/cone.py +++ b/src/sage/geometry/cone.py @@ -201,20 +201,28 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations -from collections.abc import Hashable, Iterable, Container +from collections.abc import Container, Hashable, Iterable from copy import copy +from typing import TYPE_CHECKING from warnings import warn from sage.misc.lazy_import import lazy_import + lazy_import('sage.combinat.posets.posets', 'FinitePoset') -from sage.arith.misc import GCD as gcd from sage.arith.functions import lcm +from sage.arith.misc import GCD as gcd from sage.geometry.point_collection import PointCollection from sage.geometry.polyhedron.constructor import Polyhedron + lazy_import('sage.geometry.hasse_diagram', 'lattice_from_incidences') -from sage.geometry.toric_lattice import (ToricLattice, ToricLattice_generic, - ToricLattice_quotient) +from sage.geometry.toric_lattice import ( + ToricLattice, + ToricLattice_generic, + ToricLattice_quotient, +) + lazy_import('sage.geometry.toric_plotter', ['ToricPlotter', 'label_list']) from sage.geometry.relative_interior import RelativeInterior from sage.matrix.constructor import matrix @@ -223,24 +231,28 @@ from sage.misc.cachefunc import cached_method from sage.misc.flatten import flatten from sage.misc.latex import latex -from sage.modules.free_module import span, VectorSpace +from sage.modules.free_module import VectorSpace, span from sage.modules.free_module_element import vector from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ -from sage.structure.sage_object import SageObject from sage.structure.element import parent -from sage.structure.richcmp import richcmp_method, richcmp +from sage.structure.richcmp import richcmp, richcmp_method +from sage.structure.sage_object import SageObject + lazy_import('sage.geometry.integral_points', 'parallelotope_points') -from sage.geometry.convex_set import ConvexSet_closed import sage.geometry.abc - from sage.features import PythonModule +from sage.geometry.convex_set import ConvexSet_closed + lazy_import('ppl', ['C_Polyhedron', 'Generator_System', 'Constraint_System', 'Linear_Expression', 'Poly_Con_Relation'], feature=PythonModule("ppl", spkg='pplpy', type='standard')) lazy_import('ppl', ['ray', 'point'], as_=['PPL_ray', 'PPL_point'], feature=PythonModule("ppl", spkg='pplpy', type='standard')) +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + def is_Cone(x): r""" @@ -1510,7 +1522,7 @@ def __init__(self, rays=None, lattice=None, if PPL is not None: self._PPL_C_Polyhedron = PPL - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: """ Return Sage command to reconstruct ``self``. @@ -4328,8 +4340,9 @@ def semigroup_generators(self): # recursively N = self.lattice() if not self.is_simplicial(): - from sage.geometry.triangulation.point_configuration \ - import PointConfiguration + from sage.geometry.triangulation.point_configuration import ( + PointConfiguration, + ) origin = self.n_rays() # last one in pc pc = PointConfiguration(tuple(self.rays()) + (N(0),), star=origin) triangulation = pc.triangulate() @@ -6772,12 +6785,11 @@ def random_cone(lattice=None, min_ambient_dim=0, max_ambient_dim=None, msg = 'max_rays must be at least min_ambient_dim for ' msg += 'a solid cone.' raise ValueError(msg) - else: - # Repeat the checks above when a lattice is given. - if max_rays is not None and max_rays < lattice.dimension(): - msg = "max_rays must be at least {0} for a solid cone " - msg += "in this lattice." - raise ValueError(msg.format(lattice.dimension())) + # Repeat the checks above when a lattice is given. + elif max_rays is not None and max_rays < lattice.dimension(): + msg = "max_rays must be at least {0} for a solid cone " + msg += "in this lattice." + raise ValueError(msg.format(lattice.dimension())) # Sanity checks for non-solid cones. if solid is not None and not solid: @@ -6852,9 +6864,8 @@ def is_valid(K): if (max_ambient_dim is not None and K.lattice_dim() > max_ambient_dim): return False - else: - if K.lattice() is not lattice: - return False + elif K.lattice() is not lattice: + return False return all([K.n_rays() >= min_rays, max_rays is None or K.n_rays() <= max_rays, solid is None or K.is_solid() == solid, @@ -6945,17 +6956,16 @@ def is_valid(K): rays[i][0] = pm * (ray[0].abs() + 1) K = Cone(rays, lattice=L) - else: - # The user requested that the cone be NOT strictly - # convex. So it should contain some line... - if K.is_strictly_convex(): - # ...but it doesn't. If K has at least two rays, - # we can just make the second one a multiple of - # the first -- then K will contain a line. If K - # has fewer than two rays, we punt. - if len(rays) >= 2: - rays[1] = -rays[0] - K = Cone(rays, lattice=L) + # The user requested that the cone be NOT strictly + # convex. So it should contain some line... + elif K.is_strictly_convex(): + # ...but it doesn't. If K has at least two rays, + # we can just make the second one a multiple of + # the first -- then K will contain a line. If K + # has fewer than two rays, we punt. + if len(rays) >= 2: + rays[1] = -rays[0] + K = Cone(rays, lattice=L) if is_valid(K): # Loop if we don't have a valid cone. diff --git a/src/sage/geometry/fan.py b/src/sage/geometry/fan.py index b4f00a3bab4..074b25a17fc 100644 --- a/src/sage/geometry/fan.py +++ b/src/sage/geometry/fan.py @@ -233,14 +233,14 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations from collections.abc import Callable, Container from copy import copy +from typing import TYPE_CHECKING from warnings import warn import sage.geometry.abc - -from sage.structure.richcmp import richcmp_method, richcmp from sage.misc.lazy_import import lazy_import lazy_import('sage.combinat.combination', 'Combinations') lazy_import('sage.combinat.posets.posets', 'FinitePoset') @@ -262,6 +262,9 @@ from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + def is_Fan(x) -> bool: r""" @@ -1217,7 +1220,7 @@ def __init__(self, cones, rays, lattice, if virtual_rays is not None: self._virtual_rays = PointCollection(virtual_rays, self.lattice()) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: """ Return Sage command to reconstruct ``self``. @@ -2487,8 +2490,8 @@ def is_polytopal(self) -> bool: """ if not self.is_complete(): raise ValueError('to be polytopal, the fan should be complete') - from sage.geometry.triangulation.point_configuration import PointConfiguration from sage.geometry.polyhedron.constructor import Polyhedron + from sage.geometry.triangulation.point_configuration import PointConfiguration pc = PointConfiguration(self.rays()) v_pc = [tuple(p) for p in pc] pc_to_indices = {tuple(p):i for i, p in enumerate(pc)} @@ -2757,8 +2760,10 @@ def is_isomorphic(self, other) -> bool: sage: fan1.is_isomorphic(fan1) True """ - from sage.geometry.fan_isomorphism import \ - fan_isomorphic_necessary_conditions, fan_isomorphism_generator + from sage.geometry.fan_isomorphism import ( + fan_isomorphic_necessary_conditions, + fan_isomorphism_generator, + ) if not fan_isomorphic_necessary_conditions(self, other): return False if self.lattice_dim() == 2: diff --git a/src/sage/geometry/lattice_polytope.py b/src/sage/geometry/lattice_polytope.py index 36d1731dba4..a113a4a606e 100644 --- a/src/sage/geometry/lattice_polytope.py +++ b/src/sage/geometry/lattice_polytope.py @@ -120,24 +120,26 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations + +import os +import shlex from collections.abc import Hashable from copyreg import constructor as copyreg_constructor from functools import reduce from io import IOBase, StringIO -from subprocess import Popen, PIPE -from warnings import warn -import os -import shlex +from subprocess import PIPE, Popen +from typing import TYPE_CHECKING +import sage.geometry.abc from sage.arith.misc import GCD as gcd from sage.features import PythonModule -from sage.features.palp import PalpExecutable from sage.features.databases import DatabaseReflexivePolytopes +from sage.features.palp import PalpExecutable from sage.geometry.cone import _ambient_space_point, integral_length -from sage.geometry.point_collection import (PointCollection, - read_palp_point_collection) -from sage.geometry.toric_lattice import ToricLattice, ToricLattice_generic from sage.geometry.convex_set import ConvexSet_compact +from sage.geometry.point_collection import PointCollection, read_palp_point_collection +from sage.geometry.toric_lattice import ToricLattice, ToricLattice_generic from sage.matrix.constructor import matrix from sage.misc.cachefunc import cached_method from sage.misc.flatten import flatten @@ -149,11 +151,9 @@ from sage.rings.rational_field import QQ from sage.sets.set import Set_generic from sage.structure.element import Matrix -from sage.structure.richcmp import richcmp_method, richcmp +from sage.structure.richcmp import richcmp, richcmp_method from sage.structure.sage_object import SageObject from sage.structure.sequence import Sequence -import sage.geometry.abc - lazy_import("sage.combinat.posets.posets", 'FinitePoset') lazy_import("sage.geometry.hasse_diagram", 'lattice_from_incidences') @@ -167,6 +167,9 @@ lazy_import('ppl', 'point', as_='PPL_point', feature=PythonModule("ppl", spkg='pplpy', type='standard')) +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + class SetOfAllLatticePolytopesClass(Set_generic): def _repr_(self) -> str: @@ -570,7 +573,7 @@ def __init__(self, points=None, compute_vertices=None, self._ambient_facet_indices = tuple(ambient_facet_indices) self._vertices = ambient.vertices(self._ambient_vertex_indices) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: """ Return Sage command to reconstruct ``self``. @@ -4471,7 +4474,7 @@ def _repr_(self): pass return result - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: bool) -> SageInputExpression: """ Return Sage command to reconstruct ``self``. diff --git a/src/sage/geometry/point_collection.pyx b/src/sage/geometry/point_collection.pyx index 8cebd2fd2d8..a84594fa666 100644 --- a/src/sage/geometry/point_collection.pyx +++ b/src/sage/geometry/point_collection.pyx @@ -83,6 +83,8 @@ from sage.geometry.toric_lattice import ToricLattice from sage.matrix.constructor import matrix from sage.misc.latex import latex +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + def is_PointCollection(x): r""" @@ -172,7 +174,7 @@ cdef class PointCollection(SageObject): self._points = tuple(points) self._module = self._points[0].parent() if module is None else module - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Return Sage command to reconstruct ``self``. diff --git a/src/sage/geometry/polyhedron/base0.py b/src/sage/geometry/polyhedron/base0.py index c710c5dfa62..e7214d71188 100644 --- a/src/sage/geometry/polyhedron/base0.py +++ b/src/sage/geometry/polyhedron/base0.py @@ -29,11 +29,17 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations -from sage.misc.cachefunc import cached_method +from typing import TYPE_CHECKING + +import sage.geometry.abc from sage.misc.abstract_method import abstract_method +from sage.misc.cachefunc import cached_method from sage.structure.element import Element -import sage.geometry.abc + +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression class Polyhedron_base0(Element, sage.geometry.abc.Polyhedron): @@ -296,7 +302,7 @@ def _delete(self): """ self.parent().recycle(self) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: """ Return Sage command to reconstruct ``self``. diff --git a/src/sage/geometry/toric_lattice.py b/src/sage/geometry/toric_lattice.py index 53346206c05..da434eb826e 100644 --- a/src/sage/geometry/toric_lattice.py +++ b/src/sage/geometry/toric_lattice.py @@ -144,6 +144,9 @@ # # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations + +from typing import TYPE_CHECKING from sage.geometry.toric_lattice_element import ToricLatticeElement from sage.misc.lazy_import import lazy_import @@ -162,6 +165,9 @@ from sage.rings.rational_field import QQ from sage.structure.factory import UniqueFactory +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + def is_ToricLattice(x): r""" @@ -897,7 +903,7 @@ def __init__(self, rank, name, dual_name, latex_name, latex_dual_name): self._latex_name = latex_name self._latex_dual_name = latex_dual_name - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Return Sage command to reconstruct ``self``. diff --git a/src/sage/matrix/matrix1.pyx b/src/sage/matrix/matrix1.pyx index fe4586d5176..a5b40bffcbe 100644 --- a/src/sage/matrix/matrix1.pyx +++ b/src/sage/matrix/matrix1.pyx @@ -24,6 +24,7 @@ from cpython.sequence cimport PySequence_Fast import sage.modules.free_module from sage.structure.coerce cimport coercion_model +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression cdef class Matrix(Matrix0): ################################################### @@ -622,7 +623,7 @@ cdef class Matrix(Matrix0): matrix._sage_object = self return matrix - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/misc/explain_pickle.py b/src/sage/misc/explain_pickle.py index bd378b35d8f..cdf4ce1d223 100644 --- a/src/sage/misc/explain_pickle.py +++ b/src/sage/misc/explain_pickle.py @@ -152,23 +152,25 @@ # (at your option) any later version. # http://www.gnu.org/licenses/ # ***************************************************************************** +from __future__ import annotations - +import bz2 as comp_other import pickletools import re import sys import types - import zlib as comp -import bz2 as comp_other - from pickletools import genops -from sage.misc.sage_input import SageInputBuilder, SageInputExpression +from sage.misc.persist import ( + SageUnpickler, + dumps, + register_unpickle_override, + unpickle_global, + unpickle_override, +) from sage.misc.sage_eval import sage_eval -from sage.misc.persist import (unpickle_override, unpickle_global, dumps, - register_unpickle_override, SageUnpickler) - +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression # Python 3 does not have a "ClassType". Instead, we ensure that # isinstance(foo, ClassType) will always return False. @@ -358,7 +360,7 @@ def __init__(self, value, expression): self.expression = expression self.immutable = False - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Extracts the expression from a PickleObject, and sets the immutable flag. @@ -424,8 +426,14 @@ class PickleExplainer: symbolically and constructs :class:`SageInputExpression` objects instead of directly constructing values. """ - def __init__(self, sib, in_current_sage=False, default_assumptions=False, - pedantic=False): + + def __init__( + self, + sib: SageInputBuilder, + in_current_sage=False, + default_assumptions=False, + pedantic=False, + ): r""" Initialize a PickleExplainer interpreter for the pickle virtual machine. @@ -845,14 +853,13 @@ def _APPENDS_helper(self, lst, slice): else: for s in slice: self.sib.command(lst, self.sib.name('list').append(lst, self.sib(s))) + elif self.pedantic: + app = self.sib(lst).append + for s in slice: + self.sib.command(lst, app(self.sib(s))) else: - if self.pedantic: - app = self.sib(lst).append - for s in slice: - self.sib.command(lst, app(self.sib(s))) - else: - for s in slice: - self.sib.command(lst, self.sib(lst).append(self.sib(s))) + for s in slice: + self.sib.command(lst, self.sib(lst).append(self.sib(s))) else: self.sib.command(lst, self.sib.name('unpickle_appends')(self.sib(lst), slice_exp)) self.push(lst) @@ -2509,7 +2516,7 @@ def unpickle_extension(code): sage: remove_extension('sage.misc.explain_pickle', 'EmptyNewstyleClass', 42) """ - from copyreg import _inverted_registry, _extension_cache + from copyreg import _extension_cache, _inverted_registry # copied from .get_extension() in pickle.py nil = [] obj = _extension_cache.get(code, nil) diff --git a/src/sage/misc/sage_input.py b/src/sage/misc/sage_input.py index 39909c0d87b..184eb0cff71 100644 --- a/src/sage/misc/sage_input.py +++ b/src/sage/misc/sage_input.py @@ -171,14 +171,22 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations + +from typing import Any, Literal from sage.misc.lazy_import import lazy_import +from sage.structure.element import parent lazy_import('sage.rings.real_mpfi', 'RealIntervalFieldElement') lazy_import('sage.rings.complex_interval', 'ComplexIntervalFieldElement') +CoercionMode = bool | Literal[2] + -def sage_input(x, preparse=True, verify=False, allow_locals=False): +def sage_input( + x, preparse: bool | None = True, verify: bool = False, allow_locals: bool = False +) -> SageInputAnswer: r""" Return a sequence of commands that can be used to rebuild the object ``x``. @@ -276,7 +284,7 @@ def sage_input(x, preparse=True, verify=False, allow_locals=False): ans_l[0] = '# Verified\n' + ans_l[0] final_answer = SageInputAnswer(*ans_l) - return final_answer + return final_answer # pyright: ignore[reportPossiblyUnboundVariable] class SageInputBuilder: @@ -304,7 +312,9 @@ class SageInputBuilder: (3 + 4)*(5 + 6) """ - def __init__(self, allow_locals=False, preparse=True): + def __init__( + self, allow_locals: bool = False, preparse: bool | None = True + ) -> None: r""" Initialize an instance of :class:`SageInputBuilder`. @@ -333,16 +343,16 @@ def __init__(self, allow_locals=False, preparse=True): sage: SageInputBuilder(preparse=False).preparse() False """ - self._allow_locals = allow_locals - self._preparse = preparse - self._cached_types = set() - self._cache = {} - self._id_cache = {} - self._parent_gens = {} - self._next_local = 1 - self._locals = {} + self._allow_locals: bool = allow_locals + self._preparse: bool | None = preparse + self._cached_types: set[type] = set() + self._cache: dict[tuple[Any, Any], SageInputExpression] = {} + self._id_cache: dict[int, tuple[Any, SageInputExpression]] = {} + self._parent_gens: dict[Any, list[SIE_gen]] = {} + self._next_local: int = 1 + self._locals: dict[str, Any] = {} - def __call__(self, x, coerced=False): + def __call__(self, x: Any, coerced: CoercionMode = False) -> SageInputExpression: r""" Try to convert an arbitrary value ``x`` into a :class:`SageInputExpression` (an SIE). @@ -445,7 +455,6 @@ def __call__(self, x, coerced=False): # However, we don't want to assume that hashing x is always # efficient, so we only try the lookup if some value of the same # type as x has been cached. - from sage.structure.element import parent if type(x) in self._cached_types: v = self._cache.get((parent(x), x)) @@ -476,11 +485,10 @@ def __call__(self, x, coerced=False): return SIE_literal_stringrep(self, str(x) + 'r') elif self._preparse is False: return self.int(x) + elif x < 0: + return -self.name('int')(self.int(-x)) else: - if x < 0: - return -self.name('int')(self.int(-x)) - else: - return self.name('int')(self.int(x)) + return self.name('int')(self.int(x)) if isinstance(x, float): # floats could often have prettier output, @@ -498,8 +506,8 @@ def __call__(self, x, coerced=False): return -SIE_literal_stringrep(self, str(-x)) else: return SIE_literal_stringrep(self, str(x)) - from sage.rings.real_mpfr import RR from sage.rings.integer_ring import ZZ + from sage.rings.real_mpfr import RR rrx = RR(x) if rrx in ZZ and abs(rrx) < (1 << 53): return self.name('float')(self.int(ZZ(rrx))) @@ -526,7 +534,7 @@ def __call__(self, x, coerced=False): else: raise ValueError("cannot convert {} to sage_input form".format(x)) - def preparse(self): + def preparse(self) -> bool | None: r""" Check the preparse status. @@ -548,7 +556,7 @@ def preparse(self): """ return self._preparse - def int(self, n): + def int(self, n) -> SIE_unary | SIE_literal_stringrep: r""" Return a raw SIE from the integer ``n``. @@ -576,7 +584,7 @@ def int(self, n): else: return SIE_literal_stringrep(self, n) - def float_str(self, n): + def float_str(self, n) -> SIE_literal_stringrep: r""" Given a string representing a floating-point number, produces a :class:`SageInputExpression` that formats as that @@ -592,7 +600,7 @@ def float_str(self, n): """ return SIE_literal_stringrep(self, n) - def name(self, n): + def name(self, n: str) -> SIE_literal_stringrep: r""" Given a string representing a Python name, produces a :class:`SageInputExpression` for that name. @@ -607,7 +615,7 @@ def name(self, n): """ return SIE_literal_stringrep(self, n) - def cache(self, x, sie, name): + def cache(self, x: Any, sie: SageInputExpression, name: str) -> None: r""" INPUT: @@ -648,13 +656,11 @@ def cache(self, x, sie, name): GF_101 = GF(101) GF_101(42) + GF_101(43) """ - from sage.structure.element import parent - self._cached_types.add(type(x)) self._cache[(parent(x), x)] = sie sie._sie_preferred_varname = name - def id_cache(self, x, sie, name): + def id_cache(self, x: Any, sie: SageInputExpression, name: str) -> None: r""" INPUT: @@ -714,7 +720,9 @@ def id_cache(self, x, sie, name): self._id_cache[id(x)] = (x, sie) sie._sie_preferred_varname = name - def import_name(self, module, name, alt_name=None): + def import_name( + self, module: str, name: str, alt_name: str | None = None + ) -> SIE_import_name: r""" INPUT: @@ -747,7 +755,7 @@ def import_name(self, module, name, alt_name=None): """ return SIE_import_name(self, module, name, alt_name) - def assign(self, e, val): + def assign(self, e: SageInputExpression, val: SageInputExpression) -> SIE_assign: r""" Construct a command that performs the assignment ``e=val``. @@ -774,7 +782,7 @@ def assign(self, e, val): return SIE_assign(self, e, val) - def command(self, v, cmd): + def command(self, v: SageInputExpression, cmd: SageInputExpression) -> None: r""" INPUT: @@ -802,7 +810,11 @@ def command(self, v, cmd): v._sie_commands.append(cmd) - def dict(self, entries): + def dict( + self, + entries: dict[SageInputExpression, SageInputExpression] + | list[tuple[SageInputExpression, SageInputExpression]], + ) -> SIE_dict: r""" Given a dictionary, or a list of (key, value) pairs, produces a :class:`SageInputExpression` representing @@ -823,7 +835,7 @@ def dict(self, entries): entries = [(self(key), self(val)) for (key, val) in entries] return SIE_dict(self, entries) - def getattr(self, sie, attr): + def getattr(self, sie: SageInputExpression, attr: str) -> SIE_getattr: r""" Given a :class:`SageInputExpression` representing ``foo`` and an attribute name bar, produce a :class:`SageInputExpression` @@ -844,7 +856,7 @@ def getattr(self, sie, attr): """ return SIE_getattr(self, self(sie), attr) - def empty_subscript(self, parent): + def empty_subscript(self, parent: SageInputExpression) -> SIE_subscript: r""" Given a :class:`SageInputExpression` representing ``foo``, produces a :class:`SageInputExpression` representing ``foo[]``. @@ -867,7 +879,7 @@ def empty_subscript(self, parent): """ return SIE_subscript(self, parent, None) - def use_variable(self, sie, name): + def use_variable(self, sie: SageInputExpression, name: str): r""" Marks the :class:`SageInputExpression` ``sie`` to use a variable even if it is only referenced once. (If ``sie`` is the final @@ -1004,7 +1016,7 @@ def parent_with_gens(self, parent, sie, gen_names, name, gens_syntax=None): v._sie_gens = gens return v - def gen(self, parent, n=0): + def gen(self, parent: Any, n=0) -> SIE_gen: r""" Given a parent, returns a :class:`SageInputExpression` for the `n`-th (default: 0) generator of the parent. @@ -1146,7 +1158,7 @@ def sum(self, terms, simplify=False): sum = sum + term return sum - def result(self, e): + def result(self, e: SageInputExpression) -> SageInputAnswer: r""" Given a :class:`SageInputExpression` constructed using ``self``, returns a tuple of a list of commands and an expression @@ -1232,7 +1244,7 @@ class SageInputExpression: way, that reveals the internal structure of the expression tree. """ - def __init__(self, sib): + def __init__(self, sib: SageInputBuilder) -> None: r""" Initialize a :class:`SageInputExpression`. @@ -1246,17 +1258,17 @@ def __init__(self, sib): sage: sie._sie_builder is sib True """ - self._sie_refcount = 0 - self._sie_builder = sib - self._sie_context = None - self._sie_preferred_varname = None + self._sie_refcount: int = 0 + self._sie_builder: SageInputBuilder = sib + self._sie_context: SageInputFormatter | None = None + self._sie_preferred_varname: str | None = None self._sie_varname = None - self._sie_request_use_var = False + self._sie_request_use_var: bool = False self._sie_use_var = False self._sie_requested_varname = False - self._sie_commands = [] + self._sie_commands: list[SageInputExpression] = [] - def _sie_is_simple(self): + def _sie_is_simple(self) -> bool: r""" Return ``True`` if this :class:`SageInputExpression` is simple enough that duplicate uses are not worth caching. Normally @@ -1273,7 +1285,7 @@ def _sie_is_simple(self): """ return False - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SageInputExpression`. @@ -1289,7 +1301,7 @@ def _sie_referenced(self): """ return [] - def _sie_prepare(self, sif): + def _sie_prepare(self, sif: SageInputFormatter) -> None: r""" We traverse the entire expression DAG to prepare for printing. Here, we notice nodes with more than one parent, and mark them @@ -1330,7 +1342,7 @@ def _sie_prepare(self, sif): for r in self._sie_commands: r._sie_prepare(sif) - def _sie_require_varname(self, sif): + def _sie_require_varname(self, sif: SageInputFormatter) -> None: r""" Mark this :class:`SageInputExpression` as requiring a variable name, and register it with a :class:`SageInputFormatter` (which will @@ -1351,7 +1363,7 @@ def _sie_require_varname(self, sif): self._sie_requested_varname = True self._sie_generated = False - def _sie_get_varname(self, sif): + def _sie_get_varname(self, sif: SageInputFormatter) -> str: r""" Get the variable name that the :class:`SageInputFormatter` allocated for this :class:`SageInputExpression`. @@ -1371,7 +1383,7 @@ def _sie_get_varname(self, sif): return self._sie_varname - def _sie_is_negation(self): + def _sie_is_negation(self) -> bool: r""" Test whether a :class:`SageInputExpression` is a negation. @@ -1390,7 +1402,9 @@ def _sie_is_negation(self): """ return False - def __call__(self, *args, **kwargs): + def __call__( + self, *args: SageInputExpression, **kwargs: dict[str, SageInputExpression] + ) -> SIE_call: r""" Given a :class:`SageInputExpression`, build a new :class:`SageInputExpression` representing a function call node @@ -1409,7 +1423,7 @@ def __call__(self, *args, **kwargs): for key, val in kwargs.items()} return SIE_call(self._sie_builder, self, new_args, new_kwargs) - def __getitem__(self, key): + def __getitem__(self, key: SageInputExpression) -> SIE_subscript: r""" Given a :class:`SageInputExpression`, build a new :class:`SageInputExpression` representing a subscript expression @@ -1430,7 +1444,7 @@ def __getitem__(self, key): skey = self._sie_builder(key) return SIE_subscript(self._sie_builder, self, skey) - def __getattr__(self, attr): + def __getattr__(self, attr: str) -> SIE_getattr: r""" Given a :class:`SageInputExpression`, build a new :class:`SageInputExpression` representing an attribute access. @@ -1447,7 +1461,7 @@ def __getattr__(self, attr): """ return SIE_getattr(self._sie_builder, self, attr) - def _rich_repr_(self, display_manager, **kwds): + def _rich_repr_(self, display_manager, **kwds) -> None: """ Disable rich output. @@ -1465,7 +1479,7 @@ def _rich_repr_(self, display_manager, **kwds): """ return None - def __pow__(self, other): + def __pow__(self, other: SageInputExpression) -> SIE_binary: r""" Compute an expression tree for ``self ** other``. @@ -1479,7 +1493,7 @@ def __pow__(self, other): """ return self._sie_binop('**', other) - def __mul__(self, other): + def __mul__(self, other: SageInputExpression) -> SIE_binary: r""" Compute an expression tree for ``self * other``. @@ -1493,7 +1507,7 @@ def __mul__(self, other): """ return self._sie_binop('*', other) - def __truediv__(self, other): + def __truediv__(self, other: SageInputExpression) -> SIE_binary: r""" Compute an expression tree for ``self / other``. @@ -1507,7 +1521,7 @@ def __truediv__(self, other): """ return self._sie_binop('/', other) - def __add__(self, other): + def __add__(self, other: SageInputExpression) -> SIE_binary: r""" Compute an expression tree for ``self + other``. @@ -1521,7 +1535,7 @@ def __add__(self, other): """ return self._sie_binop('+', other) - def __sub__(self, other): + def __sub__(self, other: SageInputExpression) -> SIE_binary: r""" Compute an expression tree for ``self - other``. @@ -1535,7 +1549,7 @@ def __sub__(self, other): """ return self._sie_binop('-', other) - def _sie_binop(self, op, other): + def _sie_binop(self, op: str, other: SageInputExpression) -> SIE_binary: r""" Compute an expression tree for ``self OP other``, where OP is a string representing a binary operator (such as @@ -1555,7 +1569,7 @@ def _sie_binop(self, op, other): """ return SIE_binary(self._sie_builder, op, self, self._sie_builder(other)) - def __neg__(self): + def __neg__(self) -> SIE_unary: r""" Compute an expression tree for ``-self``. @@ -1569,7 +1583,7 @@ def __neg__(self): """ return self._sie_unop('-') - def __pos__(self): + def __pos__(self) -> SIE_unary: r""" Compute an expression tree for ``+self``. @@ -1583,7 +1597,7 @@ def __pos__(self): """ return self._sie_unop('+') - def __invert__(self): + def __invert__(self) -> SIE_unary: r""" Compute an expression tree for ``~self``. @@ -1597,7 +1611,7 @@ def __invert__(self): """ return self._sie_unop('~') - def __abs__(self): + def __abs__(self) -> SIE_call: r""" Compute an expression tree for ``abs(self)``. @@ -1611,7 +1625,7 @@ def __abs__(self): """ return self._sie_builder.name('abs')(self) - def _sie_unop(self, op): + def _sie_unop(self, op: str) -> SIE_unary: r""" Compute an expression tree for ``OP self``, where OP is a string representing a unary operator (such as @@ -1632,7 +1646,7 @@ def _sie_unop(self, op): """ return SIE_unary(self._sie_builder, op, self) - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this expression, and the precedence of the top-level operator in the expression. @@ -1664,7 +1678,7 @@ def _sie_format(self, sif): """ raise NotImplementedError - def _sie_format_statement(self, sif): + def _sie_format_statement(self, sif: SageInputFormatter): r""" Return the formatted string value of this expression, when used as a statement. @@ -1763,7 +1777,7 @@ class SIE_literal_stringrep(SIE_literal): {atomic:False} """ - def __init__(self, sib, n): + def __init__(self, sib: SageInputBuilder, n: str) -> None: r""" Initialize a :class:`SIE_literal_stringrep` value. @@ -1787,7 +1801,7 @@ def __init__(self, sib, n): self._sie_value = str(n) self._sie_share = False - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representing this :class:`SIE_literal_stringrep` value. @@ -1804,7 +1818,7 @@ def __repr__(self): """ return "{atomic:%s}" % self._sie_value - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this expression, and an indication that it is ``atomic`` (never needs to be parenthesized). @@ -1838,7 +1852,13 @@ class SIE_call(SageInputExpression): {call: {atomic:GF}({atomic:49})} """ - def __init__(self, sib, func, args, kwargs): + def __init__( + self, + sib: SageInputBuilder, + func: SageInputExpression, + args: list[SageInputExpression], + kwargs: dict[str, SageInputExpression], + ) -> None: r""" Initialize an instance of :class:`SIE_call`. @@ -1866,7 +1886,7 @@ def __init__(self, sib, func, args, kwargs): self._sie_args = args self._sie_kwargs = kwargs - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representing this :class:`SIE_call` value. @@ -1884,7 +1904,7 @@ def __repr__(self): all_args = ', '.join(args + kwargs) return "{call: %s(%s)}" % (func, all_args) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_call`. @@ -1902,7 +1922,7 @@ def _sie_referenced(self): refs.extend(self._sie_kwargs.values()) return refs - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this expression, and an indication that it is a function call. @@ -1941,7 +1961,12 @@ class SIE_subscript(SageInputExpression): {subscr: {atomic:QQ}[{atomic:'x,y'}]} """ - def __init__(self, sib, coll, key): + def __init__( + self, + sib: SageInputBuilder, + coll: SageInputExpression, + key: SageInputExpression | None, + ) -> None: r""" Initialize an instance of :class:`SIE_subscript`. @@ -1973,7 +1998,7 @@ def __init__(self, sib, coll, key): self._sie_coll = coll self._sie_key = key - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representing this :class:`SIE_subscript` value. @@ -1992,7 +2017,7 @@ def __repr__(self): key = repr(self._sie_key) return "{subscr: %s[%s]}" % (coll, key) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_subscript`. @@ -2011,7 +2036,7 @@ def _sie_referenced(self): refs.append(self._sie_key) return refs - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this expression, and an indication that it is a subscript. @@ -2049,7 +2074,7 @@ class SIE_getattr(SageInputExpression): sage: sie {call: {getattr: {atomic:CC}.gen}()} """ - def __init__(self, sib, obj, attr): + def __init__(self, sib: SageInputBuilder, obj: SageInputExpression, attr: str) -> None: r""" Initialize an instance of :class:`SIE_getattr`. @@ -2088,7 +2113,7 @@ def __repr__(self): obj = repr(self._sie_obj) return "{getattr: %s.%s}" % (obj, self._sie_attr) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_subscript`. @@ -2104,7 +2129,7 @@ def _sie_referenced(self): """ return [self._sie_obj] - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this expression, and an indication that it is an attribute reference. @@ -2140,7 +2165,9 @@ class SIE_tuple(SageInputExpression): {list: ({atomic:'lists'})} """ - def __init__(self, sib, values, is_list): + def __init__( + self, sib: SageInputBuilder, values: list[SageInputExpression], is_list: bool + ) -> None: r""" Initialize an instance of :class:`SIE_tuple`. @@ -2165,10 +2192,10 @@ def __init__(self, sib, values, is_list): {list: ({atomic:'Hello'}, {atomic:'world'})} """ super().__init__(sib) - self._sie_values = values - self._sie_is_list = is_list + self._sie_values: list[SageInputExpression] = values + self._sie_is_list: bool = is_list - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representing this :class:`SIE_tuple` value. @@ -2186,7 +2213,7 @@ def __repr__(self): return "{%s: (%s)}" % \ (kind, ', '.join(repr(v) for v in self._sie_values)) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_tuple`. @@ -2202,7 +2229,7 @@ def _sie_referenced(self): """ return self._sie_values - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this tuple or list, and an indication that it is atomic (never needs to be parenthesized). @@ -2227,11 +2254,10 @@ def _sie_format(self, sif): values = [sif.format(val, 0) for val in self._sie_values] if self._sie_is_list: return '[%s]' % ', '.join(values), _prec_atomic + elif len(values) == 1: + return '(%s,)' % values[0], _prec_atomic else: - if len(values) == 1: - return '(%s,)' % values[0], _prec_atomic - else: - return '(%s)' % ', '.join(values), _prec_atomic + return '(%s)' % ', '.join(values), _prec_atomic class SIE_dict(SageInputExpression): @@ -2252,7 +2278,11 @@ class SIE_dict(SageInputExpression): {atomic:0}:{atomic:32}, {atomic:100}:{atomic:212}}} """ - def __init__(self, sib, entries): + def __init__( + self, + sib: SageInputBuilder, + entries: list[tuple[SageInputExpression, SageInputExpression]], + ) -> None: r""" Initialize an instance of :class:`SIE_dict`. @@ -2276,7 +2306,7 @@ def __init__(self, sib, entries): super().__init__(sib) self._sie_entries = entries - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representing this :class:`SIE_dict` value. @@ -2292,7 +2322,7 @@ def __repr__(self): ', '.join(repr(key) + ':' + repr(val) for key, val in self._sie_entries) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_dict`. @@ -2308,7 +2338,7 @@ def _sie_referenced(self): """ return [k for k, v in self._sie_entries] + [v for k, v in self._sie_entries] - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this dict, and an indication that it is atomic (never needs to be parenthesized). @@ -2342,7 +2372,13 @@ class SIE_binary(SageInputExpression): {binop:+ {atomic:3} {atomic:5}} """ - def __init__(self, sib, op, lhs, rhs): + def __init__( + self, + sib: SageInputBuilder, + op: str, + lhs: SageInputExpression, + rhs: SageInputExpression, + ) -> None: r""" Initialize an instance of :class:`SIE_binary`. @@ -2382,7 +2418,7 @@ def __repr__(self): """ return "{binop:%s %s %s}" % (self._sie_op, repr(self._sie_operands[0]), repr(self._sie_operands[1])) - def _sie_referenced(self): + def _sie_referenced(self) -> tuple[SageInputExpression, SageInputExpression]: r""" Return a tuple of the immediate subexpressions of this :class:`SIE_binary`. @@ -2398,7 +2434,7 @@ def _sie_referenced(self): """ return self._sie_operands - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this expression, and the precedence of the top-level operator in the expression. @@ -2492,7 +2528,9 @@ class SIE_unary(SageInputExpression): {unop:- {atomic:256}} """ - def __init__(self, sib, op, operand): + def __init__( + self, sib: SageInputBuilder, op: str, operand: SageInputExpression + ) -> None: r""" Initialize an instance of :class:`SIE_unary`. @@ -2514,7 +2552,7 @@ def __init__(self, sib, op, operand): """ super().__init__(sib) self._sie_op = op - self._sie_operand = operand + self._sie_operand: SageInputExpression = operand def __repr__(self): r""" @@ -2530,7 +2568,7 @@ def __repr__(self): """ return "{unop:%s %s}" % (self._sie_op, repr(self._sie_operand)) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_unary`. @@ -2546,7 +2584,7 @@ def _sie_referenced(self): """ return [self._sie_operand] - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this expression, and the precedence of the top-level operator in the expression. @@ -2628,7 +2666,7 @@ def _sie_format(self, sif): return '%s%s' % (fop, sif.format(self._sie_operand, prec)), rprec - def _sie_is_negation(self): + def _sie_is_negation(self) -> bool: r""" Test whether a :class:`SageInputExpression` is a negation. @@ -2679,7 +2717,13 @@ class SIE_gens_constructor(SageInputExpression): {constr_parent: {subscr: {atomic:QQ}[{atomic:'x'}]} with gens: ('x',)} """ - def __init__(self, sib, constr, gen_names, gens_syntax=None): + def __init__( + self, + sib: SageInputBuilder, + constr: SageInputExpression, + gen_names: tuple[str, ...], + gens_syntax: SageInputExpression | None = None, + ) -> None: r""" Initialize an instance of :class:`SIE_gens_constructor`. @@ -2707,10 +2751,10 @@ def __init__(self, sib, constr, gen_names, gens_syntax=None): {constr_parent: {subscr: {atomic:QQ}[{atomic:'x'}]} with gens: ('x',)} """ super().__init__(sib) - self._sie_constr = constr - self._sie_gen_names = gen_names - self._sie_gens = None # will be overwritten from .parent_with_gens() - self._sie_gens_constr = gens_syntax + self._sie_constr: SageInputExpression = constr + self._sie_gen_names: tuple[str, ...] = gen_names + self._sie_gens: list[SIE_gen] | None = None # will be overwritten from .parent_with_gens() + self._sie_gens_constr: SageInputExpression | None = gens_syntax self._sie_assign_gens = False self._sie_generated = False @@ -2731,7 +2775,7 @@ def __repr__(self): """ return "{constr_parent: %s with gens: %s}" % (repr(self._sie_constr), self._sie_gen_names) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_gens_constructor`. @@ -2754,7 +2798,7 @@ def _sie_referenced(self): # self._sie_gens_constr also occur in self._sie_constr. return [self._sie_constr] - def _sie_gens_referenced(self, sif): + def _sie_gens_referenced(self, sif: SageInputFormatter) -> None: r""" Mark that at least one of the generators in this :class:`SIE_gens_constructor` is used. (This means we will actually @@ -2781,7 +2825,7 @@ def _sie_gens_referenced(self, sif): for gen in self._sie_gens: gen._sie_require_varname(sif) - def _sie_add_command(self, sif): + def _sie_add_command(self,sif: SageInputFormatter) -> None: r""" Build commands to construct this parent and (if necessary) its associated generators. @@ -2859,7 +2903,7 @@ def _sie_add_command(self, sif): sif._commands += '%s = %s.gens()\n' % (','.join(g._sie_get_varname(sif) for g in self._sie_gens), self._sie_get_varname(sif)) self._sie_generated = True - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this parent-construction expression, and its precedence. @@ -2905,7 +2949,9 @@ class SIE_gen(SageInputExpression): {gen:x {constr_parent: {subscr: {atomic:ZZ}[{atomic:'x'}]} with gens: ('x',)}} """ - def __init__(self, sib, parent, name): + def __init__( + self, sib: SageInputBuilder, parent: SIE_gens_constructor, name: str + ) -> None: r""" Initialize an instance of :class:`SIE_gen`. @@ -2929,7 +2975,7 @@ def __init__(self, sib, parent, name): self._sie_parent = parent self._sie_preferred_varname = name - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representing this :class:`SIE_gen` value. @@ -2957,7 +3003,7 @@ def _sie_is_simple(self): """ return True - def _sie_prepare(self, sif): + def _sie_prepare(self, sif: SageInputFormatter) -> None: r""" We override the \method{_sie_prepare} method from :class:`SageInputExpression` to additionally mark the parent of this @@ -2979,7 +3025,7 @@ def _sie_prepare(self, sif): super()._sie_prepare(sif) self._sie_parent._sie_gens_referenced(sif) - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this named generator, and an indication that it is atomic. @@ -3003,7 +3049,7 @@ def _sie_format(self, sif): self._sie_parent._sie_add_command(sif) return self._sie_get_varname(sif), _prec_atomic - def _sie_got_preferred(self, sif): + def _sie_got_preferred(self, sif: SageInputFormatter) -> bool: r""" Check whether the :class:`SageInputFormatter` assigned us a variable name which is the same as the name of the generator @@ -3057,7 +3103,9 @@ class SIE_import_name(SageInputExpression): {import:sage.foo/happy as sad} """ - def __init__(self, sib, module, name, alt_name=None): + def __init__( + self, sib: SageInputBuilder, module: str, name: str, alt_name: str | None = None + ) -> None: r""" Initialize an instance of :class:`SIE_import_name`. @@ -3091,7 +3139,7 @@ def __init__(self, sib, module, name, alt_name=None): else: self._sie_preferred_varname = alt_name - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representing this :class:`SIE_import_name` value. @@ -3108,7 +3156,7 @@ def __repr__(self): return "{import:%s/%s%s}" % (self._sie_module_name, self._sie_object_name, "" if self._sie_object_name == self._sie_preferred_varname else " as %s" % self._sie_preferred_varname) - def _sie_is_simple(self): + def _sie_is_simple(self) -> Literal[True]: r""" Report that :class:`SIE_import_name` values are single tokens. @@ -3122,7 +3170,7 @@ def _sie_is_simple(self): """ return True - def _sie_prepare(self, sif): + def _sie_prepare(self, sif: SageInputFormatter) -> None: r""" We override the \method{_sie_prepare} method from :class:`SageInputExpression` to request a variable name. @@ -3143,7 +3191,7 @@ def _sie_prepare(self, sif): super()._sie_prepare(sif) self._sie_require_varname(sif) - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this import, and an indication that it is atomic. @@ -3191,7 +3239,7 @@ class SIE_assign(SageInputExpression): {assign: {getattr: {atomic:foo}.x} {atomic:pi}} """ - def __init__(self, sib, lhs, rhs): + def __init__(self, sib: SageInputBuilder, lhs: SageInputExpression, rhs: SageInputExpression) -> None: r""" Initialize an instance of :class:`SIE_assign`. @@ -3212,8 +3260,8 @@ def __init__(self, sib, lhs, rhs): {assign: {getattr: {atomic:foo}.x} {atomic:pi}} """ super().__init__(sib) - self._sie_lhs = lhs - self._sie_rhs = rhs + self._sie_lhs: SageInputExpression = lhs + self._sie_rhs: SageInputExpression = rhs def __repr__(self): r""" @@ -3229,7 +3277,7 @@ def __repr__(self): """ return "{assign: %s %s}" % (repr(self._sie_lhs), repr(self._sie_rhs)) - def _sie_referenced(self): + def _sie_referenced(self) -> list[SageInputExpression]: r""" Return a list of the immediate subexpressions of this :class:`SIE_assign`. @@ -3245,7 +3293,7 @@ def _sie_referenced(self): """ return [self._sie_lhs, self._sie_rhs] - def _sie_format(self, sif): + def _sie_format(self, sif: SageInputFormatter) -> tuple[str, int]: r""" Return the formatted string value of this :class:`SIE_assign` as an expression. Since an assignment is a statement, not @@ -3266,7 +3314,7 @@ def _sie_format(self, sif): """ raise ValueError("Cannot format SIE_assign as expression") - def _sie_format_statement(self, sif): + def _sie_format_statement(self, sif: SageInputFormatter) -> str: r""" Return the formatted string of this :class:`SIE_assign` as a statement. @@ -3300,11 +3348,11 @@ def __init__(self): sage: from sage.misc.sage_input import SageInputFormatter sage: sif = SageInputFormatter() """ - self._commands = '' - self._names = set() - self._dup_names = {} + self._commands: str = '' + self._names: set[str] = set() + self._dup_names: dict[str, int] = {} - def format(self, e, prec): + def format(self, e: SageInputExpression, prec: int) -> str: r""" Format a Sage input expression into a string. @@ -3381,7 +3429,7 @@ def format(self, e, prec): return formatted - def register_name(self, name): + def register_name(self, name: str | None) -> None: r""" Register that some value would like to use a given name. If only one request for a name is received, then we will use the @@ -3414,7 +3462,7 @@ def register_name(self, name): else: self._names.add(name) - def get_name(self, name): + def get_name(self, name: str | None) -> str: r""" Return a name corresponding to a given requested name. If only one request for a name is received, then we will use the @@ -3448,7 +3496,7 @@ def get_name(self, name): return name -def verify_same(a, b): +def verify_same(a, b) -> None: r""" Verify that two Sage values are the same. This is an extended equality test; it checks that the values are equal and that their parents are equal. @@ -3505,7 +3553,7 @@ def verify_same(a, b): raise AssertionError("Expected %r == %r" % (a, b)) -def verify_si_answer(x, answer, preparse): +def verify_si_answer(x: Any, answer: SageInputAnswer, preparse: bool | None): r""" Verify that evaluating ``answer`` gives a value equal to ``x`` (with the same parent/type). If ``preparse`` is ``True`` or @@ -3542,7 +3590,7 @@ def verify_si_answer(x, answer, preparse): verify_same(x, sage_eval(answer, preparse=preparse)) -class SageInputAnswer(tuple): +class SageInputAnswer(tuple[str, str, dict[str, Any]]): r""" This class inherits from tuple, so it acts like a tuple when passed to :func:`sage_eval`; but it prints as a sequence of commands. @@ -3573,7 +3621,7 @@ class SageInputAnswer(tuple): {'sin': } """ - def __new__(cls, cmds, expr, locals=None): + def __new__(cls, cmds: str, expr: str, locals: dict[str, Any] | None = None): r""" Construct an instance of :class:`SageInputAnswer`. @@ -3596,7 +3644,7 @@ def __new__(cls, cmds, expr, locals=None): else: return tuple.__new__(cls, (cmds, expr)) - def __repr__(self): + def __repr__(self) -> str: r""" Return a string representation for a :class:`SageInputAnswer`, such that if you evaluate this :class:`SageInputAnswer` at the diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx index b84b11336ec..f4c363495f5 100644 --- a/src/sage/modules/free_module_element.pyx +++ b/src/sage/modules/free_module_element.pyx @@ -129,6 +129,7 @@ from sage.rings.abc import RealDoubleField, ComplexDoubleField from sage.rings.integer cimport Integer, smallInteger from sage.arith.numerical_approx cimport digits_to_bits +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression # For the norm function, we cache Sage integers 1 and 2 __one__ = smallInteger(1) @@ -1259,7 +1260,7 @@ cdef class FreeModuleElement(Vector): # abstract base class return self return self.change_ring(R) - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/complex_interval.pyx b/src/sage/rings/complex_interval.pyx index b0b9f14263b..e137d8fa7c2 100644 --- a/src/sage/rings/complex_interval.pyx +++ b/src/sage/rings/complex_interval.pyx @@ -64,6 +64,7 @@ from sage.libs.flint.fmpz cimport * from sage.libs.mpfr cimport MPFR_RNDU from sage.arith.constants cimport LOG_TEN_TWO_PLUS_EPSILON +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.structure.element cimport FieldElement from sage.structure.parent cimport Parent from sage.rings.complex_mpfr cimport ComplexNumber @@ -1002,7 +1003,7 @@ cdef class ComplexIntervalFieldElement(FieldElement): """ raise TypeError - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/complex_interval_field.py b/src/sage/rings/complex_interval_field.py index c090d6cdae2..6ecef453c4c 100644 --- a/src/sage/rings/complex_interval_field.py +++ b/src/sage/rings/complex_interval_field.py @@ -34,9 +34,10 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** - +from __future__ import annotations import weakref +from typing import TYPE_CHECKING import sage.rings.abc from sage.misc.cachefunc import cached_method @@ -48,6 +49,9 @@ from sage.rings.ring import Field from sage.structure.parent import Parent +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + cache = {} @@ -295,7 +299,7 @@ def _magma_init_(self, magma): """ return "ComplexField(%s : Bits := true)" % self.prec() - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/complex_mpfr.pyx b/src/sage/rings/complex_mpfr.pyx index 11f58008fcf..1af71d838ff 100644 --- a/src/sage/rings/complex_mpfr.pyx +++ b/src/sage/rings/complex_mpfr.pyx @@ -33,6 +33,7 @@ import re import weakref import sage.misc.misc +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.libs.mpfr cimport * @@ -645,7 +646,7 @@ class ComplexField_class(sage.rings.abc.ComplexField): """ return "\\Bold{C}" - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -1071,7 +1072,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement): else: return numpy_object_interface - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/finite_rings/finite_field_base.pyx b/src/sage/rings/finite_rings/finite_field_base.pyx index d3aadd8d990..0e4e3b2b4f7 100644 --- a/src/sage/rings/finite_rings/finite_field_base.pyx +++ b/src/sage/rings/finite_rings/finite_field_base.pyx @@ -39,6 +39,7 @@ from sage.categories.finite_fields import FiniteFields from sage.misc.persist import register_unpickle_override from sage.misc.cachefunc import cached_method from sage.misc.prandom import randrange +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.rings.integer cimport Integer import sage.rings.abc @@ -269,7 +270,7 @@ cdef class FiniteField(Field): return "GF(%s,Variable=>symbol %s)" % (self.order(), self.variable_name()) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx index 768f2a75927..1fe8464b2b0 100644 --- a/src/sage/rings/finite_rings/integer_mod.pyx +++ b/src/sage/rings/finite_rings/integer_mod.pyx @@ -110,6 +110,7 @@ from sage.categories.morphism cimport Morphism from sage.categories.map cimport Map from sage.misc.persist import register_unpickle_override +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.structure.parent cimport Parent @@ -611,7 +612,7 @@ cdef class IntegerMod_abstract(FiniteRingElement): _fricas_init_ = _axiom_init_ - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/infinity.py b/src/sage/rings/infinity.py index ecf711d5fff..4a365034638 100644 --- a/src/sage/rings/infinity.py +++ b/src/sage/rings/infinity.py @@ -214,8 +214,10 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations from sys import maxsize +from typing import TYPE_CHECKING import sage.rings.abc @@ -230,6 +232,8 @@ lazy_import('sage.rings.integer', 'Integer') +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression _obj = {} @@ -542,7 +546,7 @@ def lcm(self, x): else: return abs(self) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: """ Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/integer.pyx b/src/sage/rings/integer.pyx index bdd2a7ce05b..a80d682bd4a 100644 --- a/src/sage/rings/integer.pyx +++ b/src/sage/rings/integer.pyx @@ -185,6 +185,8 @@ from sage.structure.richcmp cimport rich_to_bool_sgn from sage.rings import integer_ring +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + cimport gmpy2 gmpy2.import_gmpy2() @@ -6422,7 +6424,7 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement): return 'StringToInteger("%s",16)' % self.str(16) return str(self) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/integer_ring.pyx b/src/sage/rings/integer_ring.pyx index e6244e3fbc9..471db987f2c 100644 --- a/src/sage/rings/integer_ring.pyx +++ b/src/sage/rings/integer_ring.pyx @@ -65,9 +65,11 @@ from sage.structure.richcmp cimport rich_to_bool from sage.misc.misc_c import prod from sage.misc.randstate cimport randstate, current_randstate, SAGE_RAND_MAX +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.rings.integer cimport Integer + arith = None cdef void late_import() noexcept: # A hack to avoid circular imports. @@ -1525,7 +1527,7 @@ cdef class IntegerRing_class(CommutativeRing): sympy_init() return Integers - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index 6b4a8792edc..2778755d18c 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -128,6 +128,7 @@ from sage.misc.cachefunc import cached_function from sage.categories.map cimport Map from sage.categories.morphism cimport Morphism +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.misc.superseded import deprecation_cython as deprecation, deprecated_function_alias from sage.misc.cachefunc import cached_method @@ -3298,7 +3299,7 @@ cdef class Polynomial(CommutativePolynomial): return "0" return s[1:].lstrip().rstrip() - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/polynomial/polynomial_ring.py b/src/sage/rings/polynomial/polynomial_ring.py index 08c5a47c252..a7db4a64d40 100644 --- a/src/sage/rings/polynomial/polynomial_ring.py +++ b/src/sage/rings/polynomial/polynomial_ring.py @@ -137,9 +137,10 @@ # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** - +from __future__ import annotations import sys +from typing import TYPE_CHECKING from sage.misc.superseded import deprecation from sage.structure.element import Element @@ -180,6 +181,9 @@ import sage.interfaces.abc +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + def is_PolynomialRing(x): """ @@ -968,7 +972,7 @@ def _gap_init_(self) -> str: base_ring = self.base_ring()._gap_init_() return 'PolynomialRing(%s, ["%s"])' % (base_ring, self.variable_name()) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/qqbar.py b/src/sage/rings/qqbar.py index 996cea78a4f..96d328d76ff 100644 --- a/src/sage/rings/qqbar.py +++ b/src/sage/rings/qqbar.py @@ -579,9 +579,11 @@ - Carl Witty (2007-01-27): initial version - Carl Witty (2007-10-29): massive rewrite to support complex as well as real numbers """ +from __future__ import annotations import itertools import operator +from typing import TYPE_CHECKING import sage.rings.abc import sage.rings.number_field.number_field_base @@ -629,6 +631,9 @@ ) from sage.structure.sage_object import SageObject +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + class AlgebraicField_common(sage.rings.abc.AlgebraicField_common): r""" @@ -1200,7 +1205,7 @@ def _latex_(self): """ return "\\mathbf{A}" - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -1686,7 +1691,7 @@ def _latex_(self): """ return "\\overline{\\QQ}" - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -3870,7 +3875,7 @@ def _latex_(self): return latex(radical) return repr(self).replace('*I', r' \sqrt{-1}') - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -3918,7 +3923,7 @@ def _sage_input_(self, sib, coerce): {call: {getattr: {atomic:QQbar}.polynomial_root}({call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:QQbar}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}} {atomic:7}})}, {call: {atomic:CIF}({call: {atomic:RIF}({call: {atomic:RR}({atomic:2.6457513110645903})}, {call: {atomic:RR}({atomic:2.6457513110645907})})}, {call: {atomic:RIF}({call: {atomic:RR}({atomic:0})})})})} """ (v, complicated) = \ - self._descr.handle_sage_input(sib, coerce, self.parent() is QQbar) + self._descr.handle_sage_input(sib, coerced, self.parent() is QQbar) if complicated or True: sib.id_cache(self, v, 'v') return v @@ -6614,7 +6619,7 @@ def _repr_(self): """ return repr(self._value) - def handle_sage_input(self, sib, coerce, is_qqbar): + def handle_sage_input(self, sib: SageInputBuilder, coerce: CoercionMode, is_qqbar): r""" Produce an expression which will reproduce this value when evaluated, and an indication of whether this value is worth sharing (always @@ -6933,7 +6938,7 @@ def __reduce__(self): """ return (AlgebraicPolynomialTracker, (self._poly, )) - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -7181,7 +7186,7 @@ def _repr_(self): """ return 'Root %s of %s' % (self._interval, self._poly) - def handle_sage_input(self, sib, coerce, is_qqbar): + def handle_sage_input(self, sib: SageInputBuilder, coerce: CoercionMode, is_qqbar): r""" Produce an expression which will reproduce this value when evaluated, and an indication of whether this value is worth sharing (always ``True`` @@ -7858,7 +7863,7 @@ def _repr_(self): sgen, self._generator._interval_fast(53)) - def handle_sage_input(self, sib, coerce, is_qqbar): + def handle_sage_input(self, sib: SageInputBuilder, coerce: CoercionMode, is_qqbar): r""" Produce an expression which will reproduce this value when evaluated, and an indication of whether this value is worth sharing (always ``True`` @@ -8309,7 +8314,7 @@ def __reduce__(self): """ return (ANUnaryExpr, (self._arg, self._op)) - def handle_sage_input(self, sib, coerce, is_qqbar): + def handle_sage_input(self, sib: SageInputBuilder, coerce: CoercionMode, is_qqbar): r""" Produce an expression which will reproduce this value when evaluated, and an indication of whether this value is worth sharing (always @@ -8567,7 +8572,7 @@ def __reduce__(self): """ return (ANBinaryExpr, (self._left, self._right, self._op)) - def handle_sage_input(self, sib, coerce, is_qqbar): + def handle_sage_input(self, sib: SageInputBuilder, coerce: CoercionMode, is_qqbar): r""" Produce an expression which will reproduce this value when evaluated, and an indication of whether this value is worth sharing (always diff --git a/src/sage/rings/rational.pyx b/src/sage/rings/rational.pyx index 02fe3b23af0..e729aa9da30 100644 --- a/src/sage/rings/rational.pyx +++ b/src/sage/rings/rational.pyx @@ -77,7 +77,7 @@ from sage.structure.coerce cimport coercion_model, is_numpy_type from sage.structure.element cimport Element from sage.structure.parent cimport Parent from sage.structure.richcmp cimport rich_to_bool_sgn - +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression RealNumber_classes = () @@ -3845,7 +3845,7 @@ cdef class Rational(sage.structure.element.FieldElement): """ return '%s/%s' % (self.numerator(), self.denominator()) - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/rational_field.py b/src/sage/rings/rational_field.py index 582862f120a..a5ffac4ccf0 100644 --- a/src/sage/rings/rational_field.py +++ b/src/sage/rings/rational_field.py @@ -52,18 +52,24 @@ - Anna Haensch (2018-03): Added function ``quadratic_defect()`` """ +from __future__ import annotations + +from typing import TYPE_CHECKING from sage.rings.integer import Integer from sage.rings.rational import Rational ZZ = None -import sage.rings.number_field.number_field_base as number_field_base from sage.misc.fast_methods import Singleton from sage.misc.superseded import deprecated_function_alias +from sage.rings.number_field import number_field_base from sage.structure.parent import Parent from sage.structure.sequence import Sequence +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + class RationalField(Singleton, number_field_base.NumberField): r""" @@ -690,13 +696,12 @@ def places(self, all_complex=False, prec=None): from sage.rings.qqbar import QQbar as domain else: from sage.rings.qqbar import AA as domain + elif all_complex: + from sage.rings.complex_mpfr import ComplexField + domain = ComplexField(prec) else: - if all_complex: - from sage.rings.complex_mpfr import ComplexField - domain = ComplexField(prec) - else: - from sage.rings.real_mpfr import RealField - domain = RealField(prec) + from sage.rings.real_mpfr import RealField + domain = RealField(prec) return [self.hom([domain(1)])] def complex_embedding(self, prec=53): @@ -1583,12 +1588,13 @@ def _sympy_(self): sage: QQ._sympy_() # needs sympy Rationals """ - from sage.interfaces.sympy import sympy_init from sympy import Rationals + + from sage.interfaces.sympy import sympy_init sympy_init() return Rationals - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/real_double.pyx b/src/sage/rings/real_double.pyx index cac66b4ac75..d27591efbb0 100644 --- a/src/sage/rings/real_double.pyx +++ b/src/sage/rings/real_double.pyx @@ -60,6 +60,7 @@ from sage.rings.integer_ring import ZZ from sage.categories.morphism cimport Morphism from sage.structure.coerce cimport is_numpy_type from sage.misc.randstate cimport randstate, current_randstate +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.structure.richcmp cimport rich_to_bool from sage.arith.constants cimport * @@ -172,7 +173,7 @@ cdef class RealDoubleField_class(sage.rings.abc.RealDoubleField): """ return "\\Bold{R}" - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -981,7 +982,7 @@ cdef class RealDoubleElement(FieldElement): from sage.rings.real_mpfr import RR return RR(self._value)._mathematica_init_() - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/real_mpfi.pyx b/src/sage/rings/real_mpfi.pyx index 4d8dafa0515..063b7fac678 100644 --- a/src/sage/rings/real_mpfi.pyx +++ b/src/sage/rings/real_mpfi.pyx @@ -308,6 +308,7 @@ import operator from sage.cpython.string cimport char_to_str, bytes_to_str from sage.misc.superseded import deprecation +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression import sage.rings.infinity # **************************************************************************** @@ -655,7 +656,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField): """ return "\\Bold{I} \\Bold{R}" - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -1392,7 +1393,7 @@ cdef class RealIntervalFieldElement(RingElement): """ raise TypeError - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx index 10ff6b8baae..e8a1b6d90ea 100644 --- a/src/sage/rings/real_mpfr.pyx +++ b/src/sage/rings/real_mpfr.pyx @@ -142,6 +142,7 @@ from sage.libs.gmp.pylong cimport mpz_set_pylong from sage.libs.mpfr cimport * from sage.libs.mpmath.utils cimport mpfr_to_mpfval from sage.misc.randstate cimport randstate, current_randstate +from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression from sage.structure.element cimport Element from sage.structure.parent cimport Parent @@ -595,7 +596,7 @@ cdef class RealField_class(sage.rings.abc.RealField): """ return "\\Bold{R}" - def _sage_input_(self, sib, coerce): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. @@ -1685,7 +1686,7 @@ cdef class RealNumber(sage.structure.element.RingElement): """ return self.str(10, e='*^') - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: bool) -> SageInputExpression: r""" Produce an expression which will reproduce this value when evaluated. diff --git a/src/sage/sets/real_set.py b/src/sage/sets/real_set.py index 7f909c69655..8b4d8747109 100644 --- a/src/sage/sets/real_set.py +++ b/src/sage/sets/real_set.py @@ -96,18 +96,24 @@ class RealSet. # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** +from __future__ import annotations + from heapq import merge +from typing import TYPE_CHECKING from sage.categories.sets_cat import EmptySetError from sage.categories.topological_spaces import TopologicalSpaces from sage.rings.infinity import infinity, minus_infinity from sage.rings.integer_ring import ZZ -from sage.rings.real_lazy import LazyFieldElement, RLF -from sage.sets.set import Set_base, Set_boolean_operators, Set_add_sub_operators +from sage.rings.real_lazy import RLF, LazyFieldElement +from sage.sets.set import Set_add_sub_operators, Set_base, Set_boolean_operators from sage.structure.parent import Parent from sage.structure.richcmp import richcmp, richcmp_method from sage.structure.unique_representation import UniqueRepresentation +if TYPE_CHECKING: + from sage.misc.sage_input import CoercionMode, SageInputBuilder, SageInputExpression + @richcmp_method class InternalRealInterval(UniqueRepresentation, Parent): @@ -456,6 +462,7 @@ def _sympy_(self): Interval.open(0, oo) """ from sympy import Interval + from sage.interfaces.sympy import sympy_init sympy_init() return Interval(self.lower(), self.upper(), @@ -1209,7 +1216,7 @@ def __classcall__(cls, *args, **kwds): elif isinstance(arg, RealSet): intervals.extend(arg._intervals) elif isinstance(arg, Expression) and arg.is_relational(): - from operator import eq, ne, lt, gt, le, ge + from operator import eq, ge, gt, le, lt, ne def rel_to_interval(op, val): """ @@ -1258,7 +1265,9 @@ def rel_to_interval(op, val): else: raise ValueError(str(arg) + ' does not determine real interval') else: - from sage.manifolds.differentiable.examples.real_line import OpenInterval + from sage.manifolds.differentiable.examples.real_line import ( + OpenInterval, + ) from sage.manifolds.subsets.closure import ManifoldSubsetClosure if isinstance(arg, OpenInterval): lower, upper = RealSet._prep(arg.lower_bound(), arg.upper_bound()) @@ -2628,7 +2637,7 @@ def are_pairwise_disjoint(*real_set_collection): overlap_generator = RealSet._scan_to_intervals(scan, lambda i: i > 1) return next(overlap_generator, None) is None - def _sage_input_(self, sib, coerced): + def _sage_input_(self, sib: SageInputBuilder, coerced: CoercionMode) -> SageInputExpression: """ Produce an expression which will reproduce this value when evaluated. @@ -2668,11 +2677,10 @@ def interval_input(i): t = 'RealSet.closed' else: t = 'RealSet.closed_open' + elif i.upper_closed(): + t = 'RealSet.open_closed' else: - if i.upper_closed(): - t = 'RealSet.open_closed' - else: - t = 'RealSet.open' + t = 'RealSet.open' return sib.name(t)(sib(lower), sib(upper)) if self.is_empty(): @@ -2742,6 +2750,7 @@ def _sympy_(self): False """ from sympy import Reals, Union + from sage.interfaces.sympy import sympy_init sympy_init() if self.is_universe():