diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 41e0a9538..5787370f5 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -11,8 +11,9 @@ jobs: build: runs-on: ubuntu-latest strategy: + # Add 3.15 below when mesonpy becomes available matrix: - python-version: ['3.14', '3.13', '3.12', '3.11'] + python-version: ['3.14', '3.13', '3.12'] steps: - uses: actions/checkout@v7 - name: Set up Python ${{ matrix.python-version }} diff --git a/mathics/core/definitions.py b/mathics/core/definitions.py index 8a68e262f..9dce4c9c4 100644 --- a/mathics/core/definitions.py +++ b/mathics/core/definitions.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Objects that represent the `Definition` associated with a `Symbol` and groups of `Definitions`. @@ -10,18 +9,9 @@ import pickle import re from collections import defaultdict -from itertools import chain, islice -from typing import ( - Dict, - Hashable, - Iterable, - List, - Optional, - Sequence, - Set, - Tuple, - Union, -) +from collections.abc import Hashable, Iterable, Sequence +from itertools import chain, islice, pairwise +from typing import Optional from mathics_scanner.tokeniser import full_names_pattern @@ -48,14 +38,14 @@ # More symbols are populated from FormMeta classes (see `mathics.builtin.forms.base`) # The contents of $BoxForms. -BOX_FORMS: Set[Symbol] = set() +BOX_FORMS: set[Symbol] = set() # The contents of $PrintForms. -PRINT_FORMS: Set[Symbol] = set() +PRINT_FORMS: set[Symbol] = set() # PRINT_FORMS.update(BOX_FORMS) # The contents of $OutputForms. -OUTPUT_FORMS: Set[Symbol] = set() +OUTPUT_FORMS: set[Symbol] = set() # OUTPUT_FORMS.update(PRINT_FORMS) @@ -67,56 +57,79 @@ class Definition: ``ownvalues``, ``upvalues``, ``downvalues``, ``subvalues``, ``nvalues``, ``format``, etc. """ + # Use slots for instance attributes. + # In contrast to the use of slots for atoms like Complex, or Integer, + # Benchmarking is not showing a visible improvement here. So this may be wishful thinking. + # We may remove the below assignment if it causes a problem. + __slots__ = ( + "_literal_index", + "attributes", + "builtin", + "changed", + "defaultvalues", + "downvalues", + "formatvalues", + "is_numeric", + "messages", + "name", + "nvalues", + "options", + "ownvalues", + "rule_index", + "subvalues", + "symbol", + "upvalues", + ) + def __init__( self, name, *, - rules_dict: Optional[dict] = None, - rules: tuple = tuple(), + rules_dict: dict | None = None, + rules: tuple = (), attributes: int = A_NO_ATTRIBUTES, builtin=None, is_numeric: bool = False, ) -> None: rules_dict = rules_dict or {} - self.name = name - self.symbol = Symbol(name) + + # Built lazily for rule lists that are large enough to benefit. + self._literal_index: dict | None = None + + self.attributes = attributes + self.builtin = builtin + self.changed = 0 self.defaultvalues = rules_dict.get("defaultvalues", []) self.downvalues = rules_dict.get("downvalues", []) self.formatvalues = rules_dict.get("formatvalues", {}) + self.is_numeric = is_numeric + self.messages = rules_dict.get("messages", []) + self.name = name self.nvalues = rules_dict.get("nvalues", []) - self.ownvalues = rules_dict.get("ownvalues", []) - self.subvalues = rules_dict.get("subvalues", []) - self.upvalues = rules_dict.get("upvalues", []) self.options: dict[str, BaseElement] = rules_dict.get("options", {}) - self.messages = rules_dict.get("messages", []) + self.ownvalues = rules_dict.get("ownvalues", []) # For each rule list, an index of its unconditional rules by the # fingerprint of their patterns, see ``insert_rule()``. It belongs to # the list object it was built for and is rebuilt when the list is # replaced. - self.rule_index: Dict[str, Tuple[list, dict]] = {} + self.rule_index: dict[str, tuple[list, dict]] = {} + + self.subvalues = rules_dict.get("subvalues", []) + self.symbol = Symbol(name) + self.upvalues = rules_dict.get("upvalues", []) - self.is_numeric = is_numeric - self.attributes = attributes - self.builtin = builtin - self.changed = 0 for rule in rules: if not self.add_rule(rule): print(f"{rule.pattern.expr} could not be associated with {self.name}") def __repr__(self) -> str: repr_str = ( - "" - ).format( - self.name, - self.ownvalues, - self.downvalues, - self.formatvalues, - self.attributes, + f"" ) return repr_str @@ -131,7 +144,7 @@ def add_rule(self, rule: BaseRule) -> bool: def add_rule_at(self, rule: BaseRule, rule_list_name: str) -> bool: """ - Add `rule` to the set of rules in field with attribute `rule_list_name` + Add `rule` to the set of rules in the field with the attribute `rule_list_name` """ values = self.get_values_list(rule_list_name) length = len(values) @@ -159,13 +172,16 @@ def get_rules_for( return index.rules_for(expression) def _get_literal_index( - self, rule_list_name: str, values: List[BaseRule] + self, rule_list_name: str, values: list[BaseRule] ) -> Optional["LiteralRuleIndex"]: """ The literal index of `values`, the rule list `rule_list_name`, built when first needed. None when the list can not be indexed. """ - cache = self.__dict__.setdefault("literal_index", {}) + cache = self._literal_index + if cache is None: + cache = self._literal_index = {} + entry = cache.get(rule_list_name) if entry is not None and entry[0] is values: return entry[1] @@ -176,7 +192,7 @@ def _get_literal_index( def _update_literal_index( self, rule_list_name: str, - values: List[BaseRule], + values: list[BaseRule], rule: BaseRule, replaced: bool, ) -> None: @@ -184,7 +200,7 @@ def _update_literal_index( Keep the literal index of `values` right after `rule` was inserted; `replaced` tells whether it took the place of an existing rule. """ - cache = self.__dict__.get("literal_index") + cache = self._literal_index if not cache or rule_list_name not in cache: return values_indexed, index = cache[rule_list_name] @@ -193,7 +209,7 @@ def _update_literal_index( if not (is_literal_rule(rule) and index.add(rule, replaced)): del cache[rule_list_name] - def get_rule_index(self, rule_list_name: str, values: List[BaseRule]) -> dict: + def get_rule_index(self, rule_list_name: str, values: list[BaseRule]) -> dict: """ Return the index of the unconditional rules in `values`, the rule list `rule_list_name`, by pattern fingerprint. @@ -204,7 +220,7 @@ def get_rule_index(self, rule_list_name: str, values: List[BaseRule]) -> dict: indexed = self.rule_index.get(rule_list_name) if indexed is not None and indexed[0] is values: return indexed[1] - index: Dict[Hashable, List[BaseRule]] = {} + index: dict[Hashable, list[BaseRule]] = {} for existing in values: if not is_conditional_rule(existing): index.setdefault(pattern_fingerprint(existing.pattern.expr), []).append( @@ -235,7 +251,8 @@ def remove_rule(self, lhs: BaseElement) -> bool: for index, existing in enumerate(values): if existing.pattern.expr.sameQ(lhs): del values[index] - self.__dict__.get("literal_index", {}).pop(position, None) + if self._literal_index is not None: + self._literal_index.pop(position, None) return True return False @@ -248,61 +265,94 @@ def set_values_list(self, pos: str, rules: list[BaseRule]) -> None: class Definitions: """The state of one instance of the Mathics3 interpreter is stored in this object. - The state is then stored as ``Definition`` object of the different - symbols defined during the runtime. + The state is then stored as ``Definition`` objects of the different + symbols defined during runtime. In the current implementation, the ``Definitions`` object stores - ``Definition`` s in four dictionaries: + ``Definition``s in four dictionaries: - builtins: stores the definitions of the ``Builtin`` symbols - pymathics: stores the definitions of the ``Builtin`` symbols added from pymathics modules. - - user: stores the definitions created during the runtime. - - definition_cache: keep definitions obtained by merging builtins, pymathics, and + - user: stores the definitions created during runtime. + - definition_cache: keeps definitions obtained by merging builtins, pymathics, and user definitions associated with the same symbol. Note: we want Rules to be serializable so that we can dump and - restore Rules in order to make startup time faster. + restore Rules to speed up startup time. """ + # Do not us slots for instance attributes for now. + # In contrast to the use of slots for atoms like Complex, or Integer, + # Benchmarking is not showing a visible improvement here. + # We might include the below assignment if there is some benefit. + # __slots__ = ( + # "_change_log", + # "_change_marks", + # "_packages", + # "boxforms", + # "builtin", + # "context_path", + # "current_context", + # "deferred_module_variables", + # "definitions_cache", + # "inputfile", + # "lookup_cache", + # "now", + # "outputforms", + # "printforms", + # "proxy", + # "pymathics", + # "timing_trace_evaluation", + # "trace_evaluation", + # "trace_show_rewrite", + # "user", + # ) + def __init__( self, add_builtin: bool = False, - builtin_filename: Optional[str] = None, + builtin_filename: str | None = None, extension_modules: tuple = (), ) -> None: - self._packages: List[str] = [] - self.builtin: Dict[str, Definition] = {} + + # Change tracking, see begin_change_tracking(): the value of `now` + # when each open tracking began, and the definitions changed since + # the outermost one began. + self._change_log: list[Definition] = [] + self._change_marks: list[int] = [] + + self._packages: list[str] = [] self.boxforms = list(BOX_FORMS) - self.context_path: Tuple[str, ...] = ( + self.builtin: dict[str, Definition] = {} + self.context_path: tuple[str, ...] = ( "System`", "Global`", ) self.current_context = "Global`" - self.definitions_cache: Dict[str, Definition] = {} - self.lookup_cache: Dict[str, str] = {} - self.now = 0 # increments whenever something is updated - # Change tracking, see begin_change_tracking(): the value of `now` - # when each open tracking began, and the definitions changed since - # the outermost one began. - self._change_marks: List[int] = [] - self._change_log: List[Definition] = [] + # The local variables of Modules that left the decision to remove # them to an enclosing Module (see Module.eval). - self.deferred_module_variables: List[str] = [] + self.deferred_module_variables: list[str] = [] + + self.definitions_cache: dict[str, Definition] = {} + self.inputfile = "" + self.lookup_cache: dict[str, str] = {} + self.now = 0 # increments whenever something is updated + self.outputforms = list(OUTPUT_FORMS) self.printforms = list(PRINT_FORMS) - self.proxy: Dict[str, Set[str]] = defaultdict(set) - self.pymathics: Dict[str, Definition] = {} - self.user: Dict[str, Definition] = {} - self.inputfile = "" + self.proxy: dict[str, set[str]] = defaultdict(set) + self.pymathics: dict[str, Definition] = {} self.timing_trace_evaluation = False - # TraceEvaluation uses these to - # decided what information to show + # TraceEvaluation uses trace_evaluation and trace_show_rewrite to + # decide what information to show. self.trace_evaluation = False self.trace_show_rewrite = False + self.user: dict[str, Definition] = {} + if add_builtin: load_builtin_definitions(self, builtin_filename, extension_modules) @@ -315,7 +365,7 @@ def add_default(self, name: str, rule: BaseRule) -> None: self.clear_definitions_cache(name) def add_format( - self, name: str, rule: BaseRule, form_names: Union[str, list] = "" + self, name: str, rule: BaseRule, form_names: str | list = "" ) -> None: """Add a format rule""" definition = self.get_user_definition(self.lookup_name(name)) @@ -344,9 +394,7 @@ def add_message(self, name: str, rule: BaseRule) -> None: self.mark_changed(definition) self.clear_definitions_cache(name) - def add_rule( - self, name: str, rule: BaseRule, position: Optional[str] = None - ) -> bool: + def add_rule(self, name: str, rule: BaseRule, position: str | None = None) -> bool: """Add a rule for the Symbol `name` in the list `pos`.""" definition = self.get_user_definition(self.lookup_name(name)) if position is None: @@ -373,7 +421,7 @@ def clear_attribute(self, name: str, attribute: int) -> None: self.mark_changed(definition) self.clear_definitions_cache(name) - def clear_cache(self, name: Optional[str] = None) -> None: + def clear_cache(self, name: str | None = None) -> None: """Clear the definitions cache. If `name` is provided, just remove the definition for `name` from the definition cache. """ @@ -427,7 +475,7 @@ def get_current_context(self) -> str: """Return a string with the current context""" return self.current_context - def get_context_path(self) -> Tuple[str, ...]: + def get_context_path(self) -> tuple[str, ...]: """return a tuple with the context path""" return self.context_path @@ -460,7 +508,7 @@ def get_names(self) -> set: def get_accessible_contexts(self) -> set: """Return the contexts reachable though $Context or $ContextPath.""" - accessible_ctxts = set(ctx for ctx in self.context_path) + accessible_ctxts = set(self.context_path) accessible_ctxts.add(self.current_context) return accessible_ctxts @@ -472,9 +520,7 @@ def get_attributes(self, name: str) -> int: """ return self.get_definition(name).attributes - def get_config_value( - self, name: str, default: Optional[int] = None - ) -> Optional[int]: + def get_config_value(self, name: str, default: int | None = None) -> int | None: "Infinity -> None, otherwise returns integer." try: value = self.get_ownvalue(name) @@ -486,7 +532,7 @@ def get_config_value( return None return int(value.to_python()) # .int_value) - def get_defaultvalues(self, name: str) -> List[BaseRule]: + def get_defaultvalues(self, name: str) -> list[BaseRule]: """Return the list of defaultvalues""" return self.get_definition(name).defaultvalues @@ -504,13 +550,13 @@ def get_definition(self, name: str, only_if_exists: bool = False) -> Definition: The name of the Symbol. only_if_exists : bool, optional If True, and the symbol was not already defined, raise a KeyError - exception. Otherwise, Creates a temporary Definition for + exception. Otherwise, creates a temporary Definition for the symbol, but does not store it. The default is False. Raises ------ KeyError - Raised when `name` has not a Definition, and `only_if_exists` + Raised when `name` has no definition, and `only_if_exists` is `True`. Returns @@ -558,7 +604,7 @@ def get_definition(self, name: str, only_if_exists: bool = False) -> Definition: return definition - def get_downvalues(self, name: str) -> List[BaseRule]: + def get_downvalues(self, name: str) -> list[BaseRule]: """Return the list of downvalues""" return self.get_definition(name).downvalues @@ -571,10 +617,10 @@ def get_rules_for( """ return self.get_definition(name).get_rules_for(rule_list_name, expression) - def get_formats(self, name: str, format_name="") -> List[BaseRule]: + def get_formats(self, name: str, format_name="") -> list[BaseRule]: """ Return a list of format rules associated with `name`. - if `format_name` is given, looks to the rules associated + If `format_name` is given, look at the rules associated to that format. """ formats = self.get_definition(name).formatvalues @@ -594,7 +640,7 @@ def get_line_no(self) -> int: """Get $Line, the current input line number""" return self.get_config_value("System`$Line", 1) or 1 - def get_matching_names(self, pattern: Union[str, re.Pattern]) -> List[str]: + def get_matching_names(self, pattern: str | re.Pattern) -> list[str]: """ Return a list of the symbol names matching a string pattern. @@ -635,8 +681,8 @@ def get_matching_names(self, pattern: Union[str, re.Pattern]) -> List[str]: else: short_pattern = pattern # start with a group matching the accessible contexts - ctx_pattern = "(?:%s)" % "|".join( - re.escape(c) for c in self.get_accessible_contexts() + ctx_pattern = "(?:{})".format( + "|".join(re.escape(c) for c in self.get_accessible_contexts()) ) short_pattern = ( @@ -648,7 +694,7 @@ def get_matching_names(self, pattern: Union[str, re.Pattern]) -> List[str]: return [name for name in self.get_names() if regex.match(name)] - def get_nvalues(self, name: str) -> List[BaseRule]: + def get_nvalues(self, name: str) -> list[BaseRule]: """Return the list of nvalues""" return self.get_definition(name).nvalues @@ -671,11 +717,11 @@ def get_ownvalue(self, name: str) -> BaseElement: raise ValueError # return None - def get_ownvalues(self, name: str) -> List[BaseRule]: + def get_ownvalues(self, name: str) -> list[BaseRule]: """Return the list of ownvalues""" return self.get_definition(name).ownvalues - def get_package_names(self) -> List[Optional[str]]: + def get_package_names(self) -> list[str | None]: """Return the list of names of the packages loaded in the system.""" try: packages = self.get_ownvalue("System`$Packages") @@ -690,11 +736,11 @@ def get_package_names(self) -> List[Optional[str]]: ] # return sorted({name.split("`")[0] for name in self.get_names()}) - def get_subvalues(self, name: str) -> List[BaseRule]: + def get_subvalues(self, name: str) -> list[BaseRule]: """Return the list of subvalues""" return self.get_definition(name).subvalues - def get_upvalues(self, name: str) -> List[BaseRule]: + def get_upvalues(self, name: str) -> list[BaseRule]: """Return the list of upvalues""" return self.get_definition(name).upvalues @@ -863,7 +909,7 @@ def change_tracking_open(self) -> bool: """Whether a change tracking (begin_change_tracking) is open.""" return bool(self._change_marks) - def end_change_tracking(self, token: int) -> List[Definition]: + def end_change_tracking(self, token: int) -> list[Definition]: """Close the tracking opened by begin_change_tracking() that returned `token`, and return the definitions changed since it began (possibly with repetitions, and possibly no longer in ``self.user``).""" @@ -948,7 +994,7 @@ def set_ownvalue(self, name: str, value) -> None: self.add_rule(name, RewriteRule(Symbol(symbol_name), value)) self.clear_cache(symbol_name) - def set_values(self, name: str, values: str, rules: List[BaseRule]) -> None: + def set_values(self, name: str, values: str, rules: list[BaseRule]) -> None: """Set a list of rules associated with the Symbol `name`""" pos = _valuesname(values) definition = self.get_user_definition(self.lookup_name(name)) @@ -1019,14 +1065,14 @@ def _valuesname(name: str) -> str: return name[7:].lower() -# FIXME: Return an enumeration, not a Optional[str]. +# FIXME: Return an enumeration, not an Optional[str]. def determine_value_role( pattern: BaseElement | BasePattern, target_symbol: Symbol -) -> Optional[str]: - """Determine the kind of Value (DownValue, OwnValue, UpValue, etc.) is getting - refered to for `target_symbol`. +) -> str | None: + """Determine the kind of Value (DownValue, OwnValue, UpValue, etc.) is being + referred to for `target_symbol`. - The return value either "downvalues", "nvalues", "ownvalues", + The return value is either "downvalues", "nvalues", "ownvalues", "subvalues", "upvalues", or None The following table indicates how we decide the Value "role" from @@ -1070,9 +1116,11 @@ def determine_value_role( return determine_value_role(pattern.get_elements()[1], target_symbol) if pattern.has_form(SymbolCondition, 2): return determine_value_role(pattern.get_elements()[0], target_symbol) - if pattern.has_form(BLANK_PATTERN_HEADS, 1): - if target_symbol is pattern.get_elements()[0]: - return "downvalues" + if ( + pattern.has_form(BLANK_PATTERN_HEADS, 1) + and target_symbol is pattern.get_elements()[0] + ): + return "downvalues" if pattern.has_form(SymbolVerbatim, 1): content = pattern.get_elements()[0] if target_symbol is content: @@ -1142,7 +1190,7 @@ def pattern_fingerprint(expr: BaseElement) -> Hashable: def insert_rule( - values: List[BaseRule], rule: BaseRule, index: Optional[dict] = None + values: list[BaseRule], rule: BaseRule, index: dict | None = None ) -> None: """ Add a new rule inside a list of values. @@ -1154,7 +1202,7 @@ def insert_rule( Parameters ---------- - values : List[Rule] + values : list[Rule] A list of rules. rule : Rule A new rule. @@ -1196,7 +1244,7 @@ def insert_rule( bisect.insort_left(values, rule, key=lambda x: x.pattern_precedence) -def find_rule(values: List[BaseRule], rule: BaseRule) -> Optional[int]: +def find_rule(values: list[BaseRule], rule: BaseRule) -> int | None: """ Return the position of the very object `rule` in `values`, or None. `values` is normally sorted by ``pattern_precedence`` (``insert_rule()`` @@ -1318,14 +1366,14 @@ def __init__(self, table: dict, others: list, other_keys: list): self.other_key_set = set(other_keys) @classmethod - def build(cls, values: List[BaseRule]) -> Optional["LiteralRuleIndex"]: + def build(cls, values: list[BaseRule]) -> Optional["LiteralRuleIndex"]: """The index of `values`, or None if it can not be indexed.""" try: keys = [rule.pattern_precedence for rule in values] - if any(later < earlier for earlier, later in zip(keys, keys[1:])): + if any(later < earlier for earlier, later in pairwise(keys)): return None - table: Dict[tuple, List[BaseRule]] = {} - others: List[BaseRule] = [] + table: dict[tuple, list[BaseRule]] = {} + others: list[BaseRule] = [] other_keys: list = [] # The sort keys of the literal rules; many literal rules # (f[1], f[2], ...) share one. It is only checked against the @@ -1392,7 +1440,7 @@ def add(self, rule: BaseRule, replaced: bool) -> bool: return True -def merge_definitions(candidates: List[Definition]) -> Definition: +def merge_definitions(candidates: list[Definition]) -> Definition: """Build a Definition object by merging other definitions""" rules: dict = { key: [] @@ -1412,7 +1460,7 @@ def merge_definitions(candidates: List[Definition]) -> Definition: is_numeric = first_candidate.is_numeric attributes = first_candidate.attributes builtin_instance = candidates[-1].builtin - formatvalues: Dict[str, List[BaseRule]] = {} + formatvalues: dict[str, list[BaseRule]] = {} options: dict = {} rules["formatvalues"] = formatvalues @@ -1437,7 +1485,7 @@ def merge_definitions(candidates: List[Definition]) -> Definition: # because of this, ``Unprotect[Expand]; ClearAll[Expand]; Options[Expand]`` # returns the builtin options of ``Expand`` instead of an empty list, like # in WMA. - # To get this behavior, we could just pick the options from the first + # To get this behavior, we could pick the options from the first # candidate. options.update(candidate.options) @@ -1453,11 +1501,11 @@ def merge_definitions(candidates: List[Definition]) -> Definition: def load_builtin_definitions( self: Definitions, - builtin_filename: Optional[str] = None, - extension_modules: tuple = tuple(), + builtin_filename: str | None = None, + extension_modules: tuple = (), ): """ - Load definitions from Builtin classes, autoload files and extension modules. + Load definitions from Builtin classes, autoload files, and extension modules. """ from mathics.core.load_builtin import ( definition_contribute, diff --git a/mathics/core/symbols.py b/mathics/core/symbols.py index a6acfdb09..aa9e4de69 100644 --- a/mathics/core/symbols.py +++ b/mathics/core/symbols.py @@ -1,8 +1,8 @@ # cython: language_level=3 -# -*- coding: utf-8 -*- import re import sys -from typing import TYPE_CHECKING, Any, ClassVar, FrozenSet, Iterable, Optional, cast +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any, ClassVar, cast from mathics.core.element import BaseElement, EvalMixin, ensure_context @@ -156,10 +156,10 @@ class Atom(BaseElement): _head_name = "" _symbol_head = None class_head_name: ClassVar[str] = "" - original: Optional["Atom"] = None + original: "Atom | None" = None def __repr__(self) -> str: - return "<%s: %s>" % (self.get_atom_name(), self) + return f"<{self.get_atom_name()}: {self}>" def atom_to_boxes(self, f, evaluation): """Produces a Box expression that represents @@ -182,7 +182,7 @@ def element_order(self) -> tuple: """ raise NotImplementedError - def equal2(self, rhs: Any) -> Optional[bool]: + def equal2(self, rhs: Any) -> bool | None: """Mathics3 two-argument Equal (==) returns True if self and rhs are identical. """ @@ -244,7 +244,7 @@ def get_symbol_definition_name(self) -> str: return self.class_head_name @property - def int_value(self) -> Optional[int]: + def int_value(self) -> int | None: return None @property @@ -257,8 +257,8 @@ def pattern_precedence(self) -> tuple: def has_form( self, - heads: Iterable["Symbol"] | "Symbol", - *element_counts: Optional[int], + heads: 'Iterable["Symbol"] | "Symbol"', + *element_counts: int | None, ) -> bool: # A symbol never has form head[...] return False @@ -339,7 +339,7 @@ class Symbol(Atom, NumericOperators, EvalMixin): """ # Declare slots for all instance attributes - __slots__ = ("_short_name", "name", "hash", "sympy") + __slots__ = ("_short_name", "hash", "name", "sympy") _short_name: str hash: int @@ -355,7 +355,7 @@ class Symbol(Atom, NumericOperators, EvalMixin): _symbols: ClassVar[dict[str, "Symbol"]] = {} class_head_name: ClassVar[str] = "System`Symbol" - sympy: Optional[Any] + sympy: Any | None # __new__ instead of __init__ is used here because we want # to return the same object for a given "name" value. @@ -424,7 +424,7 @@ def default_format(self, evaluation, form) -> str: def do_copy(self) -> "Symbol": return Symbol(self.name) - def equal2(self, rhs: Any) -> Optional[bool]: + def equal2(self, rhs: Any) -> bool | None: """Mathics3 two-argument Equal (==)""" if self is rhs: @@ -594,7 +594,7 @@ def pattern_precedence(self) -> tuple: Return a precedence value, a tuple, which is used in selecting which pattern to select when several match. """ - return super(Symbol, self).pattern_precedence + return super().pattern_precedence def replace_vars( self, vars: dict[str, BaseElement], options={}, in_function=True @@ -603,7 +603,7 @@ def replace_vars( # assert all(fully_qualified_symbol_name(v) for v in vars) return vars.get(self.name, self) - def round_to_float(self, evaluation=None) -> Optional[float]: + def round_to_float(self, evaluation=None) -> float | None: """ Round to a Python float. Return None if rounding is not possible. This can happen if self or evaluation is NaN. @@ -763,7 +763,7 @@ def is_literal(self) -> bool: return True -def symbol_set(*symbols: Symbol) -> FrozenSet[Symbol]: +def symbol_set(*symbols: Symbol) -> frozenset[Symbol]: """ Return a frozenset of symbols from a Symbol arguments. We will use this in testing membership, so an immutable object is fine. diff --git a/pyproject.toml b/pyproject.toml index 0adb6538e..d3c03d34d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,7 @@ dependencies = [ ] license = "GPL-3.0-or-later" name = "Mathics3" -requires-python = ">=3.11" +requires-python = ">=3.12" readme = "README.rst" keywords = ["Mathematica", "Wolfram", "Interpreter", "Shell", "Math", "CAS"] maintainers = [ @@ -52,7 +52,6 @@ classifiers = [ "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Programming Language :: Python", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", diff --git a/test/core/test_config_values.py b/test/core/test_config_values.py index cfe222b67..a3facdc19 100644 --- a/test/core/test_config_values.py +++ b/test/core/test_config_values.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ $RecursionLimit and $IterationLimit are looked up by their full names at each evaluation step, not resolved through $Context and $ContextPath. @@ -8,20 +7,20 @@ import pytest +from mathics.core.definitions import Definitions from mathics.core.interrupt import AbortInterrupt def test_limits_do_not_resolve_names(monkeypatch): - definitions = session.definitions looked_up = [] - original = definitions.lookup_name + original = Definitions.lookup_name - def recording(name): + def recording(self, name): if name in ("$RecursionLimit", "$IterationLimit"): looked_up.append(name) - return original(name) + return original(self, name) - monkeypatch.setattr(definitions, "lookup_name", recording) + monkeypatch.setattr(Definitions, "lookup_name", recording) session.evaluate("Do[cvF[i], {i, 50}]") assert looked_up == [] diff --git a/test/test_session.py b/test/test_session.py index 03744d9f4..e924ac665 100644 --- a/test/test_session.py +++ b/test/test_session.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- """ Basic tests for the MathicsSession class. """ - from mathics.core.atoms import Integer1, Integer2, IntegerM1 from mathics.core.evaluation import Result from mathics.core.expression import Expression