Decorators in Python

Decorators in Python

<strong>Originally published by </strong>Meenakshi Agarwal<strong> </strong><em>at&nbsp;</em><a href="https://www.techbeamers.com/python-decorator/" target="_blank"><em>T</em>echbeamers</a>

From this tutorial, you will be learning about Python Decorator. You will see what decorators are, how to create and use them with the help of examples.

Note: The syntax used here is for Python 3. You may modify it to use with other versions of Python.

What Is Python Decorator?

Decorators are a callable entity in Python that allows us to make modifications to functions or classes. The decorator works in an abstract style to extend or completely replace the behavior of an object.

By understanding how to create decorators, you make your code extensible and more readable. Also, you get the functions tailored to your needs without even changing their definitions.

Decorator Syntax

Follow the below style:

def decoratorFunc(args):
    # Code to you want to execute
    ...

@decoratorFunc
def existingFunction(args):
    # Code that you want to decorate
    ...

Alternatively, you can try this way:

existingFunction = decoratorFunc(existingFunction)

How Does Decorator Work In Python?

Mainly, decorators are a construct that wraps a function, gives it a new functionality without changing the original code.

They return the output which may differ from the original behavior of the function.

They are good to use when a function has to operate differently in different situations.

Create Your Decorator:

A decorator is a function that may or may not return a function object.

We place it on top of the function that we want to decorate and pre-fix it with a @ sign.

So, let’s first create the decorator function.

def decoratorFunc(fn):
    return 10

The above decorator function returns an integer instead of a function.

So when you apply it to a function, it would get overridden altogether.

Check below how to specify a decorator to a function.

@decoratorFunc
def existingFunc():
    print("Hello World!")

Let’s now bring all the pieces together.

def decoratorFunc(fn):
    return 10

@decoratorFunc
def existingFunc():
    print("Hello World!")

existingFunc()

When you run the above code, the following error occurs.

line 8, in 
    existingFunc()
TypeError: 'int' object is not callable

It is because the decorator replaced the existing function and forcing it to return “10” which is an integer, not a callable object.

NOTE – the decorator’s return value replaces the function, i.e., existingFunc.
By the way, if you want to run the function that we decorated, then make the decorator return it. Check the below code.

def decoratorFunc(fn):
    def callExistingFunc():
        print("%s was called." % fn)
        fn()
    return callExistingFunc

@decoratorFunc
def existingFunc():
    print("Hello World!")

existingFunc()

In the above example, our decorator function is returning a function which prints the name of the decorated function and executes it.

The result of execution is as follows:

 was called.
Hello World!

Flowchart:

The following diagram attempts to simplify the decorator concept for you.

Must Read – Functions in Python

Chaining Decorators

We can decorate a function as many times as desired. In such a case, the decorators create a chain effect.

Typically, the decorator at the top hands over the control to the next, and continues in this way.

For illustration, check out the following code:

def top(func):
    def wrapper(*args, **kwargs):
        print("1" * 1)
        func(*args, **kwargs)
        print("1" * 1)
    return wrapper

def middle(func):
    def wrapper(*args, **kwargs):
        print("2" * 2)
        func(*args, **kwargs)
        print("2" * 2)
    return wrapper

def bottom(func):
    def wrapper(*args, **kwargs):
        print("3" * 3)
        func(*args, **kwargs)
        print("3" * 3)
    return wrapper

@top
@middle
@bottom
def myTest(anyString):
    print(anyString)

myTest("Hello World!")

You can check that this example is using three decorators on the myTest() function. Below is the result after execution:

1
22
333
Hello World!
333
22
1

Decorator Examples

Simple Decorator Program To Demonstrate:

def decorate(func):
   def first():
      func()
      print("This is the First Program on Decorators.")
   return first

def hello_not_decorated():
   print("Hello World!.\n")

print("This is an original function that is not decorated : ")

hello_not_decorated()
print("This is a decorated function :")
@decorate
def hello():
   print("Hello World!.")

hello()

#1 Output:

This is an original function that is not decorated : 
Hello World!.

This is a decorated function :
Hello World!.
This is the First Program on Decorators.

Decorate Arithmetic Operations:

def arithmetic_operations(func):
    def operators(a, b):
        func(a, b)
        print("The product is :", a*b)
        print("The division is :", a/b)
        print("The remainder is :", a%b)
    return operators
         
print("This is a decorated function.")

@arithmetic_operations
def add_and_subtract(a, b):
    print("The addition is :", a + b)
    print("The subtraction is :", a - b)

add_and_subtract(8, 4)

#2 Output:

This is a decorated function.
The addition is : 12
The subtraction is : 4
The product is : 32
The division is : 2.0
The remainder is :

Display Multiple Lines Using Chaining:

def Chaining_of_decorators(func):
   print("This is an example of chaining of decorators implementation.")
         
def Decorator_demo(func):
    print("This tutorial is about Decorators.")
         
print("This is a decorated function.")

@Chaining_of_decorators
@Decorator_demo
def hello():
   print("Hello World!")
    
hello

#3 Output:

This is a decorated function.
This tutorial is about Decorators.
This is an example of chaining of decorators implementation.

Pass Arguments To A Decorator:

def argument_for_decorator(argument1, argument2):
    def decorator(function):
        def wrapper(*args):
            print("%s%s" % (argument1, argument2))
            function(*args)
            print("Congratulations.  You decorated a function.")
        return wrapper
    return decorator

@argument_for_decorator("Hello ", "World!")
def print_args(*args):
    print("The Fibonacci Sequence upto number 8.")
    for arg in args:
        print(arg)

print_args(1, 1, 2, 3, 5, 8)

#4 Output:

Hello World!
The Fibonacci Sequence upto number 8.
1
1
2
3
5
8
Congratulations.  You decorated a function.

We wish the above Python Decorator tutorial would have given you a fair idea of using them in real Python programs.

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: