Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a <em>really</em> bad way (undefined behavior), but I think it shows the path to a more reasonable technique.</p> <p>Your current namespace is really a dictionary under the covers:</p> <pre><code>&gt;&gt;&gt; local_namespace = locals() &gt;&gt;&gt; name = "myVarName" &gt;&gt;&gt; local_namespace[name] = 'VarData' &gt;&gt;&gt; myVarName 'VarData' </code></pre> <p>But that's not very DRY - you have to write the name of the variable twice! It would be nice to use a variable that stored the name of our dynamically created variable so we didn't have to type it twice:</p> <pre><code>&gt;&gt;&gt; name 'myVarName' </code></pre> <p>obviously doesn't work for this. But we can use our dictionary again:</p> <pre><code>&gt;&gt;&gt; local_namespace[name] 'VarData' </code></pre> <p>So now we can store and recall the value associated with our variable. But wait - there's no need to use the special <code>locals()</code> dictionary for this - an ordinary dictionary will do!</p> <pre><code>&gt;&gt;&gt; d = {} &gt;&gt;&gt; d[name] = 'VarData' &gt;&gt;&gt; d[name] 'VarData' </code></pre> <p>And now we have all these added benefits, like being able to keep track of the names of several of these variables in a list:</p> <pre><code>&gt;&gt;&gt; l = [] &gt;&gt;&gt; l.append('myVarName') &gt;&gt;&gt; l.append('anotherVarName') </code></pre> <p>Dictionaries even do this for us:</p> <pre><code>&gt;&gt;&gt; d['anotherVarName'] = 123 &gt;&gt;&gt; d.keys() ['myVarName', 'anotherVarName'] </code></pre> <p>Unless you're doing terrifically wacky things, it's hard to imagine how constructing variable names could be more useful than using a dictionary.</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.
    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