code_junkie

What is the scope for imported classes in python?

Nov 11th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. ## File 1
  2. def f1(): print "go f1!"
  3.  
  4. class C1(object):
  5. def do_eval(self,x): # maybe this should be do_evil, given what happens
  6. print "evaling"
  7. eval(x)
  8. eval(x,globals(),locals())
  9.  
  10. ## interactive
  11. class C2(object):
  12. def do_eval(self,x): # maybe this should be do_evil, given what happens
  13. print "evaling"
  14. eval(x)
  15. eval(x,globals(),locals())
  16.  
  17. def f2():
  18. print "go f2!"
  19.  
  20. from file1 import C1
  21. import file1
  22.  
  23. C1().do_eval('file1.f1()')
  24. C1().do_eval('f1()')
  25. C1().do_eval('f2()')
  26.  
  27. file1.C1().do_eval('file1.f1()')
  28. file1.C1().do_eval('f1()')
  29. file1.C1().do_eval('f2()')
  30.  
  31. C2().do_eval('f2()')
  32. C2().do_eval('file1.f1()')
  33. C2().do_eval('f1()')
  34.  
  35. >>> class C1(object):
  36. >>> def eval(self, x):
  37. >>> x()
  38. >>>
  39. >>> def f2(): print "go f2"
  40. >>> c = C1()
  41. >>> c.eval(f2)
  42. go f2
  43.  
  44. ## File 1
  45. def f1(): print "go f1!"
  46.  
  47. class C1(object):
  48. def do_eval(self, x, e_globals = globals(), e_locals = locals()):
  49. eval(x, e_globals, e_locals)
  50.  
  51. >>> def f2():
  52. >>> print "go f2!"
  53. >>> from file1 import * # 1
  54. >>> C1().do_eval("f2()") # 2
  55. NameError: name 'f2' is not defined
  56.  
  57. >>> C1().do_eval("f2()", globals(), locals()) #3
  58. go f2!
  59. >>> C1().do_eval("f1()", globals(), locals()) #4
  60. go f1!
Add Comment
Please, Sign In to add comment