Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - overload same function with different arguments

I have got a function that sets features and want to have two versions of it. One takes all features and splits them into words and phrases and the second one receives already split words and phrases as arguments

def set_features_2(self, words, phrases):
    self.vocabulary = set(words)
    self.phrases = SortedSet(phrases)

def set_features(self, features):
    phrases = [f for f in features if ' ' in f]
    words = [f for f in features if f not in phrases]
    self.set_features_2(words, phrases)

What is the easiest way to remove this duplication? Both of them should be called "set_features" but both receive a different set of arguments. I know that it is possible to use args and kwargs but it is an overkill for such as trivial case.

like image 212
Alicja Głowacka Avatar asked Oct 21 '25 20:10

Alicja Głowacka


1 Answers

You can't overload function arguments per se, but you can emulate this behavior with keyword arguments. The slightly annoying part is that you'd have to handle the validity checks (i.e., that the user doesn't pass both features and words and phases). E.g.:

def set_features(self, features = None, words = None, phrases = None):
    if features: 
        if words or phrases:
            raise ValueError('Either pass features or words and phrases')
        else:
            phrases = [f for f in features if ' ' in f]
            words = [f for f in features if f not in phrases]

    self.vocabulary = set(words)
    self.phrases = SortedSet(phrases)
like image 95
Mureinik Avatar answered Oct 24 '25 09:10

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!