The Path.mkdir method creates a directory, and with parents=True it also creates any missing directories above it. The mode argument sets the permissions of the new directory, but not of the parents. Before Python 3.15, there was no way to choose what permissions those parents received.
For example, a directory intended to be private is created inside two parents that do not exist yet:
from pathlib import Path
Path('data/cache/secrets').mkdir(mode=0o700, parents=True)
ls -ld data data/cache data/cache/secrets
drwxr-xr-x 3 john john 4096 Nov 4 15:05 data
drwxr-xr-x 3 john john 4096 Nov 4 15:05 data/cache
drwx------ 2 john john 4096 Nov 4 15:05 data/cache/secrets
The final directory is private, but the two above it are readable and traversable by everyone. Making the whole chain private meant creating it first and then walking back up to call chmod on each level, which also left the directories briefly at the wrong permissions.
Since Python 3.15, the parent_mode argument sets the permissions of the parent directories:
from pathlib import Path
Path('data/cache/secrets').mkdir(mode=0o700, parents=True, parent_mode=0o700)
drwx------ 3 john john 4096 Nov 4 15:05 data
drwx------ 3 john john 4096 Nov 4 15:05 data/cache
drwx------ 2 john john 4096 Nov 4 15:05 data/cache/secrets
Every directory in the chain is now created with the permissions given, in a single call and without a separate pass to correct them afterwards. The argument is keyword-only and has an effect only together with parents=True.
The same argument is available on os.makedirs, which accepts parent_mode in the same keyword-only position and produces identical results.
Leave a Comment
Cancel reply