Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

decorator python

def our_decorator(func):
    def function_wrapper(x):
        print("Before calling " + func.__name__)
        func(x)
        print("After calling " + func.__name__)
    return function_wrapper

@our_decorator
def foo(x):
    print("Hi, foo has been called with " + str(x))

foo("Hi")
Comment

python decorator

def uppercase_decorator(func):
    def function_wrapper(x):
        print("Before calling " + func.__name__)
        # function that is decorated making name parameter always uppercase
        func(x.upper())
        print("After calling " + func.__name__)
    return function_wrapper

@uppercase_decorator
def user(name):
    print(f"Hi, {name}")

user("Sam")

# output
# Before calling user
# Hi, SAM
# After calling user
Comment

python decorator

from functools import wraps
def debug(func):
    @wraps(func)
    def out(*args, **kwargs):
        print('hello world')
        return func(*args, **kwargs)
    return out

@debug
def add(x, y):
    return x + y
Comment

python decorator

# Decorator with arguments
import functools

# First function takes the wanted number of repetition
def repeat(num_times):
    # Second function takes the function
    def decorator_repeat(func):
        # Third function, the wrapper executes the function the number of times wanted        
        # functools decorator to print the true name of the function passed instead of "wrapper"
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result= func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

# Our function using the decorator
@repeat(num_times= 3)
def greet(name):
    print(f"Hello {name}")

greet("thomas")
Comment

Decorators in python

# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper
# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]
Comment

decorators in python

# this functon converts any string into uppercase
def deco(function):
    def wrap(s):
        return s.upper()
        function(s)
    return wrap

@deco
def display(s):
    return s 
print(display("not bad"))
Comment

examples of function decorators in Python

from functools import wraps

def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

@logit
def addition_func(x):
   """Do some math."""
   return x + x


result = addition_func(4)
# Output: addition_func was called
Comment

decorators in python

def deco(function):
    def wrap(num):
        if num % 2 == 0:
            print(num,"is even ")
        else:
            print(num,"is odd")
        function(num)
    return wrap
    
@deco
def display(num):
    return num
display(9)   # pass any number to check whether number is even or odd
Comment

python decorator python

# class decorator 
import random

# changes the properties of a function to a class instance
class Eliphant:
    def __init__(self,funct):
        self._funct = funct
        #all return values are storredin momory
        self._memory = []

    def __call__(self):
        returnvalue = self._funct()
        self._memory.append(returnvalue)
        return returnvalue

    def memory(self):
        return self._memory


@Eliphant

def random_odd():
    return random.choice([1,3,5,7,9])
print(random_odd())
print(random_odd.memory())
print(random_odd())
print(random_odd.memory())
Comment

Decorators in python

# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper
# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]
Comment

examples of function decorators in Python

from functools import wraps

def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # Open the logfile and append
            with open(logfile, 'a') as opened_file:
                # Now we log to the specified logfile
                opened_file.write(log_string + '
')
            return func(*args, **kwargs)
        return wrapped_function
    return logging_decorator

@logit()
def myfunc1():
    pass

myfunc1()
# Output: myfunc1 was called
# A file called out.log now exists, with the above string

@logit(logfile='func2.log')
def myfunc2():
    pass

myfunc2()
# Output: myfunc2 was called
# A file called func2.log now exists, with the above string
Comment

Decorators in Python

def first(msg):
    print(msg)


first("Hello")

second = first
second("Hello")
Comment

python decorator

def deco(func):
    def wrap(lst):
        x = [1 if i % 2 == 0 else 0 for i in lst]
        return x
        func(lst)
    return wrap

@deco  
Comment

PREVIOUS NEXT
Code Example
Python :: change excel value in python 
Python :: how to parse http request in python 
Python :: python if file exist 
Python :: items of list 
Python :: multiple model search in django rest framework 
Python :: tkinter auto resize height 
Python :: .add_prefix to certain columns python 
Python :: plot circles in matplotlib 
Python :: remove element from pack tkinter 
Python :: cv2.imshow not working in vscode 
Python :: error python 
Python :: python set workspace dir 
Python :: django change id to uuid 
Python :: var colors python 
Python :: #Function in python 
Python :: newsapi 
Python :: what is chr function on python 
Python :: python list include 
Python :: python catch int conversion error 
Python :: dict comprehension python 
Python :: how to put space in between list item in python 
Python :: python latest version 64 bit 
Python :: float python 
Python :: false in py 
Python :: how to delete a column in pandas dataframe 
Python :: pandas read parquet from s3 
Python :: Check version of package poetry 
Python :: python web app 
Python :: two underscores python 
Python :: serialize list to json python 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =