Decorators in Python are extremely useful tools. This syntactic sugar is an integral part of standard python code, and can be custom-built to make your own code more succinct and awesome.
I've used decorators to mark functions as deprecated, make them curryable, make sure a user is authenticated (when that method was a render method in a Twisted resource), and more. Recently I was using them to add a little bit of magic to a collection of methods that I needed to use a lot, that had a lot of repeated code in them. I needed to sometimes set up the executing environment of those functions a little differently than usual though, using keyword options that I would pass to the decorator. I've seen decorators used this way before, so I figured it would be easy. Uhm, not so much.
Decorators are a little confusing to people who haven't written them before. The idea is simple:
@decorator
def function():
pass
def function():
pass
function = decorator(function)
def decorator(func):
def inner(*args, **kwargs):
print "This is a decorated function!"
func(*args, **kwargs)
return inner
@decorator
def function(x):
print x
function(42)
#> This is a decorated function!
#> 42
A decorator can also take arguments:
@decorator(argument="An argument")
def function(x):
print x
# Without arguments:
function = decorator(function)
# With arguments:
function = decorator(argument="Argument")(function)
I chose to use just a function-style decorator, like what I've been demonstrating above. This is how I accomplished it:
def decorator(func=None, **options):
if func != None:
# We received the function on this call, so we can define
# and return the inner function
def inner(*args, **kwargs):
if len(options) > 0:
print "Decorated function with options:"
else:
print "Decorated function without options!"
for k, v in options.items():
print "\t{}: {}".format(k, v)
func(*args, **kwargs)
return inner
else:
# We didn't receive the function on this call, so the return value
# of this call will receive it, and we're getting the options now.
def partial_inner(func):
return decorator(func, **options)
return partial_inner
@decorator
def function_a(x, y):
print x + y
@decorator(foo="bar", baz=42)
def function_b(x, y):
print x + y
function_a(2, 3)
#> Decorated function without options!
#> 5
function_b(2, 3)
#> Decorated function with options:
#> foo: bar
#> baz: 42
#> 5
This solution has a caveat: it only works if what you're passing to the decorator are keyword arguments. If you use regular positional arguments, the first one will be put into the func argument of the decorator, and you'll probably get the error that it isn't callable. If you want to pass an optional, callable, positional argument to a decorator, it gets even more convoluted. I find this keywords-only solution to be acceptable, and it works well for my purposes. I hope others find this useful as well.
For some reason this doesn't work. Pasting your code in leaves function_b with the value None. I'm using Python 2.7, perhaps you are using Python 3?
ReplyDeleteWhoops! Of course it does, the `partial_inner` function wasn't returning a value :/ I've fixed it.
ReplyDeleteclass 10 tution classes in gurgaon
ReplyDeleteaz 104 exam questions
ReplyDeletescrum master exam questions
dp 900 exam questions
Good content. You write beautiful things.
ReplyDeletevbet
mrbahis
mrbahis
vbet
sportsbet
korsan taksi
taksi
hacklink
hacklink
Good text Write good content success. Thank you
ReplyDeletebetmatik
tipobet
betpark
bonus veren siteler
slot siteleri
kibris bahis siteleri
kralbet
mobil ödeme bahis
ReplyDeleteشركة مكافحة حشرات بالاحساء
شركة مكافحة حشرات بالخفجي
başakşehir
ReplyDeletebayrampaşa
beşiktaş
beykoz
beylikdüzü
PD6T
manisa
ReplyDeletetunceli
amasya
balıkesir
şırnak
D25D
https://saglamproxy.com
ReplyDeletemetin2 proxy
proxy satın al
knight online proxy
mobil proxy satın al
5UD5SR
https://istanbulolala.biz/
ReplyDeleteTJZ2
yalova evden eve nakliyat
ReplyDeletetunceli evden eve nakliyat
giresun evden eve nakliyat
ağrı evden eve nakliyat
van evden eve nakliyat
FEVKN3
hatay evden eve nakliyat
ReplyDeleteısparta evden eve nakliyat
erzincan evden eve nakliyat
muğla evden eve nakliyat
karaman evden eve nakliyat
WG6EVO
Explore top-notch Docker consulting services to optimize containerization strategies. Unlock efficiency and seamless deployment for your business success.
ReplyDeleteExperience the ultimate Satisfactory Game Server solution. Enhance your gaming experience with unrivaled performance and reliability.
ReplyDeletemt5 download apk
ReplyDeleteforex trading kya hai
ReplyDeleteشركة تنظيف منازل بجازان yBFQhfIe8N
ReplyDeleteرقم المجاري بالاحساء Ckd1emwU4m
ReplyDeleteشركة تنظيف بيوت بجازان vsMeIbiiTj
ReplyDelete