A deep dive into Python functions
In this post I will be discussing Python’s function in depth, accompanied by a bunch of examples on the way to clear up the concepts. All examples are in Python 2.7 but the same concepts should apply to Python 3 with some change in the syntax.
In Python, functions are first class citizens, they are objects and that means we can do a lot of useful stuff with them.
def greet(name): return "hello "+name greet_someone = greet print greet_someone("John") # Outputs: hello John
def greet(name): def get_message(): return "Hello " result = get_message()+name return result print greet("John") # Outputs: Hello John
def greet(name): return "Hello " + name def call_func(func): other_name = "John" return func(other_name) print call_func(greet) # Outputs: Hello John
In other words, functions generating other functions.
def compose_greet_func(): def get_message(): return "Hello there!" return get_message greet = compose_greet_func() print greet() # Outputs: Hello there!
Python only allows read access to the outer scope and not assignment. Notice how we modified the example above to read a “name” argument from the enclosing scope of the inner function and return the new function.
def compose_greet_func(name): def get_message(): return "Hello there "+name+"!" return get_message greet = compose_greet_func("John") print greet() # Outputs: Hello there John!
That was an introduction and a deep dive to functions in Python. I hope that you found this post helpful, if you have any suggestions or questions please do share their to me and I’ll be sure to get back to you.
Happy coding! :smile: