DEV Community

Shawn McElroy for Space Rock Media

Posted on

1 1

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?

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay