[Tutor] accessing modules found throughout a package?

Martin A. Brown martin at linux-ip.net
Sun Oct 18 14:15:23 EDT 2015


Hello Alex,

>>>> How does one arrange so "the top level directory _can_ be found within
>>>> Python's path."?
>>>
>>> Is the answer to include the following at the beginning of each file?
>>>
>>> if not 'path/to/top/level/package/directory' in sys.path:
>>>     sys.path.append('path/to/top/level/package/directory')
>>
>> You could, but you can also add it to your PYTHONPATH environment variable.
>
> It seems to not exist:
> (venv)alex at x301:~/Py/CSV/debk$ echo $PYTHONPATH
>
> Should I add the following to the end of my ~/.bashrc file?
> export PYTHONPATH="$PYTHONPATH:/home/alex/Py"

Quite possibly.  You can test it out easily as follows to be 
certain that this allows you to import your Python easily.

  $ PYTHONPATH=/home/alex/Py python
  >>> import something_you_wrote

If that works, then, yes.  See also the docs [0].

This should certainly be suitable for personal work.

<detour type="shell">

It is generally polite to prefix any existing value of PYTHONPATH 
before adding your own.  For a possibly esoteric improvement, you 
might consider a little shell refinement to avoid leaving any empty 
path in the variable.  What do I mean?  After the fragment in your 
.bashrc (assuming PYTHONPATH remains unset before the above line 
runs), you will end up with:

  PYTHONPATH=:/home/alex/Py

Oops!  There's an empty path in there in the first position.  A 
minor improvement would be to only prepend the PYTHONPATH and 
required colon if there's a value to PYTHONPATH already.  So, this 
little beautifully obnoxious bash parameter expansion gem will 
accomplish that for you:

  PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/home/alex/Py"

</detour>

Good luck,

-Martin

 [0] https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list