Ask Your Question

How does SageMath assign to a function call without raising an exception?

asked 2016-03-19 19:23:34 -0500

Pretty Antlers gravatar image

I can assign some functions to a function call like this:

sage: f(x) = cos(x)

But I can't assign other functions like this:

sage: f(x) = lambda x: 1

which happens to raise a different exception in Python:

>>> f(x) = lambda x: 1
SyntaxError: can't assign to function call

So, how does the SageMath interpreter change the behavior of Python?

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2016-03-20 08:18:24 -0500

The input f(x) = cos(x) is preparsed by Sage as follows.

sage: preparse('f(x) = cos(x)')
'__tmp__=var("x"); f = symbolic_expression(cos(x)).function(x)'

The following definition

sage: f = lambda x: 1

is synonymous with

sage: def f(x): return 1

If you want a symbolic function returning 1, see the discussion at

edit flag offensive delete link more

answered 2016-03-19 20:57:03 -0500

tmonteil gravatar image

When you write f(x) = cos(x), you define a symbolic expression. If you want to define a Python function, just do

sage:  f = lambda x: 1
edit flag offensive delete link more


The syntax f(x) = something is invalid in Python and SageMath uses iPython, so what kind of wizardry does SageMath use to make it valid?

Pretty Antlers gravatar imagePretty Antlers ( 2016-03-19 21:13:33 -0500 )edit

You can see it by means of the function preparse, which shows the action of Sage's preparser before moving to Python:

sage: preparse("f(x) = cos(x)")
'__tmp__=var("x"); f = symbolic_expression(cos(x)).function(x)'
eric_g gravatar imageeric_g ( 2016-03-20 08:05:34 -0500 )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


Asked: 2016-03-19 19:23:34 -0500

Seen: 143 times

Last updated: Mar 20 '16