user defined modules
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Jun 5 03:32:09 EDT 2018
On Mon, 04 Jun 2018 20:13:32 -0700, Sharan Basappa wrote:
> Is there a specific location where user defined modules need to be kept?
> If not, do we need to specify search location so that Python interpreter
> can find it?
Python modules used as scripts can be run from anywhere, by pointing the
interpreter at the script:
python /path/to/my/script.py
But Python modules uses as libraries, to be imported by other modules,
have to be on the Python search path. You can add extra paths to the
Python search path from the shell by setting the environment variable
PYTHONPATH to a colon-separated list of paths. On Linux, I do this in
my .bashrc config file:
export PYTHONPATH="paths:to:add"
In the Python interpreter, you can query and modify the search path by
importing sys and looking at sys.path. (But you should not do so unless
you really know what you are doing.)
The default search path is set by the site module:
https://docs.python.org/3/library/site.html
but again, you should not mess with this unless you know what you are
doing.
There are some per-user directories which are automatically added to the
search path. I can't find the existing documentation for them, but a good
place to start is the PEP that introduced the feature:
https://www.python.org/dev/peps/pep-0370/
Apart from setting the PYTHONPATH environment variable, the best way to
add extra paths to is to install a .pth file. See here:
https://pymotw.com/2/site/#path-configuration-files
> Also, when does Python interpreter compile the module code? When it is
> imported?
Yes. Executing a module as a script does not compile it. But when it is
imported, it will be compiled to byte-code the first time, and then the
byte-code will be used.
You can force the compilation using the compileall:
https://docs.python.org/3/library/compileall.html
Or just import the module from the interactive interpreter.
--
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson
More information about the Python-list
mailing list