Alicja Głowacka
Alicja Głowacka

Reputation: 411

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.

Upvotes: 4

Views: 7068

Answers (2)

Mureinik
Mureinik

Reputation: 311163

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)

Upvotes: 3

Paul Becotte
Paul Becotte

Reputation: 9977

Python allows default arguments.

def set_features(self, features=None, words=None, phrases=None):
    if features is not None:
        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)

you could then call it with set_features(features=features) or set_features(words=words, phrases=phrases)

Upvotes: 1

Related Questions