Question

Good time!

What is the best way to make a function that can be applied to one elements or to list of same elements? For example, I've got such func and I don't want to make map outside.

    def setName(self, name):

        if isinstance(name, list):
            return map(self.setName, name)
        else:
            self.names.append(name)
            return

For example, I don't know what to expect (string or list) and I need to make function multipurpose.

name = "a"
names = ["a", "b", "c"]
obj.setName(name)
obj.setName(names)

Are there some other (more optimal) ways to do it?

Was it helpful?

Solution

The best way I can think of is accepting variable number of arguments:

def setName(self, *names):
    for name in names:
        self.names.append(name)

And now you can call it with:

c.setName("Utku")

or

c.setName("Utku", "Onur")

or

names = ["Utku", "Onur"]
c.setName(*names)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top