beardc
beardc

Reputation: 21063

Possible to change function name in definition?

I tried several ways to change the function name in the definition, but they failed.

>>> def f():
        pass
>>> f.__name__
'f'
>>> def f():
        f.__name__ = 'new name'
>>> f.__name__
'f'
>>> def f():
        self.__name__ = 'new name'
>>> f.__name__
'f'

But I can change the name attribute after defining it.

>>> def f():
        pass
>>> f.__name__ = 'new name'
>>> f.__name__
'new name'

Any way to change/set it in the definition (other than using a decorator)?

Upvotes: 14

Views: 33355

Answers (5)

Rusty Rob
Rusty Rob

Reputation: 17173

This is probably stupid but kinda works?

>>> f = None
>>> def new_name():
    global f
    f = new_name


>>> new_name()
>>> f
<function new_name at 0x01945108>
>>> f.__name__
'new_name'

Upvotes: 0

Ben
Ben

Reputation: 71450

If you put it in the function body, you're saying that part of the execution of f is setting its name to 'new name'. Obviously that's not going to do anything before the function has been called.

Using a decorator is the canonical way to declare that a function is a bit different than its def block alone would indicate, and you're not going to find anything better.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318508

The function body is not executed until you execute the function. You could use a decorator though:

def rename(newname):
    def decorator(f):
        f.__name__ = newname
        return f
    return decorator

And then use it like this:

@rename('new name')
def f():
    pass
print f.__name__

However, the function is still only reachable as f.

Upvotes: 31

BrenBarn
BrenBarn

Reputation: 251383

The function body is not executed until you call the function, so there's no way you can use the function body to alter what happens at definition time. Why do you want to do this anyway? If you're writing the function and want it to have a different name, just define it with a different name.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

No. The closest you can come to this is defining a callable class with each instance having its __name__ set in the initializer.

Upvotes: 3

Related Questions