I’m wondering if you could, instead of using eval to make functions with the right names, allocate some function objects and assign strings to their name (or is it func_name?) attribute? Or is that one read-only? I remember some of the attributes of function objects are read-only but not all of them are.
In Python 2.7, you can do this by constructing a new code object and assigning it to a function’s func_code attribute. The function’s func_name is ignored by the traceback generation. Still, no eval necessary!
$ python2 maketraceback.py
Traceback (most recent call last):
File "maketraceback.py", line 27, in <module>
bar()
File "bar.rs", line 4, in bar
File "foo.rs", line 3, in foo
IndexError: 0
For Python3, there’s one extra argument to the CodeType constructor, so it’s just:
$ python3 maketraceback3.py
Traceback (most recent call last):
File "maketraceback3.py", line 29, in <module>
bar()
File "bar.rs", line 4, in bar
File "foo.rs", line 3, in foo
IndexError: 0
I’m wondering if you could, instead of using eval to make functions with the right names, allocate some function objects and assign strings to their name (or is it func_name?) attribute? Or is that one read-only? I remember some of the attributes of function objects are read-only but not all of them are.
In Python 2.7, you can do this by constructing a new code object and assigning it to a function’s func_code attribute. The function’s func_name is ignored by the traceback generation. Still, no eval necessary!
Running this:
with python2.7 gives me this output:
For Python3, there’s one extra argument to the CodeType constructor, so it’s just:
and output looks the same:
Yes, this is what I’m planning for the next post :)