Variable definition

alex goretoy aleksandr.goretoy at gmail.com
Sat Feb 27 01:41:43 CET 2010


On Fri, Feb 26, 2010 at 6:22 PM, Alf P. Steinbach <alfps at start.no> wrote:

> * Raphael Mayoraz:
>
>> Hello,
>>
>>
>> I'd like to define variables with some specific name that has a common
>> prefix.
>> Something like this:
>>
>> varDic = {'red': 'a', 'green': 'b', 'blue': 'c'}
>> for key, value in varDic.iteritems():
>>   'myPrefix' + key = value
>>
>> I know this is illegal, but there must be a trick somewhere.
>>
>
> In general you'll IMHO be better off with the variables as attributes of an
> object.
>
> If you want them to be modifiable then you can do
>
>  class Whatever: pass
>
>  myPrefix = Whatever()
>  myPrefix.a = 'a'
>  myPrefix.b = 'b'
>  myPrefix.c = 'c'
>
> 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  --
>
>  import collections
>
>  Color = namedtuple( "Color", "red green blue" )
>  myPrefix = Color( 'a', 'b', 'c' )
>
>
> Cheers & hth.,
>
> - Alf
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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.

>>> class stuff(object):
...  def __init__(self):
...   pass
...  def duuit(self,abc):
...   for k,v in abc.items():
...    setattr(self,"prefix_%s"%k,v)
...
>>> varDic = {'red': 'a', 'green': 'b', 'blue': 'c'}
>>> abc=stuff()
>>> abc.duuit(varDic)
>>> dir(abc)
['__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']
>>>

-Alex Goretoy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100226/f524f91f/attachment.html>


More information about the Python-list mailing list