3

Consider this example:

def foo():
    raise BaseException()

globals()["bar"] = foo
foo.__name__ = "bar"
# foo.__code__.co_name = "bar" # - Error: property is readonly

bar()

The output is:

Traceback (most recent call last):
  File "*path*/kar.py", line 9, in <module>
    bar()
  File "*path*/kar.py", line 2, in foo
    raise BaseException()
BaseException

How can I change the function name "foo" in the traceback? I already tried foo.__name__ = "bar", globals()["bar"] = foo and foo.__code__.co_name = "bar", but while the first two one just do nothing, the third one fails with AttributeError: readonly attribute.

1 Answer 1

3

Update: Changing function traceback name

You want to return a function with a different name within the function you call.

def foo():
    def bar():
        raise BaseException
    return bar

bar = foo()

bar()

Observe the following traceback: enter image description here

Old Answer: So I'm assuming your goal is to be able to call foo as bar with bar().

I think what you need to do is set the variable name equal to the function you want to call. If you define the variable above a function definition and outside of a function, then that variable is global (it can be used in subsequent function definitions).

See the following code and screenshot.

def foo():
    for i in range(1,11):
        print(i)


bar = foo #Store the function in a variable name = be sure not to put parentheses - that tells it to call!

bar() #call the function you stored in a variable name
print(bar) #print the function's location in memory to show that it is stored.

Let me know if you are trying to do something differently, or if you are just trying to store a function in a variable to be called later. enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

I would like to change the function name in the traceback or when printed, I believe its the same
@SuperHrush I have updated the answer so that the function name in the traceback is now bar, I have shown screenshot and code in update as well. Let me know if this is what you want / if you have any questions.
My main concern is changing function name in traceback using a string during runtime, not an identifier. I'm sorry if I didn't clarify this in my question properly.
That does not really answers my question, but with the help of this I found what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.