What is the best way to define local variables dynamically in a method
<p>When I call a function, I would like to be able to define dynamic variable names in the function, like so...</p>

<pre><code>def build_ports(portlist):
    for idx, portname in enumerate(portlist):
        chassis, slot, port = portname.split('/') 
        vartxt = "p%i" % idx
        locals()[vartxt] = Port()  # Class defining a port object
        locals()[vartxt].port_method1(chassis, slot, port)
        if idx &gt; 5:
            locals()[vartxt].port_method2()  # Only call this object method, if idx &gt; 5
</code></pre>

<p>But we all know that <code>locals()</code> is read-only, unlike <code>globals()</code>... so the interpreter barfs when it sees <code>locals()[vartxt]</code>...</p>

<p>Is there any way to define dynamic variables in a method without polluting the global namespace (or worse, using a global variable in a method, when it was never defined in that method)?</p>
