Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to modify variables of another scope?
    primarykey
    data
    text
    <p>Currectly, I'm trying the following: Some <code>mutator</code> function accepts other function's local scope using <code>locals()</code></p> <pre><code>def mutator(locals): locals['n'] = 10 locals['l'].append(10) def f(): n = 1 l = [1] mutator(locals()) print(n,l) # &gt;&gt;&gt; 1, [1,10] f(None) </code></pre> <p>and that works as expected: I was able to modify mutable list contents but failed to 'rebind' another immutable <code>int</code> to the same name.</p> <p>Currently, I see some options:</p> <ul> <li><code>eval()</code>, <code>exec()</code> &amp; Co</li> <li>Play with stack frames &amp; local variables in <code>mutator()</code></li> <li>Keep such variables in a <code>dict</code>: not very handy but probably the best one</li> </ul> <p>The restriction is: target function <code>f()</code> can contain just one function call, possibly with arguments, and that function should be able to alter values in <code>f()</code>s current scope.</p> <p>So.. is there a way to reintroduce variable's value (bind another object) at runtime? I don't believe there is no good trick to achive this!</p> <hr> <p>Here's an example of the thing I'm trying to achieve:</p> <pre><code>def view(request): # Yes, that's Django! q = MyModel.objects.all() data = { 'some_action': True, 'items_per_page': 50 } # defaults. Mutators can change this mutators.launch(locals(), data ) # Launch mutators that may want to narrow the QuerySet if data['some_action']: # do something useful if no mutator has disabled it ... # paginate using data['items_per_page'] </code></pre> <p>I don't want to use <code>data</code> dict here: ability to modify them as local variables would be much better &amp; pretty. Note that <code>q</code> QuerySet object is mutable &amp; mutators can alter its contents.</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.
 

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