how to inject a function?

One can inject variables using the inject_variable utility function:

from sage.misc.misc import inject_variable
inject_variable('foo', 'bar')


Now, how would it be possible to inject a function?

The context in which it is needed is the following one: I'm injecting the result of a resolution in the context as follow:

sol = solve([ ... ], f, g)
for s in sol[0]:
inject_variable(str(s.lhs()),s.rhs());


but now I need to define f and g as parametrized by i, and things like inject_variable(str(s.lhs())+'(i)',s.rhs()) don't seem to work.

edit retag close merge delete

Sort by ยป oldest newest most voted

It is not simple to understand the question.

Is for instance the following code injecting a function?

from sage.misc.misc import inject_variable
inject_variable( 'foo', lambda x, y: "%s is entering %s's bar" % ( x, y ) )
foo( 'Fangoraro', 'Harry' )


Result:

"Fangoraro is entering Harry's bar"


Also, one can inject many variables by using a fixed prefix and a numbered running suffix, e.g.

sage: for count in [1..999]:
....:     digits = count.digits( padto=3 )
....:     digits . reverse()
....:     inject_variable( "sol_%s" % ( ''.join( [str(d) for d in digits ] ) ), count^3 )
....:


This initializes a lot of variables, among them:

sage: sol_123
1860867
sage: sol_001
1
sage: sol_002
8


But why not use dictionaries instead? In fact, solve may even give the result in form of a dictionary, just use solution_dict=True. (And merge together all solution dictionaries with different keys. And keys may even be numbers, strings, tuples, or other immutable objects.)

more

Thanks. The lambda construct did the trick. Numbering running suffixes are not applicable in my case, neither are dictionaries since positional parameters aren't yet functions at the time of the solving.

( 2017-10-20 05:39:21 -0600 )edit

In this case, it may be that using exec and/or eval is also an alternative to generate dynamic code:

sage: del(foo)
sage: exec( """def foo(x,y): return "%s is entering %s's bar" % (x,y) """ )
sage: foo( 'Fangoraro', 'Harry' )
"Fangoraro is entering Harry's bar"

( 2017-10-20 06:00:41 -0600 )edit

Thanks, that's good to know.

( 2017-10-20 07:36:59 -0600 )edit