1

Can I somehow refer to a method without using the lambda keyword?

Say we have following example code:

class AbstractDummy: def size(self): raise NotImplementedError class Dummy1(AbstractDummy): def size(self): return 10 class Dummy2(AbstractDummy): def size(self): return 20 

If I have my example objects:

dummies1 = [Dummy1(), Dummy1(), Dummy1()] dummies2 = [Dummy2(), Dummy2()] 

Then if I want to map them, and I can do that with extracted function parameter to save me some characters:

f = lambda x : x.size() map(f, dummies1) map(f, dummies2) 

Question here: can I somehow avoid this temporary f and/or lambda keyword?

To make a small comparison, in Java it would be possible to refer to AbstractDummy::size and so the invocation would look a bit like print(map(AbstractDummy::size, dummies1).

4
  • If you want this to work correctly, the lambda is the simplest way here. You cannot use AbstractDummy.size because that will always call the abstract-classes size method (because in Python, .size is just a regular function here). So the lambda is a perfectly sensible solution. Alternatively, you could use operator.methodcaller Commented Jan 13, 2020 at 22:28
  • 1
    Though if you are only assigning the lambda expression to a name, just use a def statement. Commented Jan 13, 2020 at 22:29
  • Note, idiomatic Python almost always prefers a list comprehension/ generator expression over an equivalent map. Guido actually wanted to remove map/filter/reduce and lambda from Python 3! The only times I use map are usually reserved for mapping simple built-in functions, so for number in map(int, user_input) for example... Commented Jan 13, 2020 at 22:35
  • Also note, in Python, methods only exist when they are called from an instance. Before that, they are simply regular functions existing in some class namespace. Note, a new method object is created on each invocation,so some_instance.some_method is some_instance.some_method will be false! Commented Jan 13, 2020 at 22:38

2 Answers 2

4

The operator module provides methodcaller for this.

from operator import methodcaller f = methodcaller('size') results1 = [f(x) for x in dummies1] results2 = [f(x) for x in dummies2] 

though [x.size() for x in ...] is simpler, as in C_Z_'s answer. methodcaller is useful for when you need a function as a function argument, for example

# Sort some_list_of_objects on return value of each object's `a` method. sorted_list = sorted(some_list_of_objects, key=methodcaller('a')) 
Sign up to request clarification or add additional context in comments.

Comments

4

In this case you would probably want to use a list comprehension

[x.size() for x in dummies1]

[x.size() for x in dummies2]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.