blob: ba9426210ad3f3cc905ca68aa47e6337e489f86c [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`user` --- User-specific configuration hook
3================================================
4
5.. module:: user
6 :synopsis: A standard way to reference user-specific modules.
7
8
9.. index::
10 pair: .pythonrc.py; file
11 triple: user; configuration; file
12
13As a policy, Python doesn't run user-specified code on startup of Python
14programs. (Only interactive sessions execute the script specified in the
15:envvar:`PYTHONSTARTUP` environment variable if it exists).
16
17However, some programs or sites may find it convenient to allow users to have a
18standard customization file, which gets run when a program requests it. This
19module implements such a mechanism. A program that wishes to use the mechanism
20must execute the statement ::
21
22 import user
23
24.. index:: builtin: exec
25
26The :mod:`user` module looks for a file :file:`.pythonrc.py` in the user's home
27directory and if it can be opened, executes it (using :func:`exec`) in its
28own (the module :mod:`user`'s) global namespace. Errors during this phase are
29not caught; that's up to the program that imports the :mod:`user` module, if it
30wishes. The home directory is assumed to be named by the :envvar:`HOME`
31environment variable; if this is not set, the current directory is used.
32
33The user's :file:`.pythonrc.py` could conceivably test for ``sys.version`` if it
34wishes to do different things depending on the Python version.
35
36A 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,
38changing the behavior of standard modules or functions is generally not a good
39idea.
40
41A suggestion for programmers who wish to use this mechanism: a simple way to let
42users 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::
46
47 import user
48
49 verbose = bool(getattr(user, "spam_verbose", 0))
50
51(The three-argument form of :func:`getattr` is used in case the user has not
52defined ``spam_verbose`` in their :file:`.pythonrc.py` file.)
53
54Programs with extensive customization needs are better off reading a
55program-specific customization file.
56
57Programs with security or privacy concerns should *not* import this module; a
58user can easily break into a program by placing arbitrary code in the
59:file:`.pythonrc.py` file.
60
61Modules for general use should *not* import this module; it may interfere with
62the operation of the importing program.
63
64
65.. seealso::
66
67 Module :mod:`site`
68 Site-wide customization mechanism.
69