sympy.Function that returns a function

39 views
Skip to first unread message

Nico

unread,
Apr 5, 2016, 7:04:55 AM4/5/16
to sympy
So far, I've always defined functions as
```
class f(sympy.Function):
     pass
```
which I could then conveniently use as
```
x = sympy.Symbol('x')
y = f(x)
```
Nice.

Now, I would like to define a function that itself returns a function, aka, an operator. It should be used as
```
y = op(u)(x)
```
With the naïve definition above, I'm getting
```
TypeError: 'op' object is not callable
```
Any hints?

Cheers,
Nico

Aaron Meurer

unread,
Apr 5, 2016, 12:38:25 PM4/5/16
to sy...@googlegroups.com
It depends if you want op(u) to also be usable in expressions. If you
do, the simplest way is to make op be a Function, and define __call__
on it so that it returns an object representing op(u)(x).

Defining that other object is the tricky part. I think something like

class AppliedOp(Expr):
def __new__(cls, op, x):
obj = Expr.__new__(cls, op, x)
return obj

@property
def func(self):
return self._args[0]

@property
def args(self):
return self._args[1:]

and op is

class op(Function):
def __call__(self, x):
return AppliedOp(self, x)

You'll also want to define some printing methods on AppliedOp so that
it prints as op(u)(x).

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/aed8dedf-9b6c-468e-838a-ad56a659ddfe%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Nico

unread,
Apr 5, 2016, 2:01:40 PM4/5/16
to sympy
Thanks Anton for the tip!
I'll see what'll work best for me. (As a dirty workaround, I now defined the function to take two arguments, e.g., op(u, x).)

Cheers,
Nico

Aaron Meurer

unread,
Apr 5, 2016, 2:04:59 PM4/5/16
to sy...@googlegroups.com
If you don't need op(u) as a distinct expression that is way easier.
You can also define custom printing on it to make it display however
you want.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/d7f8ea86-e993-4499-a8d3-8fc7967c361c%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages