Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I efficiently manage references between script files?

I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.

Currently, I have this:

import sys
sys.path.append('..//shared1//reusable_foo')
import Foo
sys.path.append('..//shared2//reusable_bar')
import Bar

My preference would be the following:

import Foo
import Bar

My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.

Does Python have equivalent support for this and, if not, what are some techniques and approaches?

like image 313
Ray Avatar asked Nov 13 '08 18:11

Ray


2 Answers

The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path.

You can also extend the search path by adding .pth files somewhere in your path. See https://docs.python.org/2/install/#modifying-python-s-search-path for more details

Oh, and python 2.6/3.0 adds support for PEP370, Per-user site-packages Directory

like image 88
JimB Avatar answered Sep 28 '22 09:09

JimB


If your reusable files are packaged (that is, they include an __init__.py file) and the path to that package is part of your PYTHONPATH or sys.path then you should be able to do just

import Foo

This question provides a few more details.

(Note: As Jim said, you could also drop your reusable code into your site-packages directory.)

like image 39
bouvard Avatar answered Sep 28 '22 09:09

bouvard