Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a decorator that seems to work. Note that this requires return locals() at the end of the function due to being unable to set locals from the outside (I don't have much experience programming so if there is a way, I don't know it).</p> <pre><code>class Static(object): def __init__(self, **kwargs): self.kwargs = kwargs def __call__(self, f): def wrapped_f(): try: new_kwargs = {} for key in self.kwargs: i = getattr(f, key) new_kwargs[key] = i self.kwargs = new_kwargs except: pass for key, value in f(**self.kwargs).items(): setattr(f, key, value) return wrapped_f @Static(x=0, y=5, z='...') def f(x, y, z): x += 1 y += 5 print x, y, z return locals() </code></pre> <p>The output would be:</p> <pre><code>&gt;&gt;&gt; f() 1 10 ... &gt;&gt;&gt; f() 2 15 ... &gt;&gt;&gt; f() 3 20 ... </code></pre> <p>EDIT:</p> <p>I found something at <a href="http://code.activestate.com/recipes/410698/" rel="nofollow noreferrer">http://code.activestate.com/recipes/410698/</a> and decided to try adding it to this. It works without the return now.</p> <p>EDIT again: Changed to to make it a few seconds faster. Edit 3; changed to function instead of class</p> <pre><code>def static(**kwargs): def wrap_f(function): def probeFunc(frame, event, arg): if event == 'call': frame.f_locals.update(kwargs) frame.f_globals.update(kwargs) elif event == 'return': for key in kwargs: kwargs[key] = frame.f_locals[key] sys.settrace(None) return probeFunc def traced(): sys.settrace(probeFunc) function() return traced return wrap_f </code></pre> <p>tested:</p> <pre><code>@static(x=1) def f(): x += 1 global_x = 1 def test_non_static(): global global_x global_x += 1 print 'Timeit static function: %s' % timeit.timeit(f) print 'Timeit global variable: %s' % timeit.timeit(test_non_static) </code></pre> <p>output:</p> <pre><code>Timeit static function: 5.10412869535 Timeit global variable: 0.242917510783 </code></pre> <p>Using settrace slows it down quite drastically.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload