w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python decorator function called at compile time
There is no compile time. A def statement, and the associated decorator calls are executable statements. Accordingly, when Python loads a module, it executes the statements in order. When executing a class statement, one of the early stages is executing all of the statements in the class body. As part of that defs are run to create functions, and those function objects will be passed to decorators for processing. Your "testing" print statement will run whenever the decorator is called, not when the function it returns is called. If you want that behaviour, move the decorator into the inner function.

Categories : Python

counting iterations in recursion python
def recursive_thing(calls=1): # "calls" argument keeps track of recursion depth if keep_recursing(): # pass a higher count to the recursive call recursive_thing(calls + 1) else: print calls return Give your function an argument that keeps track of the recursion depth, or put the recursion in a helper function with such an argument.

Categories : Python

Decorator functions in classes. Should each instantiation result in decorator function being run again?
As everyone else is mentioning, and I am restating for further clarity there is no need to add a @with_setup decorator to a test function. You have already added setup and teardown functions to the class and they will automatically be run before and after the test. From the nose docs: Note that with_setup is useful only for test functions, not for test methods or inside of TestCase subclasses. Now in your case you have with_setup within a TestCase class. The nose documentation explicitly mentions that this does not work But you already solved the puzzle, now just remove the @with_setup decorator and you're finished. Your code should ultimately look something like this class Test_getFileSize: def setUp(self): print " running Setup",self.testsize ... def t

Categories : Python

Is python @decorator related to the decorator design pattern?
A "pattern" is a workaround for a missing language feature. "Decoration" is a term which pre-existed the Gang Of Four patterns book in programming - it has been used to describe any number of operations that involve adding some information or behaviour onto something else. Strictly speaking, this isn't a way of implementing the decorator pattern, because it doesn't involve the creation of a class which composes other classes (except co-incidentally that that is one thing you can do with a decorator). It does, however, together with python's other features, render it largely obsolete. In fact, I'd add that most "patterns" are a way of faking dynamic or reflective behaviour in C++, Java, and the like. You'll find very little excitement outside of those language communities. In Python decor

Categories : Python

How can I programmatically change the argspec of a function *not* in a python decorator?
A decorator is simply a function that does something with another function. So, technically, you could put the required code directly underneath the foo method and then, technically, you would be changing foo without using a decorator, but it would be a horrible mess. The easiest way to do what you want is going to be to make a decorator that takes a second function (bar in this case) as an argument so it knows which signature to copy. The class code would then look something like: class Blah(object): @copy_argspec(bar) def foo(self, *args, **kwargs): """ a docstr """ result = bar(*args, **kwargs) result = result**2 # just so it's clear we're doing something extra here... return result You'll have to have bar defined before instead of after th

Categories : Python

Problems passing argument to python function with decorator
You need to pass arguments for a subtask in the args keyword argument, which must be a tuple according to the celery.subtask() documentation: subtask('smallTask', args=(obj,)).apply_async() or use the Task.subtask() method on your smallTask task, but again pass the arguments as a tuple: smallTask.subtask((obj,)).apply_async() Alternatively, use star arguments with the Task.s() method: smallTask.s(obj).apply_async() The subtasks documentation you yourself linked to use a tuple in the examples; arguments and keyword arguments are two pieces of data that Celery has to store for you until it can run that task, then it'll apply those arguments and keyword arguments for you. But the celery.subtask() function takes more than just the arguments and keyword arguments for your task; it als

Categories : Python

python decorator parameter using variable from function its wrapping
You could pass two lists when creating the decorator. First one would contain the list of positions for the positional arguments and the second one would contain the list of parameter names for keyword arguments. def cached(positions, names): def cached_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): keys = [func.__name__] + [str(kwargs.get(name)) for name in sorted(names)] + [str(args[position]) for position in positions] cache_key = '_'.join(keys) cached_value = cache.get(cache_key) if cached_value: return cached_value value = func(*args, **kwargs) cache.set(cache_key, value) return cached_value return wrapper return cached_decorator

Categories : Python

Is a general-purpose function/object doubling decorator feasible in Python?
Edit: Here's a general solution if I understood your question properly as well as an example to go along. generator = None def getObject(askOnce = None, createFunction = None, *args): global generator if generator is None: askOnceValue = askOnce() generator = getGenerator(askOnceValue, createFunction, *args) return generator.next() def getGenerator(askOnceValue, createFunction, *args): while(True): yield createFunction(askOnceValue, *args) def myInputFunction(): return "Some dynamic value" def myCreateFunction(myInput, arg1, arg2): return list([myInput, arg1, arg2]) myObj1 = getObject(myInputFunction, myCreateFunction, "hello", 1234) print(myObj1) myObj2 = getObject() print(myObj2) This could be made much nicer by creating a cla

Categories : Python

Time complexity analysis of function with recursion inside loop
Assuming that you've fixed the bugs others have noted, then the i values are the places that the string is being split (each i is the leftmost splitpoint, and then you recurse on everything to the right of i). This means that if you were to unwind the recursion, you are looking at up to n-1 different split points, and asking if each substring is a valid word. Things are ok if the beginning of word doesn't have a lot of elements from your set, since then you can skip the recursion. But in the worst case, prefix in s is always true, and you try every possible subset of the n-1 split points. This gives 2^{n-1} different splitting sets, multiplied by the length of each such set.

Categories : Algorithm

Executing a javascript function in different computers at same time
You could use WebSocket, though be aware of potential problems (which is a good reason to use Socket.io, as already recommended, which provides fallbacks and workaround). RTCDataChannel leverages RTCPeerConnection to enable peer-to-peer communication of arbitrary data with very low latency -- and as part of WebRTC, it's designed to cope with NATs and firewalls. (More information here, press P for speaker notes -- apologies for shameless self promotion!) RTCDataChannel is used by the wonderful Cube Slam game. Another option is to use XHR plus the Google Channel API: apprtc.appspot.com uses this for messaging, code here.

Categories : Javascript

Python Import Statement and Recursion- need function available in module namespace
The easy answer is move foo() to foo.py and import from there or move it to create.py and import it from there into main.py - if there are things in main.py that it needs the move the too. Your other option is to pass foo from main into create as a function parameter where it is needed.

Categories : Python

Python - abstracting a recursion to all nth level recursion (lxml)
I would suggest using a recursive algorithm which takes a list of the 2 items to compare, and the pass number, as arguments. You would need a dictionary specifying which list to supply on each pass. You could also write an algorithm to create the dictionary of n elements, hope this helps. I could try and give example code if that'd be more helpful. EDIT: n=3 ##Depth of tree d={'0':['a.root', 'b.root', 0]} for i in range(n): d[str(i+1)]=[d[str(i)][0]+'['+chr(105+i)+']', #since ord('i')=105, start d[str(i)][1]+'['+chr(105+i)+']', # at i, j, k, etc i+1 #passNo ] print(d) def compare(points=d['0'], passNo=0): if xml.xml_compare(eval(points[0]), eval(points[1])) == False: exec('for'+str(chr(poin

Categories : Python

recursive ajax calls not executing script included inbetween the recursion
If msg is an integer, you should compare integers instead of strings: if( parseInt(msg,10) < parseInt($('#end_'+code_regional).val(),10) ) If it's still failing, try to add a console.log(...) before and after the test to know what's going on.

Categories : Javascript

Decorator for elapsed time flask
With the print_elapsed_time decorator above Flask's route decorators, the function registered by route has not yet been modified by print_elapsed_time, as decorators are applied from bottom to top. The solution is to put @print_elapsed_time below both route decorators. However, Flask keeps track of its registered functions by their name, and for everything wrapped by print_elapsed_time this is wrapper. See my answer to another StackOverflow question for ways around that.

Categories : Python

Python thread timer, not executing or executing instantly
You lost all the indentation in your code snippet, so it's hard to be sure what you did. The most obvious problem is responseTimer.start. That merely retrieves the start method of your responseTimer object. You need to call that method to start the timer; i.e., do responseTimer.start(). Then it will produce the output you expected, with a delay of about 2 seconds before the final "timeout!" is printed.

Categories : Python

A more elegant way for this python decorator
You want a function that returns a decorator: def status_display_with_comment(comment): def decorator(function): def wrapper(): print(comment) print("Entering", function.__name__) result = function() print("Exited", function.__name__) return result return wrapper return decorator def a_function(): print('a_function executes') a_function_SD_WC = status_display_with_comment('a comment')(a_function) a_function_SD_WC() Also works: @status_display_with_comment('a comment') def a_function(): print('a_function executes') a_function() The regular, direct decorator already returns a closure: def a_normal_decorator(function): def wrapper(): return function() return wrapper w

Categories : Python

Python decorator error?
I believe this is the code you wanted: def outer(): def inner(): print 'inner called' return inner foo = outer() foo() Your return was indented too far

Categories : Python

Function decorator not being invoked
Short answer: change the order of the decorators; blueprint.route only "sees" your undecorated function. Decorators are applied inside-out, in loose analogy to function calls. Thus your function definition is equivalent to: def index(): return render_template('index.html') index = blueprint.route('/')(index) index = admin_required(index) Note how blueprint.route is passed the index function before it gets wrapped by admin_required. Of course, admin_required does eventually get applied to the index name in the module, so if you were to call index directly, it would go through both decorators. But you're not calling it directly, you're telling flask's request processor to call it.

Categories : Python

Deactivate function with decorator
You can turn functions into no-ops (that log a warning) with a decorator: def conditional(cond, warning=None): def noop_decorator(func): return func # pass through def neutered_function(func): def neutered(*args, **kw): if warning: log.warn(warning) return return neutered return noop_decorator if cond else neutered_function Here conditional is a decorator factory. It returns one of two decorators depending on the condition. One decorator simply leaves the function untouched. The other decorator replaces the decorated function altogether, with one that issues a warning instead. Use: @conditional('matplotlib' in sys.modules, 'Please install matplotlib') def foo(self, bar): pass

Categories : Python

overload setters decorator in python
Python doesn't have any notion of overloading functions based on signature. If you want to do that, you have to do it inside the function. You could do something like this. @x.setter def x(self, value, *args): if args: self._x[0] = value self._x[3] = args[0] else: self._x = [value,value,value,value]

Categories : Python

Python decorator optional argument
put the def outer(var) outward, that is def outer(var): def logged(func): ... , then use @outer(somevar) for your function, this would work.

Categories : Python

How does Python resolve decorator names
synchronized is defined as a function in the class body of Synchronized only. A class body is executed like a function to define the class; the resulting local namespace is used to form the class attributes. This is why synchronized is still a local name within Synchronized when used as a decorator on go. You could compare that with defining the decorator inside a function, then trying to apply it outside of that function; it won't work, because the decorator is a local variable. You could use @Syncronized.synchronized.im_func in class B (.im_func to unwrap the function from the method wrapper): class B(Synchronized): @Synchronized.synchronized.im_func def foo(self): return 1 Better still, do not defined the decorator inside a class at all but instead defined it outsid

Categories : Python

Python Decorator not performing task
1) Your serve function doesn't look like a decorator. You should do like this... Write this function outside of your class definition. def serve(func): def wrapper(*args,**kwargs): func(*agrs,**kwargs) return wrapper 2) you can also do like this. def serve(self,func): def wrapper(self,*args,**kwargs): func(self,*args,**kwargs) return wrapper you should call your add_rule method inside func method definition.

Categories : Python

Preventing function (or decorator) from being nested
The obvious solution is to have special_wrapper set a global flag, and just skip its magic if the flag is set. This is about the only good use of a global variable - to allow a single piece of code to store information that is only used within that code, but which needs to survive the life of execution in that code. It doesn't need to be set in global scope. The function could set the flag on itself, for example, or on any object or class, as long as nothing else will touch it. As noted by Lattyware in comments, you'll want to use either a try/except, or perhaps even better, a context manager to ensure the variable is unset. Update: If you need the wrapped code to be able to check if it is wrapped, then provide a function which returns the value of the flag. You might want to wrap it

Categories : Python

How to inject variable into scope with a decorator in python
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.func_globals sentinel = object() oldvalue = g.get('var', sentinel) g['var'] = value try: res = f(*args, **kwargs) finally: if oldvalue is sentinel: del g['var'] else: g['var'] = oldvalue return res return inner_dec return msg_decorator f.func_globals is the global namespace for the wrapped function, so this

Categories : Python

Python decorator with optional callable argument
Yes, but it will remain slightly hacky. The trick is to use named arguments. Besides that there is no clean way to differentiate between the different callables. class MyDecorator(object): def __init__(self, *args, **kwargs): if kwargs: # arguments print 'got %r as arguments' else: callable, = args @MyDecorator(some_function=lambda x:2*x) def foo(): pass

Categories : Python

What is the use of Python property decorator that returns an instance?
It creates a new Database instance when it is called similar to your second alternative. This means every call to insert creates a new Database instance, inserts and then deletes the Database instance because there is no reference left pointing to it. In your first alternative you will always acess the same instance. This means after a call to insert, the Database object is still there.

Categories : Python

How do I use the python-decorator package to decorate classmethods?
You do not need to provide your own wrapper anymore, just use @decorator.decorator on the inner function, which takes one extra first positional argument, the function wrapped: @decorator.decorator def mydec(func, cls, *args, **kwargs): # do some stuff return func(cls, *args, **kwargs) The decorator package doesn't use a closure for decorators and instead passes in the wrapped function as an argument. Demo: >>> @decorator.decorator ... def mydec(func, cls, *args, **kwargs): ... # do some stuff ... return func(cls, *args, **kwargs) ... >>> class Foo(object): ... @classmethod ... @mydec ... def bar(cls, baz='test', qux=None): ... print (baz, qux) ... >>> Foo.bar() ('test', None)

Categories : Python

Python - using decorator.py to preserve a method docstring
Basic Descriptor/Decorator You just need to keep in mind which function you should decorate. Your function is being created in __get__, so it won't help to use the wrapper as a decorator, instead, you need to apply it in the __get__ method. As an aside, you can use either functools.update_wrapper or decorators.decorator for this. They work very similarly, except that you have to keep the result of decorators.decorator whereas functools.update_wrapper returns None. Both have signature f(wrapper, wrapped). from functools import update_wrapper class class_or_instance(object): def __init__(self, fn): self.fn = fn def __get__(self, obj, cls): if obj is not None: f = lambda *args, **kwds: self.fn(obj, *args, **kwds) else: f = lambda *a

Categories : Python

Can you write a c# decorator function that can take any number of arguments?
No, you can'd do exactly this in C# with strongly typed results. It is mainly due to return type - you can relatively easy construct calling of the function with arbitrary number of parameters (i.e. Emit or reflection), but to have strongly typed result you'll have to have multiple functions. Usual approach is to have multiple functions for each of 0-n (often 0-3 is enough) number of arguments. public Func<TReturn> EnableP4<TReturn>(Func<T1, TReturn> function)... public Func<T1, TReturn> EnableP4<TReturn, T1>(Func<T1, TReturn> function).... public Func<T1, T2, TReturn> EnableP4<TReturn, T1, T2>(Func<T1, T2, TReturn> function)... Notes: you may experiment with dynamic to see if you get close to what you want also Dependenc

Categories : C#

How to get through decorator to get the underlying function arguments information?
Assuming you've installed Michele Simionato's decorator module, you can make yourshowdurationdecorator work with it by making some minor modifications to it and to the nestedwrapped_f()function defined in it so the latter fits the signature that module's decorator.decorator() function expects: import decorator def showduration(user_function): ''' show time duration decorator''' import time def wrapped_f(user_function, *args, **kwargs): t1 = time.clock() result = user_function(*args, **kwargs) print "%s()_Time: %0.5f"%(user_function.__name__, time.clock()-t1) return result return decorator.decorator(wrapped_f, user_function) However, the module really shines because it will let you reduce boilerplate stuff like the above down to just: imp

Categories : Python

Python property getter and setter decorator not callable
The whole point of the getter is that it returns the value without being called. p.voltage returns the integer object, so running p.voltage() is equivalent to 100() or something. There can still be cases where you want to call the value of a property, like if the value is itself a function. But you don't need it here.

Categories : Python

'@' python decorator used to do something similar to method overriding in java?
In Python functions are first class objects, so that they may be passed as parameters. I'll rewrite your function for the clarity of the following explanation: @app.before_request def f(): g.db = connect_db() First, app.before_request is function. What happens here is the following: def f(): g.db = connect_db() f = app.before_request(f) So, function app.before_request is applied to function f. As app.before_request is used as decorator, the result of app.before_request is assigned again to f. But in this case it doesn't matter. What is imporatant is that app.before_request makes something internally with f to make use of it. Decorator is used just for concise and beautiful way of describing it. You can achieve the same by this code (which I think is less readable than t

Categories : Java

Decorator which conditionally activates another decorator?
Isn't this doing the thing you want? import functools from itertools import product def the_list(): return ["foo", "bar", "baz"] def do_all(func): if hasattr(func, 'get_from'): @functools.wraps(func) def wrapper(*args, **kwargs): return tuple(func(*args) for args in product(*(lf() for lf in func.get_from))) return wrapper return func def gets_arg_from(*list_funcs): def decorator(func): func.get_from = list_funcs return func return decorator @gets_arg_from(the_list) def print_func(word): return word print print_func('foo') all = do_all(print_func) print all() Edit: Explanation These two code segments are identical: @deco def func(...): some code is the same as func = deco(

Categories : Python

How to call specific function based on parameters to decorator
There's no reason a decorator can't do other stuff, in addition to wrapping the function >>> def print_stuff(stuff): ... def decorator(f): ... print stuff ... return f ... return decorator ... >>> @print_stuff('Hello, world!') ... def my_func(): ... pass ... Hello, world! In this example, we simply print out the the argument passed to the decorator's constructor when we define the function. Notice that we printed "Hello, world!" without actually invoking my_func - that's because the print occurs when we construct the decorator, rather than in the decorator itself. What's happening, is that application.route is not a decorator itself. Rather, it is a function that takes a route, and produces a decorator that will be applied to the view func

Categories : Python

Custom decorator for Pyramid views: View function is ignored?
You didn't apply the decorators; call the return value of `view_config(), passing in the item to decorate: def entity_search_method(type_name): def decorator(fkt): fkt = view_config(route_name = A % type_name, ...)(fkt) fkt = view_config(route_name = B % type_name, ...)(fkt) fkt = view_config(route_name = C % type_name, ...)(fkt) fkt = view_config(route_name = D % type_name, ...)(fkt) return fkt return decorator The @view_config(route_name='D', renderer='D') syntax takes the return value of the expression and calls it with the next object (function or output of another decorator) defined below it in the source, with the return value replacing the object-to-decorate. In other words, the following: @some_expression def some_function():

Categories : Python

Python suds "RuntimeError: maximum recursion depth exceeded while calling a Python object"
After more testing, it seems that (unfortunately) suds has trouble interpreting Java Collection objects serialized as XML. I ended up using SOAPpy instead to avoid this issue. If someone can suggest a fix, that would be awesome! I really like suds for its other merits over SOAPpy.

Categories : Python

Why does the decorator module force me to lift the inner function to the outer level?
Requiring this is an intentional design choice of the decorator library, explained in the documentation (emphasis in the original): The difference with respect to the memoize_uw approach, which is based on nested functions, is that the decorator module forces you to lift the inner function at the outer level (flat is better than nested). This is also explained right up in the motivation section of the Introduction: For instance, typical implementations of decorators involve nested functions, and we all know that flat is better than nested. Of course "flat is better than nested" is part of the Zen of Python. But you may disagree that it applies here, or may think that some other principle overrides it. If you violently disagree with the design principles behind the library, you

Categories : Python

Point free function wouldn't cause recursion but normal function would here?
Uncontrolled mutability is the reason for this behavior. Other languages like Haskell provides controlled mutability using Software transaction memory techniques which avoid these kind of problems. Also, eager evaluation plays an important role here. let d = (notify >> (wrap a)) : In this case whatever value of notify has will be composed with (wrap a) and the result will be assigned to d let d x = (notify >> (wrap a)) x : Here, the body of the function is not executed untill you actually call the d function and hence you get the mutated value of notify

Categories : F#

Running a function in Python every time any key is pressed?
For starters, you need a loop somewhere to continue prompting the user. You also need some sort of exit condition for the loop. This loop can be inside the function like so: def random_letter(letters): while True: x = raw_input('Press enter for a random letter...') if x == 'done': break print random.choice(letters) random_letter('abcdef') Notice that inside the loop we use raw_input to prompt the user to type something, anything, then press enter. When the user types done and hits enter, we break out of the loop using break. An alternative would be to wrap your existing function in a loop and take care of the prompting outside the function. def random_letter(letters): print random.choice(letters) while True: x = raw_input('Press enter

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.