Honeybear
Honeybear

Reputation: 3138

Can I reference or reuse a Python function parameter for other function parameters?

I'm creating a function taking one or two shape-lists A = [x1,y1,c1] / B = [x2,y2,c2] as input. If both shapes A and B are provided, each is used in one respective place A and B. If only one shape (A) is provided, by default the function implicitly uses it on both different places.

I solved this with an if-else construct:

def data_process(shape_A, shape_B = None):
  # ... some code ...
  res1 = process.shape(shape_A)    # shape A is always used
  if shape_B is not None:
      res2 = process.shape(shape_B)
  else: 
      res2 = process.shape(shape_A)
  return res1, res2

data_process(my_shape_A)  # call 1
data_process(my_shape_A, shape_B=my_shape_B)  # call 2

However I thought something much more elegant would be referencing shape_A as default in the function definition with shape_B = shape_A:

def data_process(shape_A, shape_B = shape_A):
  # ... some code ...
  res1 = process.shape(shape_A)    # shape_A is always used
  res2 = process.shape(shape_B)    # if shape_B not provided, shape_B = shape_A
  return res1, res2

Since simply doing it gives me the error that I'm referencing unknown variables, I was wondering: Is there a way to reference or reuse a Python function parameter for other function parameters (of the same function)?

This is just one straightforward use-case, but I think defaulting function parameters based on other function parameters would be quite useful to save a few lines of code.

Upvotes: 1

Views: 2069

Answers (2)

jpp
jpp

Reputation: 164623

I do not see anything wrong with your current code from a logic or efficiency perspective. There are some alternatives you can consider for aesthetic reasons only.

This assumes that a shape, if provided, is a tuple.

def data_process2(shape_A, shape_B=None):
    res1 = process.shape(shape_A)
    res2 = process.shape(shape_B if shape_B else shape_A)
    return res1, res2

def data_process3(shape_A, shape_B=None):
    if shape_B:
        shape_B = shape_A
    res1 = process.shape(shape_A)
    res2 = process.shape(shape_B)
    return res1, res2

Upvotes: 0

FHTMitchell
FHTMitchell

Reputation: 12147

No, there isn't. But whats wrong with

def data_process(shape_A, shape_B = None):
    if shape_B is None:
        shape_B = shape_A
    # rest of function not worrying about whether shape_B was passed or not

?

Upvotes: 1

Related Questions