Apply multiple methods to a single object?

While saving outputs in a data structure to check posteriorly. The methods return strings (parsing or selecting HTML, they don't modify the object).

I've found a "hard-coded" solution by creating a class which is not very motivating for now: call list of function using list comprehension.

[Maybe another Library for checking libraries would be an extreme. I tried to put a few print in Python source but it didn't obey me. It seems that another instance is running]

I've tried this syntax (not possible):

result = [obj.f() for f in [append, attrs]] 

because append and attrs aren't static functions by default but 'dotted' as showed above.

The goal is just a simple check of all obj methods.

[edits are highly recommended]

Update

In [122]: getattr? Docstring: getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. Type: builtin_function_or_method enter image description here getattr(): attribute name must be string enter image description here Only 2 works. It is the "result" to get (not hard-coding it) enter image description here More information for 'model' as an object.

Upvotes: 1

Views: 1231

Answers (1)

chepner
chepner

Reputation: 532053

You want either bound methods:

result = [f() for f in [obj.append, obj.attrs]]

or dynamic attribute lookup via either getattr:

result = [getattr(obj, m)() for m in ["append", "attrs"]]

If you plan to do this for a lot of objects, you might want to use operator.methodcaller:

methods = [methodcaller(m) for m in ["append", "attrs"]]
results_for_obj_a = [f(obj_a) for f in methods]
results_for_obj_b = [f(obj_b) for f in methods]
# etc.

methodcaller is a way of abstracting the idea of calling a method away from any particular object.

methodcaller(method_name)(obj) == getattr(obj, method_name)()

Upvotes: 1

Related Questions