Skip to content

Commit df59fde

Browse files
committed
Add example usage of umask_of to write permission-agnostic code
1 parent 0ff7997 commit df59fde

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

Doc/library/shutil.rst

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -915,13 +915,39 @@ The file's permissions are empty for anyone but the user:
915915

916916
.. code-block:: shell-session
917917
918-
$ ls -l my-secret-file
919-
-rw------- 1 guest guest 20 Jan 1 23:45 my-secret-file
918+
$ ls -l my-secret-file
919+
-rw------- 1 guest guest 20 Jan 1 23:45 my-secret-file
920920
921921
Using :class:`umask_of` like this is better practice than first creating the file,
922922
and later changing its permissions with :func:`~os.chmod`, between which a
923923
period of time exists in which the file may have too lenient permissions.
924924

925+
It also allows you to write code that creates files, in a way that is agnostic
926+
of permissions -- that is without the need to pass a custom ``mode`` keyword
927+
argument to :func:`open` every time.
928+
929+
In this example we create files with a function ``touch_file`` which uses the
930+
:func:`open` built-in without setting ``mode``. Permissions are managed by
931+
:class:`!umask_of`:
932+
933+
.. code-block:: pycon
934+
935+
>>> from shutil import umask_of
936+
>>>
937+
>>> def touch_file(path):
938+
... with open(path, "a"):
939+
... pass
940+
...
941+
>>> touch_file("normal-file")
942+
>>> with umask_of(0o077):
943+
... touch_file("private-file")
944+
945+
.. code-block:: shell-session
946+
947+
$ ls -l normal-file private-file
948+
-rw-r--r-- 1 guest guest 0 Jan 1 23:45 normal-file
949+
-rw------- 1 guest guest 0 Jan 1 23:45 private-file
950+
925951
.. _`fcopyfile`:
926952
http://www.manpagez.com/man/3/copyfile/
927953

0 commit comments

Comments
 (0)