Dynamic assignment

Emile van Sebille emile at fenx.com
Fri Oct 26 09:01:59 EDT 2001


----- Original Message -----
From: "Ingo Blank" <iblank at nospam.com>
Newsgroups: comp.lang.python
Sent: Thursday, October 25, 2001 7:59 PM
Subject: Dynamic assignment


> Hi,
>
> I want to dynamically create variables and assign values to them.
>
> I tried the following:
>
> >>> vn = "dynVar"
> >>> vv = 1
> >>> eval("%s=%d" % (vn,vv))
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<string>", line 1
>     dynVar=1
>           ^
> SyntaxError: invalid syntax
>
> Q1: Why is the "syntax error" issued ?
> Q2: *HOW* do I achieve a dynamic assignment ?
>

For Q2, if using a dictionary just won't do it, look into using setattr.
>From 2.3 Built-in Functions:

setattr(object, name, value)
This is the counterpart of getattr(). The arguments are an object, a string
and an arbitrary value. The string may name an existing
attribute or a new attribute. The function assigns the value to the
attribute, provided the object allows it. For example,
setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

One way of adding a variable to the main namespace is:

>>> import sys
>>> setattr(sys.modules['__main__'],'abc','def')
>>> abc
'def'

HTH,

Emile van Sebille
emile at fenx.com

---------





More information about the Python-list mailing list