2

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.

Community
  • 1
  • 1
Yair Daon
  • 1,043
  • 2
  • 15
  • 27

4 Answers4

2

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
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

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.

djhoese
  • 3,567
  • 1
  • 27
  • 45
1

Create a lambda that wraps around f:

Class MyClass:

    def __init__(self):
        self.function = lambda parameters: module1.f(parameters)[0]
jwodder
  • 54,758
  • 12
  • 108
  • 124
0

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.

Yair Daon
  • 1,043
  • 2
  • 15
  • 27