Reputation: 1123
First let me say I don't think it is a duplicate. I checked Ignore python multiple return value already. This isn't quite what I need.
So, I have a function f:
def f(parameters):
return a,b # returns two values
defined in module1.py
. Now, I want another class to be aware of this function, so I do:
import module1
Class MyClass:
def __init__(self):
self.function = module1.f
This, of course, happens in module2.py
. I need to call it in yet another module,
module3.py
like so:
import module2
instance = module2.MyClass()
otherFunction(args, instance.function )
Here's the catch: the second argument of otherFunction
has to be a function that returns a single value (currently, it returns two). I tried
import module1
Class MyClass:
def __init__(self):
self.function = module1.f[0]
But this does not work. Any ideas? I cannot change module3.py
. I can change the others but then I would have to do a bunch of changes to my project and this seems to be very painful.
I use python 2.6. I would be happy if whatever solution you find would also work for python3, though.
Upvotes: 2
Views: 95
Reputation: 1123
OK this might have been a dumb question:
In module1.py
I do:
def f(parameters):
retrun a,b # returns two values
def ff(parameters):
a, b = f(parameters)
return a
and use ff
instead of f
.
Upvotes: 0
Reputation: 3667
If you need to accept an arbitrary function then you could use lambdas or a wrapper function:
self.function = lambda *args: module1.f(*args)[0]
Otherwise, check out @Christian's answer.
Upvotes: 2
Reputation: 57570
Create a lambda that wraps around f
:
Class MyClass:
def __init__(self):
self.function = lambda parameters: module1.f(parameters)[0]
Upvotes: 1
Reputation: 34166
You can try using a decorator:
def mydecorator(f):
def w(*args, **kwargs):
r = f(*args, **kwargs)
return r[0]
return w
@mydecorator
def f(a, b):
return a + 2, b + 3 # returns two values
print f(1, 2) # 3
Upvotes: 2