Python decorator? – can someone please explain this? [duplicate]

Take a good look at this enormous answer/novel. It’s one of the best explanations I’ve come across. The shortest explanation that I can give is that decorators wrap your function in another function that returns a function. This code, for example: @decorate def foo(a): print a would be equivalent to this code if you remove … Read more

How can I decorate an instance method with a decorator class?

tl;dr You can fix this problem by making the Timed class a descriptor and returning a partially applied function from __get__ which applies the Test object as one of the arguments, like this class Timed(object): def __init__(self, f): self.func = f def __call__(self, *args, **kwargs): print(self) start = dt.datetime.now() ret = self.func(*args, **kwargs) time = … Read more

How to use Python decorators to check function arguments?

From the Decorators for Functions and Methods: Python 2 def accepts(*types): def check_accepts(f): assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ “arg %r does not match %s” % (a,t) return f(*args, **kwds) new_f.func_name = f.func_name return new_f return check_accepts Python 3 In Python 3 func_code has … Read more

Applying a decorator to an imported function?

Decorators are just syntactic sugar to replace a function object with a decorated version, where decorating is just calling (passing in the original function object). In other words, the syntax: @decorator_expression def function_name(): # function body roughly(*) translates to: def function_name(): # function body function_name = decorator_expression(function_name) In your case, you can apply your decorator … Read more

Is a Python Decorator the same as Java annotation, or Java with Aspects?

Python decorators are just syntactic sugar for passing a function to another function and replacing the first function with the result: @decorator def function(): pass is syntactic sugar for def function(): pass function = decorator(function) Java annotations by themselves just store metadata, you must have something that inspects them to add behaviour.   Java AOP … Read more

How to inject variable into scope with a decorator?

You can’t. Scoped names (closures) are determined at compile time, you cannot add more at runtime. The best you can hope to achieve is to add global names, using the function’s own global namespace: def decorator_factory(value): def msg_decorator(f): def inner_dec(*args, **kwargs): g = f.__globals__ # use f.func_globals for py < 2.6 sentinel = object() oldvalue … Read more

How to bypass python function definition with decorator?

If the goal is to have the same sort of effect in your code that #ifdef WINDOWS / #endif has.. here’s a way to do it (I’m on a mac btw). Simple Case, No Chaining >>> def _ifdef_decorator_impl(plat, func, frame): … if platform.system() == plat: … return func … elif func.__name__ in frame.f_locals: … return … Read more

How to do a conditional decorator in python?

Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator: def conditional_decorator(dec, condition): def decorator(func): if not condition: # Return the function unchanged, not decorated. return func return dec(func) return decorator Now you can use it like this: @conditional_decorator(timeit, … Read more

Make @lru_cache ignore some of the function arguments

With cachetools you can write: from cachetools import cached from cachetools.keys import hashkey from random import randint @cached(cache={}, key=lambda db_handle, query: hashkey(query)) def find_object(db_handle, query): print(“processing {0}”.format(query)) return query queries = list(range(5)) queries.extend(range(5)) for q in queries: print(“result: {0}”.format(find_object(randint(0, 1000), q))) You will need to install cachetools (pip install cachetools). The syntax is: @cached( cache={}, … Read more

How to create a custom decorator in Django?

Played around with the various links above and couldn’t get them working and then came across this really simple one which I adapted. http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/ from functools import wraps from django.http import HttpResponseRedirect def authors_only(function): @wraps(function) def wrap(request, *args, **kwargs): profile = request.user.get_profile() if profile.usertype == ‘Author’: return function(request, *args, **kwargs) else: return HttpResponseRedirect(“https://stackoverflow.com/”) return wrap … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)