Constructor. See class doc string.
(self, stmt="pass", setup="pass", timer=default_timer,
globals=None)
| 99 | """ |
| 100 | |
| 101 | def __init__(self, stmt="pass", setup="pass", timer=default_timer, |
| 102 | globals=None): |
| 103 | """Constructor. See class doc string.""" |
| 104 | self.timer = timer |
| 105 | local_ns = {} |
| 106 | global_ns = _globals() if globals is None else globals |
| 107 | init = '' |
| 108 | if isinstance(setup, str): |
| 109 | # Check that the code can be compiled outside a function |
| 110 | compile(setup, dummy_src_name, "exec") |
| 111 | stmtprefix = setup + '\n' |
| 112 | setup = reindent(setup, 4) |
| 113 | elif callable(setup): |
| 114 | local_ns['_setup'] = setup |
| 115 | init += ', _setup=_setup' |
| 116 | stmtprefix = '' |
| 117 | setup = '_setup()' |
| 118 | else: |
| 119 | raise ValueError("setup is neither a string nor callable") |
| 120 | if isinstance(stmt, str): |
| 121 | # Check that the code can be compiled outside a function |
| 122 | compile(stmtprefix + stmt, dummy_src_name, "exec") |
| 123 | stmt = reindent(stmt, 8) |
| 124 | elif callable(stmt): |
| 125 | local_ns['_stmt'] = stmt |
| 126 | init += ', _stmt=_stmt' |
| 127 | stmt = '_stmt()' |
| 128 | else: |
| 129 | raise ValueError("stmt is neither a string nor callable") |
| 130 | src = template.format(stmt=stmt, setup=setup, init=init) |
| 131 | self.src = src # Save for traceback display |
| 132 | code = compile(src, dummy_src_name, "exec") |
| 133 | exec(code, global_ns, local_ns) |
| 134 | self.inner = local_ns["inner"] |
| 135 | |
| 136 | def print_exc(self, file=None): |
| 137 | """Helper to print a traceback from the timed code. |