Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic method in python

Tags:

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?

like image 946
AK47 Avatar asked Dec 25 '22 13:12

AK47


2 Answers

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"))
like image 95
Martijn Pieters Avatar answered Jan 09 '23 18:01

Martijn Pieters


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)
like image 23
dting Avatar answered Jan 09 '23 18:01

dting