Reputation: 26406
My goal is to use the same function from multiple classes in Python.
I've seen discussion about mixins and inheritance etc but they all seem to come with caveats and cautions about doing things just right.
So I wondered if I could just call another plain old function that lives outsides the classes. It seems to work, but maybe I'm failing to understand something important?
So my question is - is this a valid approach to sharing a function between Python classes?
def clean_reference_url(self):
if not self.cleaned_data['reference_url']:
return ''
try:
if 'illegaltext' in self.cleaned_data['reference_url']:
raise Exception
except:
raise forms.ValidationError('You cannot put illegaltext in this field.')
return self.cleaned_data['reference_url']
class ContactForm(forms.ModelForm):
def clean_reference_url(self):
return clean_reference_url(self)
class TripForm(forms.ModelForm):
def clean_reference_url(self):
return clean_reference_url(self)
Upvotes: 0
Views: 51
Reputation: 155584
It's valid, but it's unnecessary to have the extra layer of wrapping. The mix-in approach is the simplest, but yes, it has some caveats (largely related to metaclasses), so if you want to avoid that, you can still set a method in multiple classes by just setting during the definition of each class. Keep the function definition the same, and change the classes to:
class ContactForm(forms.ModelForm):
clean_reference_url = clean_reference_url
class TripForm(forms.ModelForm):
clean_reference_url = clean_reference_url
Again, a mixin is even cleaner, e.g.:
class CleanableUrl: # Change name as appropriate
def clean_reference_url(self):
# ...
class ContactForm(CleanableUrl, forms.ModelForm):
# No need to talk about clean_reference_url at all
class TripForm(CleanableUrl, forms.ModelForm):
# No need to talk about clean_reference_url at all
and it's usually the most Pythonic approach, assuming it works for your scenario (no conflicting metaclasses on the base types).
Upvotes: 4