Home > Net >  Rename a function
Rename a function

Time:03-28

Let's say I want to rename a function like "print" into "bark". Is there a way to do that?

I found information on how to apply another name to a library, but that's it. And don't ask about the question, the "bark" idea is just an example. I remember you can do something like that in C# and wonder if Python is an exception.

CodePudding user response:

You can change the "name" of the function assigning it to an other variable, since in Python functions are objects.

>>> def foo(): pass
>>> foo
<function foo at 0x0000021C6B537E20>
>>> bar = foo
>>> bar
<function foo at 0x0000021C6B537E20> # Functions gets named with the name given by def, so assigning it to bar doesn't really change its name

So you just have to do this:

bar = foo # That's it

If you have the doubt that this may be a non-working way in some language, why don't you simply try? Open your Python Launcher, then insert this commands:

>>> myFunction = quit
>>> myFunction()

If the window collapses then you have the prove that this works with Python.


I found information on how to apply another name to a library

Yes, in this case you would have to do this:

from myModule import foo as bar

CodePudding user response:

You can just write

 bark = print
 bark('Hello World')
  • Related