0

To make a simple example, I don't care about the practicality, just the implemenation. Say I create some class with a few methods. I want to create a list containing whether or not they're callable. So I can take this example from: Finding what methods an object has

[method for method in dir(object) if callable(getattr(object, method))] 

It's great for what it does, but if for the heck of it, I want to use map and I have object, which is a non-iterable item...

map(callable,map(getattr,object,dir(object)))

To focus on the real problem:

I have an iterable list, and a non iterable item. What is the best solution that lets me use some non-iterable item and an iterable item, so that I can utilize map?

Community
  • 1
  • 1
pyInTheSky
  • 1,459
  • 1
  • 9
  • 24

3 Answers3

4

I will admit to not understanding why, since the LC works, but:

map(lambda x: callable(getattr(object, x)), dir(object))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

If you're not clear on what the lambda above does, equivalently you could define:

def myMap(fun1,obj,iterlist):
        def fun2(x):
            return fun1(obj,x)
        return map(fun2,iterlist)

And then, call

map(callable,myMap(getattr,object,dir(object)))

for example:

map(callable,myMap(getattr,myMap,dir(myMap)))

Though using lambda is more pythonic.

highBandWidth
  • 16,751
  • 20
  • 84
  • 131
0

Sometime LC is just the right way to do it

>>> from itertools import izip, repeat, starmap
>>> map(callable, starmap(getattr, zip(repeat(object), dir(object))))

This also works, but requires dir(object) twice

>>> map(callable, map(getattr, repeat(object, len(dir(object))), dir(object)))

and finally

>>> from itertools import izip_longest
>>> map(callable, starmap(getattr, izip_longest([], dir(object), fillvalue=object)))
John La Rooy
  • 295,403
  • 53
  • 369
  • 502