Take the tour ×  I'm trying to define variable inside function.
vars() shows variable is created, but gives me NameError:
exception. What am I doing wrong?  def a(str1):     vars()
[str1] =  1     print vars()     print b    {'str1': 'b', 'b':
1}   NameError: global name 'b' is not defined share|improve
this question possible duplicate of Python vars() global name
error –  Thomas Jul 15 '10 at 16:35 add comment  3 Answers  up
vote 2 down vote accepted  Your code works for me. Perhaps you
should try an alternative approach:  exec(str1 + '=1')  This
will execute b=1  share|improve this answer strange, i tried on
mac py 2.6.4 and on linux py 2.5.4, doesn't work.. –  damir Jul
15 '10 at 16:31 exec() inside a function scope will work within
that function local scope. –  msw Jul 15 '10 at 16:46 add
comment  You're invoking undefined behaviour. From the
documentation of vars():  Note The returned dictionary should
not be modified: the effects on the corresponding symbol table
are undefined.  Other answers give possi