I have two apps installed in my Django project...
Contacts Package
Models.py
- class Contact
Homes Package
Models.py
- class House
Class House has a model method called get_contact, in this method I import Contacts and filter etc (not important).
My question: House is now dependent on Contacts, meaning I can no longer install the House app without having the Contact app too. Despite this house should be able to exist without a Contact. In Python, (well in the context on the framework Django) how do you Python people deal with this?
Is there a better way?
If the use of the Contacts package in House is limited to a single method then you put the import inside the method and catch the exception:
def foo(self):
try:
from Contacts.Models import Contact
except ImportError:
return
... use Contact here
Alternatively you can put the import at the top of the module but set it to None in the case where it isn't available:
try:
from Contacts.Models import Contact
except ImportError:
Contact = None
...
if Contact is not None:
... use Contact ...
If you want to go a more pure OOP route, then you could use Zope3 adapters, but that means you've swapped dependency on one package for dependency on a group of others. It is likely to be overkill for the problem you've described, but if you want to investigate this solution see this blog post.
I think the real issue you will hit if you try this is that you'll have to define an interface such as IContactProvider that you can fetch for your House class. That interface has to live somewhere and if that somewhere is the Contacts package you still end up requiring that package to be installed. If your need is for some sort of generic IContactProvider and several specific implementations then this could be a good way of handling that problem.
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