One cool use of functools.partial

The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.

Instead of using lot of os.path.join This pattern is much more useful and more so if you want to use the path multiple times. Discovered this very recently and I am delighted to use this from now onwards

>>> import functools
>>> import os
>>> user_path = functools.partial(os.path.join, r"C:\Users\sukhbinder")
>>> print(user_path)
functools.partial(<function join at 0x00000169E056BCA0>, 'C:\\Users\\sukhbinder')
>>> d = user_path("Desktop")
>>> d
>>> d = user_path("Desktop", "PROJECTS")
>>> d
>>> d = user_path("Desktop", "PROJECTS", "winsay")
>>> d
>>> d = user_path("..","Desktop", "PROJECTS", "winsay")
>>> d

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s