4

Is there something like this:

a,b,c = a,b,c.method()

?

It's just an example, I want to know the shortest way to do this

3
  • 3
    Well, is a,b,c = (x.method() for x in (a,b,c)) good enough? Commented Jan 16, 2014 at 7:09
  • 2
    Just to be clear, you want to return the results of calling method() on each object back into the objects themselves? Commented Jan 16, 2014 at 7:09
  • Why not use lists? l2 = [x.method() for x in l1] might be a good way to do what you need. Commented Jan 16, 2014 at 7:14

3 Answers 3

7

Not exactly that short, but if I understand you correct, this will work:

a, b, c = (x.method() for x in (a, b, c))

(Note, that if a, b or c are referring to the same object, the method will be called few times).

Sign up to request clarification or add additional context in comments.

Comments

6

Not short. But here's an alternative using operator.methodcaller.

a, b, c = map(operator.methodcaller('method'), (a,b,c))

Example:

>>> import operator
>>> a, b, c = [1,2,3], [4,5,6], [7,8,9]
>>> a, b, c = map(operator.methodcaller('pop'), (a,b,c))
>>> a
3
>>> b
6
>>> c
9

>>> m = operator.methodcaller('pop') # If you call `method` multiple times,
                                     #   keep a reference to the methodcaller
>>> a, b, c = [1,2,3], [4,5,6], [7,8,9]
>>> a, b, c = map(m, (a,b,c))
>>> a
3
>>> b
6
>>> c
9

If all objects are same type, you can use unbound method. For example a, b, c here all list instances. So you can use list.pop instead of operator.methodcaller('pop').

For example:

>>> a, b, c = [1,2,3], [4,5,6], [7,8,9] # a, b, c are all `list` objects.
>>> a, b, c = map(list.pop, (a,b,c))
>>> a
3
>>> b
6
>>> c
9

2 Comments

__neg__ is not a so good example - one would better use operator.neg in this case. Nevertheless, +1.
Oops!! a, b, c = map(list.pop, (a, b, c)) is possible.
1

Using a generator would be the simplest way. For example, if a, b, and c were strings:

a, b, c = 'asdf', 'quer', 'zxcv'

And you wanted to capitalize the beginning of each string, you can do:

a, b, c = (x.capitalize() for x in (a, b, c))

2 Comments

This method is already suggested by bereal. Please do not duplicate the answer without providing additional information.
Sorry. Everyone please look in the comments of the original question for a generalized solution by bereal

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.