<br><div class="gmail_quote">On Fri, Feb 26, 2010 at 6:22 PM, Alf P. Steinbach <span dir="ltr"><<a href="mailto:alfps@start.no">alfps@start.no</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
* Raphael Mayoraz:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Hello,<div class="im"><br>
<br>
I'd like to define variables with some specific name that has a common prefix.<br></div><div class="im">
Something like this:<br>
<br>
varDic = {'red': 'a', 'green': 'b', 'blue': 'c'}<br>
for key, value in varDic.iteritems():<br>
'myPrefix' + key = value<br>
<br>
I know this is illegal, but there must be a trick somewhere.<br>
</div></blockquote>
<br>
In general you'll IMHO be better off with the variables as attributes of an object.<br>
<br>
If you want them to be modifiable then you can do<br>
<br>
class Whatever: pass<br>
<br>
myPrefix = Whatever()<br>
myPrefix.a = 'a'<br>
myPrefix.b = 'b'<br>
myPrefix.c = 'c'<br>
<br>
If you want them to be sort of constants (weasel words intentional) then you might do (Python 3.x) -- disclaimer: off-the-cuff & I'm not sure if that function is called 'namedtuple' but I think you'll find it anyway --<br>
<br>
import collections<br>
<br>
Color = namedtuple( "Color", "red green blue" )<br>
myPrefix = Color( 'a', 'b', 'c' )<br>
<br>
<br>
Cheers & hth.,<br><font color="#888888">
<br>
- Alf</font><div><div></div><div class="h5"><br>
-- <br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</div></div></blockquote></div><br>you can use setattr to do your bidding for setting variable like this. That is how I've been able to do it. Not sure if its the best solution, but it is a solution. I just don't know how to use setattr without it being in a class.<br>
<br>>>> class stuff(object):<br>... def __init__(self):<br>... pass<br>... def duuit(self,abc):<br>... for k,v in abc.items():<br>... setattr(self,"prefix_%s"%k,v)<br>... <br>>>> varDic = {'red': 'a', 'green': 'b', 'blue': 'c'}<br>
>>> abc=stuff()<br>>>> abc.duuit(varDic)<br>>>> dir(abc)<br>['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'duuit', 'prefix_blue', 'prefix_green', 'prefix_red']<br>
>>> <br><br>-Alex Goretoy<br>