3

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?

3
  • 1
    Your code already almost works as written, it is pidlist.append(), not .add(). Commented Oct 17, 2015 at 13:43
  • I come from a java background - I'm trying to get into the "python" way of thinking. Is there any way to improve on this code? I'd imagine the 4 lines can probably be changed to 1/2 lines Commented Oct 17, 2015 at 13:44
  • 2
    @Alan: that's true, you can make it more compact (via a listcomp or map or something) but please don't get in the habit of associating "pythonic" and "short". "Pythonic" doesn't mean "golfed", it means something more like "clear and straightforward". Commented Oct 17, 2015 at 13:48

2 Answers 2

6

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"))
Sign up to request clarification or add additional context in comments.

2 Comments

By the way, set has the set.add() method :)
@KevinGuan: sure, but that is neither here nor there when using a list. There are other Python objects that have .add methods too, but those are also not lists. :-P
4

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.