Vars () in Python giving different results

When I run this code:

a = '1'
vars()['a'] = '2'
print a

I get the following output:

2

But when I run this code:

def bar():
    a = '1'
    vars()['a'] = '2'
    print a

bar()

I get the following output:

1

Now my question is: why is this happening and how can I make the second case, give me the same solution as the first case.

Edit:

Could not find a solution, but I found a small hack around it ... Although I will not use exec:

def bar():
    a = "a"
    b = "b"
    exec a+"="+b
    print a

bar()

Which gives me the result:

b

If someone can find a better solution, then it would be great. I don't set any global variables this way or do anything crazy, so don't worry about that.

+3
source share
2 answers

, __dict__ vars(). , , .

(http://docs.python.org/library/functions.html#vars):


vars([object]) __dict__ , , __dict__.

, , __dict__; __dict__ (, dictproxy ).

, vars() locals(). : locals , locals.


, self. = val setattr(self, 'x', val) ?

+2

vars() . , / / python. , ( regex groupdict ), .

+1

All Articles