Advertisement
nher1625

dynamic_scoping

Apr 3rd, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. __author__ = 'Neys'
  2.  
  3. """
  4. Create a function add(n) which returns a function that always adds n to any number
  5.  
  6. addOne = add(1)
  7. addOne(3) # 4
  8.  
  9. addThree = add(3)
  10. addThree(3) # 6
  11. """
  12.  
  13. # Question is about the principles of closure. AKA a technique for implementing lexically scoped name binding.
  14. """Lexical scoping: Use of local variables. Local means variables with limited scope, that only exist within a specific
  15. function. Helps avoid name collision between 2 identically named variables.
  16.  
  17. So what does it mean to be within a function? If a variable is within the scope of a certain function then its scope
  18. is effectively the block of code following the function definition. In that block the variable name exists, and is bound
  19. to an assigned value. Outside the block the variable name does not exist.
  20.  
  21. Dynamic Scoping:
  22. If the variable name's scope is in a certain function, then it's scope is the time frame with which the function is
  23. executing. (While function is running the variable name exists and is bound to a value.) After the function returns the
  24. variable name does not exist. """
  25.  
  26. pi = 3.1415  # create variable pi in global scope
  27. pi_holder = None
  28.  
  29. def create_area():
  30.     pi_holder = pi  # local variable, different from pi_holder outside
  31.  
  32.     def area(r):
  33.         return pi_holder*r*r
  34.  
  35.     return area  # area() gives error
  36.  
  37. area = create_area()
  38.  
  39. print("area(10) = ", area(10))
  40. del pi_holder  # delete global pi_holder w/o mutating local lexical pi_holder
  41.  
  42. try:
  43.     pi_holder # proves pi_holder is created and removed within scope of create_area() and is local to area(r)
  44. except NameError:
  45.     print("pi_holder is empty")
  46.  
  47. print("area(100) = ", area(100))
  48.  
  49.  
  50. x = 42
  51. def local_var_test():
  52.     temp = x  # correct variable assignment
  53.     print("LHS temp assignment to global variable x = ",temp)  # 42
  54. #   x = temp  # incorrect because x is referenced before assignment to local scope of x
  55. #   print(x)  # incorrect also
  56.  
  57. n = None  # define n
  58.  
  59. def add(n=n):  # n is what it is arg passed upon function
  60.     def add_to_n(k):
  61.         return k + n
  62.     return add_to_n
  63.  
  64. addOne = add(1)
  65. addTwo = add(2)
  66. addZero= add(0)
  67. print(addZero(7))
  68.  
  69. # Final Solution!
  70. def add(n):
  71.     def add_to_x(x):
  72.         return x + n
  73.     return add_to_x
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement