Python is a wonderful language. It is easy to learn but like many other languages it still takes time to master. There are many small things in python, whether builtin or as a package, that make our lives easier.
What tricks or features in python do you love to use that help you write more concise code, that you don't see others use often.
For me, one thing I love making use of is functools.partial
which can help you write code in a functional way, but also help make things simpler.
Namely, you can make common calls to other functions shorter if you will always call them with the same arguments.
>>> from functools import partial
>>> def multiply(x, y):
... return x * y
>>> # partial lets us make a new function, by calling the old function with set parameters.
>>> double = partial(multiply, 2)
>>> print(double(4))
8
You can also call the method with named arguments
>>> triple = partial(multiply, y=3)
>>> triple(3)
9
But be careful cause arguments are passed in order
>>> quad = partial(multiply, x=4)
>>> quad(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: multiply() got multiple values for argument 'x'
multiply() got multiple values for argument 'x'
Pretty much anything in functools
is great. you can find functool partial docs here
What are your favorite?
Top comments (0)