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

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
...
TypeError


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 close merge delete

Sort by » oldest newest most voted

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

more

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

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?

1

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)'