Added section on passing contextual information to logging and documentation for...
[python.git] / Doc / library / user.rst
blobaa09b67278c6ef81660504f459e3a9aba717c503
2 :mod:`user` --- User-specific configuration hook
3 ================================================
5 .. module:: user
6    :synopsis: A standard way to reference user-specific modules.
9 .. index::
10    pair: .pythonrc.py; file
11    triple: user; configuration; file
13 As a policy, Python doesn't run user-specified code on startup of Python
14 programs.  (Only interactive sessions execute the script specified in the
15 :envvar:`PYTHONSTARTUP` environment variable if it exists).
17 However, some programs or sites may find it convenient to allow users to have a
18 standard customization file, which gets run when a program requests it.  This
19 module implements such a mechanism.  A program that wishes to use the mechanism
20 must execute the statement ::
22    import user
24 .. index:: builtin: execfile
26 The :mod:`user` module looks for a file :file:`.pythonrc.py` in the user's home
27 directory and if it can be opened, executes it (using :func:`execfile`) in its
28 own (the module :mod:`user`'s) global namespace.  Errors during this phase are
29 not caught; that's up to the program that imports the :mod:`user` module, if it
30 wishes.  The home directory is assumed to be named by the :envvar:`HOME`
31 environment variable; if this is not set, the current directory is used.
33 The user's :file:`.pythonrc.py` could conceivably test for ``sys.version`` if it
34 wishes to do different things depending on the Python version.
36 A warning to users: be very conservative in what you place in your
37 :file:`.pythonrc.py` file.  Since you don't know which programs will use it,
38 changing the behavior of standard modules or functions is generally not a good
39 idea.
41 A suggestion for programmers who wish to use this mechanism: a simple way to let
42 users specify options for your package is to have them define variables in their
43 :file:`.pythonrc.py` file that you test in your module.  For example, a module
44 :mod:`spam` that has a verbosity level can look for a variable
45 ``user.spam_verbose``, as follows::
47    import user
49    verbose = bool(getattr(user, "spam_verbose", 0))
51 (The three-argument form of :func:`getattr` is used in case the user has not
52 defined ``spam_verbose`` in their :file:`.pythonrc.py` file.)
54 Programs with extensive customization needs are better off reading a
55 program-specific customization file.
57 Programs with security or privacy concerns should *not* import this module; a
58 user can easily break into a program by placing arbitrary code in the
59 :file:`.pythonrc.py` file.
61 Modules for general use should *not* import this module; it may interfere with
62 the operation of the importing program.
65 .. seealso::
67    Module :mod:`site`
68       Site-wide customization mechanism.