AlanK
AlanK

Reputation: 9833

Dynamic method in python

I'm trying to create a method in python, which accepts 1-n number of parameters, calls the same method on each and returns the result. For example;

(Note this is pseudo code, I'm just typing these methods/syntax on the fly - new to python )

def get_pid(*params):
    pidlist = []
    for param in params:
        pidlist.add(os.getpid(param))
    return pidlist

Ideally I would like to do something like

x, y = get_pid("process1", "process2")

Where I can add as many parameters as I want - and the method to be as 'pythonic' and compact as possible. I think there may be a better way than looping over the parameters and appending to a list?

Any suggestions/tips?

Upvotes: 3

Views: 180

Answers (2)

dting
dting

Reputation: 39287

You can use yield to create a generator:

def get_pid(*params):
    for param in params:
        yield os.getpid(param)

x, y = get_pid("process1", "process2")
print(x, y)

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1122172

Your code already works. Your function accepts 0 or more arguments, and returns the results for each function call. There is but a minor mistake in it; you should use list.append(); there is no list.add() method.

You could use a list comprehension here to do the same work in one line:

def get_pid(*params):
    return [os.getpid(param) for param in params]

You could just inline this; make it a generator expression perhaps:

x, y = (os.getpid(param) for param in ("process1", "process2"))

You could also use the map() function for this:

x, y = map(os.getpid, ("process1", "process2"))

Upvotes: 6

Related Questions