I'm currently maintaining two of my own applications. They both share some common aspects, and as a result, share some code. So far, I've just copied the modules from one project to the other, but now it's becoming a maintenance issue. I'd rather have the common code in one place, outside of both of the projects, which they can both import. Then, any changes to the common code would be reflected in both project.
My question is: how can I do this? Do I create a library out of this code? If so, how do the dependent projects use the library? I think one thing I struggle with here is that the common code isn't really useful to anyone else, or at least, I don't want to make it a supported modules that other people can use.
If my question isn't clear, please let me know.
There is nothing special you have to do, Python just needs to find your module. This means that you have to put your common module into your PYTHONPATH , or you add their location to sys. path .
Setup.py allows you to create a custom Python package enabling you to share code easily within a project. Simply structure your sub-projects and shared code into folders containing an __init__.py and direct your setup.py 's setup() to install the code contained within shared code folder.
There is nothing special you have to do, Python just needs to find your module. This means that you have to put your common module into your PYTHONPATH
, or you add their location to sys.path
. See this.
Say you have
~/python/project1
~/python/project2
~/python/libs/stuff.py
~/python/libs/other.py
You can either set PYTHONPATH='~/python/libs'
in your os enviroment, or you can do
import sys, os
sys.path.append(os.path.expanduser('~/python/libs')) # or give the full path
After that you can do import stuff, other
anywhere.
You can also package your stuff, then you need a layout like this:
~/python/project1
~/python/project2
~/python/libs/mylibname/__init__.py
~/python/libs/mylibname/stuff.py
~/python/libs/mylibname/other.py
~/python/libs/mylibname/__init__.py
must exist, but it can be a empty file. It turns mylibname
into a package.
After adding the libs folder to your path as above, you can do from mylibname import stuff, other
.
There are a lot of ways to factor code so it is reusable. It really depends on your specific situation as far as what will work best. Factoring your code into separate packages and modules is always a good idea, so related code stays bundled together and can be reused from other packages and modules. Factoring your code into classes within a module can also help in keeping related code grouped together.
I would say that putting common code into a module or package that is on your PYTHONPATH and available to both applications would probably be your best solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With