Writing effective functions
April 2, 2015
For readability
- Use variable arguments where possible e.g.
def foo(*args)
- Use
foo(*arg_list)
when calling functionfoo
which unpacks the list of arguments.
- Specify keyword arguments when changing default values in a function call rather than positional defaults.
- def foo(a,b, c=10, d=True) So, when you call it foo(3,4, c=20,d=False).
- Python 3 syntactically can force keyword only arguments by using * as one of the arguments, enforcing all the arguments that follow to be keyword only
- def foo(a,b,*, c=10, d=True) Python 3 syntax– force keyword-only args.
For performance:
Return generators rather than a list. Few advantages:
- No memory running out issue
- Less lines of code
- More readable
def load(cities):
out = []
for city in cities:
out.append(city)
return out
Replace the lines struck out with,
yield city
.
In the first implementation, you would get all the cities by:
result = load(cities)
print result
And the second, we wouldnt need to store all the cities in memory. Instead you would use it as needed by calling it as follows:
print next(result)