Return a function that do not create a new local scope. Given a function, create a clone of this function where the co_newlocal flag has been removed, making this function code actually run in the sourounding scope. We need this in order to run asynchronous code in user level nam
(function:types.FunctionType)
| 128 | #----------------------------------------------------------------------------- |
| 129 | |
| 130 | def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType: |
| 131 | """Return a function that do not create a new local scope. |
| 132 | |
| 133 | Given a function, create a clone of this function where the co_newlocal flag |
| 134 | has been removed, making this function code actually run in the sourounding |
| 135 | scope. |
| 136 | |
| 137 | We need this in order to run asynchronous code in user level namespace. |
| 138 | """ |
| 139 | from types import CodeType, FunctionType |
| 140 | CO_NEWLOCALS = 0x0002 |
| 141 | code = function.__code__ |
| 142 | new_co_flags = code.co_flags & ~CO_NEWLOCALS |
| 143 | if sys.version_info > (3, 8, 0, 'alpha', 3): |
| 144 | new_code = code.replace(co_flags=new_co_flags) |
| 145 | else: |
| 146 | new_code = CodeType( |
| 147 | code.co_argcount, |
| 148 | code.co_kwonlyargcount, |
| 149 | code.co_nlocals, |
| 150 | code.co_stacksize, |
| 151 | new_co_flags, |
| 152 | code.co_code, |
| 153 | code.co_consts, |
| 154 | code.co_names, |
| 155 | code.co_varnames, |
| 156 | code.co_filename, |
| 157 | code.co_name, |
| 158 | code.co_firstlineno, |
| 159 | code.co_lnotab, |
| 160 | code.co_freevars, |
| 161 | code.co_cellvars |
| 162 | ) |
| 163 | return FunctionType(new_code, globals(), function.__name__, function.__defaults__) |
| 164 | |
| 165 | |
| 166 | # we still need to run things using the asyncio eventloop, but there is no |