I am trying to specify which variables a function should return. The purpose of this is to allow the function to return different sets of variables according to the requirements of another function, in order to make things more efficient (rather than always returning all the variables):

# Python 2.6
def myfunc(arg1, arg2):
    x = 2
    y = 3
    z = 4
    return arg1

print myfunc('x, y', arg2) #would return: 2, 3
print myfunc('y, z', arg2) #would return: 3, 4

arg2 is another argument separate from the variable list that I am trying to return. Any suggestions?

bdesc100
Deleted Member

Looks like I found my own answer, was so close:

# Python 2.6
def myfunc(arg1, arg2):
    x = 2
    y = 3
    z = 4
    return eval(arg1)
 
print myfunc('x, y', arg2) # returns: 2, 3
print myfunc('y, z', arg2) # returns: 3, 4

It's not a very good function interface. You should not need to pass the names of variables local to the function. The question is rather when and why you want to return either x and y or y and z.

Totally agree with Gribouillis. This is not a good way of doing things. Many problems may occur.
You may use a dictionnary instead:

def myfunc(arg1, arg2):
    d={'x':2, 'y':3, 'z':4}
    return d[arg1], d[arg2] 
 
print myfunc('x', 'y') # returns: 2, 3
print myfunc('y', 'z') # returns: 3, 4

But in this case, you should even imagine args are not what you are waiting for

def myfunc(arg1, arg2):
    d={'x':2, 'y':3, 'z':4}
    try:
        a=d[arg1]
    except KeyError:
        a="%s not handled" % arg1
    try:
        b=d[arg2]
    except KeyError:
        b="%s not handled" % arg2
    return a,b
 
print myfunc('x', 'y') # returns: 2, 3
print myfunc('y', 'z') # returns: 3, 4
print myfunc('g', 'z') # surprise

Of course what I do here in the try except blocks may be very different depending on your needs.
You also don't need to have 2 differents blocks

Edited 7 Years Ago by jice: n/a

The cure seems worse than the disease.

have you actually tried returning a tuple of all results and the caller just picking the ones it needs?

- Paddy.

This question has already been answered. Start a new discussion instead.