Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for reusing python code [closed]

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.

like image 419
Tyler Liu Avatar asked Aug 05 '11 13:08

Tyler Liu


People also ask

What is the best way to reuse lines of code Python?

And when it comes to reusing code in Python, it all starts and ends with the humble function. Take some lines of code, give them a name, and you've got a function (which can be reused). Take a collection of functions and package them as a file, and you've got a module (which can also be reused).

What are the benefits of reusing existing code?

Code reuse aims to save time and resources and reduce redundancy by taking advantage of assets that have already been created in some form within the software product development process.

What is code reusability in Python?

A Python function can be defined once and used many times. So it aids in code reuse: you don't want to write the same code more than once. Functions are a great way to keep your code short, concise, and readable.


2 Answers

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/

like image 161
Nicola Musatti Avatar answered Sep 17 '22 12:09

Nicola Musatti


Of your three options, PYTHONPATH is the way to go. Copy & paste is clearly out, and adding code to your other projects to modify sys.path simply pollutes those files with knowledge about their environment.

A fourth option is, create a true installable package from your common code, and install it into your Python installation. Then you can simply import those modules like any other 3rd-party install code.

like image 25
Ned Batchelder Avatar answered Sep 19 '22 12:09

Ned Batchelder