Best practice for reusing python code

Tyler Long picture Tyler Long · Aug 5, 2011 · Viewed 7.3k times · Source

I have write a python library app(which contains several *.py files). And several of my python projects need to reuse the code in the library app. What's the recommended best practice for reusing python code? Currently I have thought out three options:

  1. Copy and paste. This is far away from best practice. It violates the DRY principle.(Don't repeat yourself.)
  2. Add the folder of the library app to the environment variable PYTHONPATH: export PYTHONPATH=/path/to/library/app. Then every projects on the same computer can reference the code in the library app.
  3. And the folder of the library app to sys.path in python code: sys.path.append('/path/to/library/app')

Among the three options above which one do you prefer? What advantage does it have compared to the other two options? Do you have any other better options? It is much appreciated that if some one with years of python development experiences could answer this question.

Answer

Nicola Musatti picture Nicola Musatti · Aug 5, 2011

Allow me to propose a fourth alternative: take the time to learn how to package your library and install it in your site-packages; it's easier than one may think and I'm convinced it's time well spent. This is a very good starting point: https://packaging.python.org/en/latest/