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