Skip to content

Instantly share code, notes, and snippets.

@JacobCallahan
Created November 22, 2019 15:29
Show Gist options
  • Save JacobCallahan/38e9aa6f0178550ccaf97bd711eee8d4 to your computer and use it in GitHub Desktop.
Save JacobCallahan/38e9aa6f0178550ccaf97bd711eee8d4 to your computer and use it in GitHub Desktop.
Decorator Class 1
"""
Decorators provide a way to intercept a decorated function, method, or class.
Ultimately, the decorator accepts the function as its only argument
Decorators can then either return the original function, or another one
"""
def change_name(func):
"""This decorator just changes the name of any decorated function"""
func.__name__ = "changed"
return func
def checker(func):
"""This decorator explicitly checks the presence of two arguments"""
def wrapper(name=None, age=None):
if args:
print("Keyword arguments only!!!")
return
if not name:
print("You must provide a name!")
return
if not age:
print("You must provide a age!")
return
print("You passed in all the params")
return func(**kwargs)
return wrapper
def defaults(func):
"""This decorator will set default values of a decorated function, if they don't exist"""
def wrapper(*args, **kwargs):
if args:
print("Keyword arguments only!!!")
return
if not kwargs.get("name"):
kwargs["name"] = "Box"
if not kwargs.get("age"):
kwargs["age"] = 42
return func(**kwargs)
return wrapper
def named_defaults(**default_args):
"""This decorator can set any default values for a function
It allows you to specify the argument and value when you decorate
This could be useful if a function only accepts **kwargs in its definition
"""
def deco(func):
def wrapper(*args, **kwargs):
if args:
print("Keyword arguments only!!!")
return
for def_arg, def_val in default_args.items():
if not kwargs.get(def_arg):
kwargs[def_arg] = def_val
return func(**kwargs)
return wrapper
return deco
def set_attrs(**attrs):
"""This decorator simply sets custom attributes on a function"""
def deco(func):
for key, val in attrs.items():
setattr(func, key, val)
return func
return deco
@named_defaults(name="Box", age="117")
def my_func(name, age):
print(f"Hello {name}, you are {age} years old.")
@named_defaults(name="Box", age="117")
@change_name
def my_func2(**kwargs):
print(f"Hello {kwargs.get(name)}, you are {kwargs.get(age)} years old.")
@named_defaults(var1=5, var2=90)
@set_attrs(something="else", another=False)
def multiply(var1, var2):
return var1 * var2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment