Import specific functions in order to reduce the startup time
The context
Let's suppose I want to create a simple script which only prints the prime factorization of the number 100. The script would look like
from sage.all import *
print(factor(100))
The problem
Executing that simple script takes a lot of time because there are plenty of modules that are expoted because of the from ... import
statemnt.
I tried finding the file in which the function factor
is defined and importing that specific module.
from sage.arith.misc import factor
print(factor(100))
However, this yields the following error.
Traceback (most recent call last):
File "/home/myusername/Experiments/factor-100.py", line 1, in <module>
from sage.arith.misc import factor
File "/usr/lib/python3.9/site-packages/sage/arith/misc.py", line 23, in <module>
from sage.libs.flint.arith import (bernoulli_number as flint_bernoulli,
File "sage/libs/flint/arith.pyx", line 1, in init sage.libs.flint.arith (build/cythonized/sage/libs/flint/arith.c:5015)
File "sage/rings/integer.pyx", line 1, in init sage.rings.integer (build/cythonized/sage/rings/integer.c:54202)
File "sage/rings/rational.pyx", line 95, in init sage.rings.rational (build/cythonized/sage/rings/rational.c:40423)
File "sage/rings/real_mpfr.pyx", line 1, in init sage.rings.real_mpfr (build/cythonized/sage/rings/real_mpfr.c:45462)
File "sage/libs/mpmath/utils.pyx", line 1, in init sage.libs.mpmath.utils (build/cythonized/sage/libs/mpmath/utils.c:9058)
File "sage/rings/complex_number.pyx", line 1, in init sage.rings.complex_number (build/cythonized/sage/rings/complex_number.c:26879)
File "sage/rings/complex_double.pyx", line 98, in init sage.rings.complex_double (build/cythonized/sage/rings/complex_double.c:25209)
ImportError: cannot import name complex_number
I can fix this problem by adding the following import
rule.
from sage.misc.all import *
from sage.arith.misc import factor
print(factor(100))
However, this also loads a lot of modules.
The question
Is it possible to import less modules than the last code block shown?