Commit | Line | Data |
---|---|---|
fbbe9302 SM |
1 | import bt2 |
2 | ||
3 | # Run callable `func` in the context of a component's __init__ method. The | |
4 | # callable is passed the Component being instantiated. | |
5 | # | |
6 | # The value returned by the callable is returned by run_in_component_init. | |
7 | ||
8 | def run_in_component_init(func): | |
9 | class MySink(bt2._UserSinkComponent): | |
10 | def __init__(self, params): | |
11 | nonlocal res_bound | |
12 | res_bound = func(self) | |
13 | ||
14 | def _consume(self): | |
15 | pass | |
16 | ||
17 | g = bt2.Graph() | |
18 | res_bound = None | |
19 | g.add_component(MySink, 'comp') | |
20 | ||
21 | # We deliberately use a different variable for returning the result than | |
22 | # the variable bound to the MySink.__init__ context and delete res_bound. | |
23 | # The MySink.__init__ context stays alive until the end of the program, so | |
24 | # if res_bound were to still point to our result, it would contribute an | |
25 | # unexpected reference to the refcount of the result, from the point of view | |
26 | # of the user of this function. It would then affect destruction tests, | |
27 | # for example, which want to test what happens when the refcount of a Python | |
28 | # object reaches 0. | |
29 | ||
30 | res = res_bound | |
31 | del res_bound | |
32 | return res | |
33 | ||
34 | # Create an empty trace class with default values. | |
35 | ||
36 | def get_default_trace_class(): | |
37 | def f(comp_self): | |
38 | return comp_self._create_trace_class() | |
39 | ||
40 | return run_in_component_init(f) |