some questions....

Tim Roberts timr at probo.com
Tue Nov 26 02:34:25 EST 2002


eugene kim <eugene1977 at hotmail.com> wrote:
>
>#!/usr/local/bin/python
>
>wow.. i thought python is easy to learn..
>but there are lot's of corks..
>namespace, scoping rule, exec, eval..
>all confuses me..

It really isn't all that complicated.  You're just playing on the edges.

>class simple:
>    def __init__(self,value):
>        self.value = value
>        if value == 4 :
>            print c ## <--- ok
>            print C ## <--- error

As far as I'm concerned, it is only an accident that the first "print"
statement works.  In fact, I didn't believe it until I tried it.

Variables do not exist until they are created.  Since "c" and "C" are not
defined in the function or the class, you're getting the global value.  In
most cases, globals are to be avoided.

>if __name__ == '__main__':
>    a = 3;
>    b = 4;
>    c = simple(a)

At this point, the variable "C" does not exist.  That's why you get an
error.  What surprises ME is that it was able to find "c".  What that tells
me is that the interpreter creates the object, assigns it to "c", and THEN
calls __init__.  __init__, then, is able to find the global variable "c".

>    d = simple(b)
>    print c
>    print d
>
>    exec "C = simple(a)"
>    print C

You said this was a question about exec, but in this case, your program
isn't even GETTING to the "exec" statement.  You're failing on the first
call to create a "simple" object.

>another question about exec
>aList = ['a', 'b']
>for aString in aList:
>    aString = myClass(aString)  ## <--error

This is not an error as is, although it is CERTAINLY bad style.  Perhaps
you should show us your definition of "myClass" so we can see what is
wrong.

>    exec "aString = myClass(aString)" ## <-- ok

I didn't have any trouble with the non-exec version.  However, in this
particular case, by the time your "exec" runs, "aString" is no longer a
1-character string: it is an instance of myClass, because of the first
statement.  If myClass.__init__ expects an instance of myClass to be passed
in, that's why the first call fails.


>a = 3
>b = a
>
>print eval("b") ## <--- arn't these same?
>print b

Yes, they are the same.

If you are a Python newbie, you are probably worrying about the wrong
things.  I've written a lot of Python application code, and I can count the
number of times I've used "eval" and "exec" on one hand.
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list