From 4c833319c9f3ed17e0dabe6a38f3718955ddf538 Mon Sep 17 00:00:00 2001 From: user202729 <25191436+user202729@users.noreply.github.com> Date: Sun, 22 Dec 2024 16:23:14 +0700 Subject: [PATCH] Refactor produce_latex_macro --- src/sage/misc/latex_macros.py | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/src/sage/misc/latex_macros.py b/src/sage/misc/latex_macros.py index fc389b32a72..1cce2fa6f14 100644 --- a/src/sage/misc/latex_macros.py +++ b/src/sage/misc/latex_macros.py @@ -43,6 +43,8 @@ contain '\newcommand' lines for each of the entries in ``macros``. """ +import importlib + def produce_latex_macro(name, *sample_args): r""" @@ -69,7 +71,7 @@ def produce_latex_macro(name, *sample_args): sage: produce_latex_macro('GF', 37) '\\newcommand{\\GF}[1]{\\Bold{F}_{#1}}' - If the Sage object is not in the global name space, describe it + If the Sage object is not in the global namespace, describe it like so:: sage: produce_latex_macro('sage.rings.finite_rings.finite_field_constructor.FiniteField', 3) @@ -84,22 +86,16 @@ def produce_latex_macro(name, *sample_args): else: module, real_name = names_split newcommand = '\\newcommand{\\' + real_name + '}' - count = 0 - args = "(" - for x in sample_args: - count += 1 - args += str(x) + ',' - args += ')' - exec('from ' + module + ' import ' + real_name) - if count: - defn = '[' + str(count) + ']{' - defn += eval('str(LatexCall()(' + real_name + args + '))') + '}' + sage_object = getattr(importlib.import_module(module), real_name) + if sample_args: + defn = '[' + str(len(sample_args)) + ']{' + defn += str(LatexCall()(sage_object(*sample_args))) + '}' else: - defn = '{' + eval('str(LatexCall()(' + real_name + '))') + '}' - count = 0 - for x in sample_args: - count += 1 - defn = defn.replace(str(x), "#" + str(count)) + defn = '{' + str(LatexCall()(sage_object)) + '}' + for i, x in enumerate(sample_args): + s = str(x) + assert s in defn + defn = defn.replace(s, "#" + str(i+1)) return newcommand + defn