Skip to content

Commit fa40444

Browse files
committed
Add shutil.umask context manager documentation
1 parent 45fb826 commit fa40444

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Doc/library/shutil.rst

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -877,6 +877,50 @@ Querying the size of the output terminal
877877
The ``fallback`` values are also used if :func:`os.get_terminal_size`
878878
returns zeroes.
879879

880+
.. _shutil-context-managers:
881+
882+
Context managers to modify process execution environments
883+
---------------------------------------------------------
884+
885+
High-level :term:`context managers <context manager>` for changing a process's execution environment.
886+
887+
.. warning::
888+
889+
These may change process-wide states, such as the current working directory,
890+
and as such are not suitable for use in most threaded or async contexts.
891+
They are also not suitable for most non-linear code execution, like generators,
892+
where the program execution is temporarily relinquished. Unless explicitly
893+
desired, you should not yield within these context managers.
894+
895+
.. class:: umask(mask)
896+
897+
This is a simple wrapper around :func:`os.umask`. It changes the process's
898+
umask upon entering and restores the old one on exit.
899+
900+
This context manager is :ref:`reentrant <reentrant-cms>`.
901+
902+
.. versionadded:: 3.14
903+
904+
In this example, we use a :class:`umask` context manager, within which we
905+
create a file that only the user can access::
906+
907+
>>> from shutil import umask
908+
>>> private_umask = umask(0o077)
909+
>>> with private_umask:
910+
... with open("my-secret-file", "w") as f:
911+
... f.write("I ate all the cake!\n")
912+
913+
The file's permissions are empty for anyone but the user:
914+
915+
.. code-block:: shell-session
916+
917+
$ ls -l my-secret-file
918+
-rw------- 1 jb2170 jb2170 20 Jan 2 01:23 my-secret-file
919+
920+
Using :class:`umask` like this is better practice than first creating the file,
921+
and later changing its permissions with :func:`~os.chmod`, between which a
922+
period of time exists in which the file may have too lenient permissions.
923+
880924
.. _`fcopyfile`:
881925
http://www.manpagez.com/man/3/copyfile/
882926

0 commit comments

Comments
 (0)