<jupyter_start><jupyter_text>DecoratorsDecorators can be thought of as functions which modify the *functionality* of another function. They help to make your code shorter and more "Pythonic". To properly explain decorators we will slowly build up from functions. Make sure to run every cell in this Notebook for this lecture to look the same on your own computer.So let's break down the steps: Functions Review<jupyter_code>def func():
    return 1
func()<jupyter_output><empty_output><jupyter_text>Scope ReviewRemember from the nested statements lecture that Python uses Scope to know what a label is referring to. For example:<jupyter_code>s = 'Global Variable'

def check_for_locals():
    print(locals())<jupyter_output><empty_output><jupyter_text>Remember that Python functions create a new scope, meaning the function has its own namespace to find variable names when they are mentioned within the function. We can check for local variables and global variables with the locals() and globals() functions. For example:<jupyter_code>print(globals())<jupyter_output><empty_output><jupyter_text>Here we get back a dictionary of all the global variables, many of them are predefined in Python. So let's go ahead and look at the keys:<jupyter_code>print(globals().keys())<jupyter_output><empty_output><jupyter_text>Note how **s** is there, the Global Variable we defined as a string:<jupyter_code>globals()['s']<jupyter_output><empty_output><jupyter_text>Now let's run our function to check for local variables that might exist inside our function (there shouldn't be any)<jupyter_code>check_for_locals()<jupyter_output><empty_output><jupyter_text>Great! Now lets continue with building out the logic of what a decorator is. Remember that in Python **everything is an object**. That means functions are objects which can be assigned labels and passed into other functions. Lets start with some simple examples:<jupyter_code>def hello(name='Jose'):
    return 'Hello '+name
hello()<jupyter_output><empty_output><jupyter_text>Assign another label to the function. Note that we are not using parentheses here because we are not calling the function **hello**, instead we are just passing a function object to the **greet** variable.<jupyter_code>greet = hello
greet
greet()<jupyter_output><empty_output><jupyter_text>So what happens when we delete the name **hello**?<jupyter_code>del hello
hello()
greet()<jupyter_output><empty_output><jupyter_text>Even though we deleted the name **hello**, the name **greet** *still points to* our original function object. It is important to know that functions are objects that can be passed to other objects!  Functions within functionsGreat! So we've seen how we can treat functions as objects, now let's see how we can define functions inside of other functions:<jupyter_code>def hello(name='Jose'):
    print('The hello() function has been executed')
    
    def greet():
        return '\t This is inside the greet() function'
    
    def welcome():
        return "\t This is inside the welcome() function"
    
    print(greet())
    print(welcome())
    print("Now we are back inside the hello() function")
hello()
welcome()<jupyter_output><empty_output><jupyter_text>Note how due to scope, the welcome() function is not defined outside of the hello() function. Now lets learn about returning functions from within functions: Returning Functions<jupyter_code>def hello(name='Jose'):
    
    def greet():
        return '\t This is inside the greet() function'
    
    def welcome():
        return "\t This is inside the welcome() function"
    
    if name == 'Jose':
        return greet
    else:
        return welcome<jupyter_output><empty_output><jupyter_text>Now let's see what function is returned if we set x = hello(), note how the empty parentheses means that name has been defined as Jose.<jupyter_code>x = hello()
x<jupyter_output><empty_output><jupyter_text>Great! Now we can see how x is pointing to the greet function inside of the hello function.<jupyter_code>print(x())<jupyter_output>This is inside the greet() function<jupyter_text>Let's take a quick look at the code again. In the if/else clause we are returning greet and welcome, not greet() and welcome(). This is because when you put a pair of parentheses after it, the function gets executed; whereas if you don’t put parentheses after it, then it can be passed around and can be assigned to other variables without executing it.When we write x = hello(), hello() gets executed and because the name is Jose by default, the function greet is returned. If we change the statement to x = hello(name = "Sam") then the welcome function will be returned. We can also do print(hello()()) which outputs *This is inside the greet() function*.  Functions as ArgumentsNow let's see how we can pass functions as arguments into other functions:<jupyter_code>def hello():
    return 'Hi Jose!'

def other(func):
    print('Other code would go here')
    print(func())
other(hello)<jupyter_output>Other code would go here
Hi Jose!<jupyter_text>Great! Note how we can pass the functions as objects and then use them within other functions. Now we can get started with writing our first decorator:  Creating a DecoratorIn the previous example we actually manually created a Decorator. Here we will modify it to make its use case clear:<jupyter_code>def new_decorator(func):

    def wrap_func():
        print("Code would be here, before executing the func")

        func()

        print("Code here will execute after the func()")

    return wrap_func

def func_needs_decorator():
    print("This function is in need of a Decorator")
func_needs_decorator()
# Reassign func_needs_decorator
func_needs_decorator = new_decorator(func_needs_decorator)
func_needs_decorator()<jupyter_output>Code would be here, before executing the func
This function is in need of a Decorator
Code here will execute after the func()<jupyter_text>So what just happened here? A decorator simply wrapped the function and modified its behavior. Now let's understand how we can rewrite this code using the @ symbol, which is what Python uses for Decorators:<jupyter_code>@new_decorator
def func_needs_decorator():
    print("This function is in need of a Decorator")
func_needs_decorator()<jupyter_output>Code would be here, before executing the func
This function is in need of a Decorator
Code here will execute after the func()
{'fraction_non_alphanumeric': 0.07360049898643381, 'fraction_numerical': 0.0001559332605644784, 'mean_word_length': 5.185149469623915, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 61, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '141704', 'license': 'MIT', 'n_tokens_mistral': 1804, 'n_tokens_neox': 1723, 'n_words': 802, 'path': 'Python-Programming/Python-3-Bootcamp/10-Python Decorators/.ipynb_checkpoints/01-Decorators-checkpoint.ipynb', 'repo_name': 'vivekparasharr/Learn-Programming', 'size': '6413'}