Ask Your Question
1

How can I distinguish between Sage and Python?

asked 2025-01-28 00:37:37 +0100

anonymous user

Anonymous

Is there a constant defined in SageMath that I can use to distinguish whether Sage is running or pure Python? Something that I can use like this:

SAGE = False
try:
    SAGE = ZZ
except NameError:
    pass
print(SAGE)

Contrary to my expectations, the Sage Cell Server outputs 'Integer Ring' in both cases.

edit retag flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted
3

answered 2025-01-29 03:40:59 +0100

It depends on what you mean by "Sage is running". If you mean, "have the standard Sage commands, etc., been imported and are ready for use," then you could test

import sys
if 'sage' in sys.modules:
    print('The Sage library has been imported')

This seems to be the case with the Sage Cell server for both Sage and Python: Sage has been imported in both cases. That's why your test isn't distinguishing the two. Along the same lines, print(sage.version.version) returns 10.2 in both Sage and Python on the Sage Cell server.

If you mean, "is Sage's preparser running," then the answer from @PedroBrazil is correct. In Python, ^ means bitwise exclusive or, while by default in Sage, ^ is exponentiation. The preparser can be turned off while still running Sage, though, so this is not a perfect test.

My guess is that the "Python" setting for the Sage Cell Server imports all of Sage and just turns off the preparser. So again, it depends on what you need to test, why you need to know whether it's Sage or Python.

edit flag offensive delete link more
2

answered 2025-01-28 11:51:17 +0100

PedroBrazil gravatar image

This 1-liner fulfills the purpose (tested with the Sage Cell Server).

def is_sage_running(): return 2^3 != 1
print(is_sage_running())
edit flag offensive delete link more
0

answered 2025-01-29 14:34:04 +0100

Peter Luschny gravatar image

Sage Math Server's behavior is clearly misleading the user and should be changed immediately.

def issage():
    try:
        import sage.all
        return True
    except ImportError:
        return False
print(issage())

This should work independent of the preparser.

edit flag offensive delete link more

Comments

1

This tests whether Sage can be imported, not whether it already has been, and furthermore it imports it if it can be: it has side effects.

John Palmieri gravatar imageJohn Palmieri ( 2025-01-29 17:55:59 +0100 )edit

That's right. Then it's not really any good.

Peter Luschny gravatar imagePeter Luschny ( 2025-01-30 00:25:34 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2025-01-28 00:37:37 +0100

Seen: 116 times

Last updated: Jan 29