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 ?

olivier dadoun
  • 622
  • 6
  • 22
  • [Check answers](https://stackoverflow.com/questions/41784308/keyword-arguments-aliases-in-python). – Olvin Roght Jun 11 '20 at 20:58
  • 1
    What about simply renaming the parameter? Maybe something broader like `locations`? Or can you not edit the function? – wjandrea Jun 11 '20 at 21:05
  • And don't use lists as default arguments: https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – Klaus D. Jun 11 '20 at 21:06
  • Is `countries`/`regions` the only argument to the function? – khelwood Jun 11 '20 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') – olivier dadoun Jun 11 '20 at 21:25

1 Answers1

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)
tdelaney
  • 73,364
  • 6
  • 83
  • 116