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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.