Ask Your Question

how to inject a function?

asked 2017-10-19 17:53:13 +0200

Claude Brisson gravatar image

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]:

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

1 Answer

Sort by ยป oldest newest most voted

answered 2017-10-20 02:21:25 +0200

dan_fulea gravatar image

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


"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
sage: sol_001
sage: sol_002

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

edit flag offensive delete link 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.

Claude Brisson gravatar imageClaude Brisson ( 2017-10-20 12:39:21 +0200 )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"
dan_fulea gravatar imagedan_fulea ( 2017-10-20 13:00:41 +0200 )edit

Thanks, that's good to know.

Claude Brisson gravatar imageClaude Brisson ( 2017-10-20 14:36:59 +0200 )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: 2017-10-19 17:53:13 +0200

Seen: 438 times

Last updated: Oct 20 '17