0

I have a function which take countries argument

getStats(countries=['France','Spain','Italy','US'])

I want to reuse exactly the same function but I would like to change the name argument countries to regions

getStats(regions=['New York','Boston','San Francisco'])

What is the good way to proceed ? Is it a decorator case ?

5
  • Check answers. Commented Jun 11, 2020 at 20:58
  • 1
    What about simply renaming the parameter? Maybe something broader like locations? Or can you not edit the function? Commented Jun 11, 2020 at 21:05
  • And don't use lists as default arguments: stackoverflow.com/questions/1132941/… Commented Jun 11, 2020 at 21:06
  • Is countries/regions the only argument to the function? Commented Jun 11, 2020 at 21:12
  • @khelwood, in fact there are more than one argument getStats(countries=['France','Spain','Italy','US'], type=type which=['l1','l2','l3'], output='pandas') Commented Jun 11, 2020 at 21:25

1 Answer 1

1

How would the function know which list to use in the default case getStats()? Assuming your function works exactly the same with countries and regions and you want to supply defaults for both, then make them lists outside the function that a user can apply. As mentioned, the parameter name can be more vague getStats(location) and require a list, but the user has handy default ones available.

countries = ['France','Spain','Italy','US']
regions = ['New York','Boston','San Francisco'])

def getStats(location):
    """Get stats for location. Default `countries` and `regions` lists
    available."""
    ....

Or, if you prefer, define multiple functions that call the common one.

def getStatsByCountry(countries=['France','Spain','Italy','US']):
    return getStats(countries)

def getStatsByRegion(regions=['New York','Boston','San Francisco']):
    return getStats(regions)
Sign up to request clarification or add additional context in comments.

1 Comment

use location instead of countries and regions is a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.