user defined modules
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:
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:
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:
but again, you should not mess with this unless you know what you are
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:
Apart from setting the PYTHONPATH environment variable, the best way to
add extra paths to is to install a .pth file. See here:
> Also, when does Python interpreter compile the module code? When it is
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:
Or just import the module from the interactive interpreter.
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson