Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Function assignment

We can assign functions to variable and then use the new variable as the original function. We effectively create an alias.

Note, we did not call the hello function when we assigned it it greet.


def hello(name):
    print(f"Hello {name}")

if __name__ == "__main__":
    hello("Python")
    print(hello)

    greet = hello
    greet("Rust")
    print(greet)

Hello Python
<function hello at 0x7f8aee3401f0>
Hello Rust
<function hello at 0x7f8aee3401f0>
from function_assignment import hello

def test_assignment(check_out):
    hello("Python")
    check_out("Hello Python\n")
    assert hello.__name__ == "hello"

    greet = hello

    greet("Rust")
    check_out("Hello Rust\n")
    assert greet.__name__ == "hello"