[Tutor] Class and Scope Question

Tim Johnson tim at johnsons-web.com
Fri May 6 03:44:13 CEST 2005


The following test script is kind of got me baffled:
#!/usr/local/bin/python
class Eval:
    def __getitem__(self,key):
        return eval(key)
##def test():
##  i = 100
##  b = ["My", "name", "is", "Tim"]
##  test = "this is number %(str(i))s for a test %(' '.join(b))s"
##  s = test % Eval()
##  print s
##test()
i = 100
b = ["My", "name", "is", "Tim"]
test = "this is number %(str(i))s for a test %(' '.join(b))s"
print test % Eval()
## ============================================================
Running this gives me the following :
[tim at linus baker]$ python test.py
this is number 100 for a test My name is Tim
## cool!
Now if I comment out the last four lines and uncomment
the previous 7, I get the following error message:
[tim at linus baker]$ python test.py
Traceback (most recent call last):
  File "test.py", line 11, in ?
    test()
  File "test.py", line 9, in test
    s = test % Eval()
  File "test.py", line 4, in __getitem__
    return eval(key)
  File "<string>", line 0, in ?
NameError: name 'i' is not defined
## It's been a lloooonngg day. What am I missing here?
Explanation and solution is no doubt going to further edify
me about python.

TIA
tim

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com


More information about the Tutor mailing list