Super Hrush
Super Hrush

Reputation: 181

Change function name in Python

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.

Upvotes: 3

Views: 835

Answers (1)

Richard K Yu
Richard K Yu

Reputation: 2202

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

Upvotes: 3

Related Questions