What are your favorite python tips you don't see others use?

autoferrit

Shawn McElroy

Posted on April 18, 2020

What are your favorite python tips you don't see others use?

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
Enter fullscreen mode Exit fullscreen mode

You can also call the method with named arguments

>>> triple = partial(multiply, y=3)
>>> triple(3)
9
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Pretty much anything in functools is great. you can find functool partial docs here

What are your favorite?

💖 💪 🙅 🚩
autoferrit
Shawn McElroy

Posted on April 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Lower bound on unitarity
jupyter Lower bound on unitarity

November 29, 2024

Thursday Quiz
python Thursday Quiz

October 31, 2024

List Comprehension and Regae
python List Comprehension and Regae

September 26, 2024

Elif or If; that is my question.
webdev Elif or If; that is my question.

October 26, 2024