exec example - I don't understand

Discussion in 'Python' started by kepes.krisztian, Jun 29, 2004.

  1. Hi !

    In


    Unifying types and classes in Python 2.2

    article I see that:

    We can also use the new type in contexts where classic only allows
    "real" dictionaries, such as the locals/globals dictionaries for the
    exec statement or the built-in function eval():
    3

    But I dont' understand that:
    exec "x = 3; print x" in a

    So what this code do ?
    Why we need "in a" ?

    This get same result !

    Thanx for help:
    FT
     
    kepes.krisztian, Jun 29, 2004
    #1
    1. Advertisements

  2. kepes.krisztian

    Peter Otten Guest

    First we make sure there's no variable x in the global namespace:Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    NameError: name 'x' is not defined

    Underneath, the global namespace is just a dictionary with the variable
    names as keys and the objects as values.False

    Now let's use our own dictionary d as the namespace for the exec statement:
    This leaves the global namespace unaffected:False

    Instead 1 is stored under the key "x" in the dictionary we provided:
    1

    Now let's repeat the same exec statement without explicitly providing a
    dictionary. Python will then use globals() as the default. Therefore a
    variable x with the value 1 will "magically" appear:1

    Peter
     
    Peter Otten, Jun 29, 2004
    #2
    1. Advertisements

  3. The 'in a' tells exec to run the code using the dictionary a to read and
    store variables. In this case, when x is set equal to 3, it's actually
    a['x'] being set to 3. Try these examples to get an idea for what's going
    on:
    10
     
    Christopher T King, Jun 29, 2004
    #3
  4. HI !

    Thanx for every answer.
    But it is a "bad" thing: when I think to I know something about python I
    get some not understanded source code with helpful people's answers, and
    them show me that I don't know nothing...

    :)

     
    fowlertrainer, Jun 29, 2004
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.