calling a function without changing scope

Thread Solved

Join Date: Dec 2006
Posts: 28
Reputation: trihaitran is an unknown quantity at this point 
Solved Threads: 0
trihaitran trihaitran is offline Offline
Light Poster

calling a function without changing scope

 
0
  #1
Feb 20th, 2008
Hi,

My problem is that I have a large function with hundreds of lines. I want to break it apart into smaller functions. The issue is that if I make a module level function, the scope changes and I have to pass the necessary variables to it. This can be difficult if there are 10 variables that need to be passed. So basically I want to be able to call a function inside another function but keep the scope the same. I found a way to do something like this by defining a function inside another function:

  1. def main():
  2. a = 'man'
  3. b = 'dog'
  4.  
  5. def insideFunc():
  6. print 'used local variable %s' % a
  7. print 'used local variable %s' % b
  8.  
  9. insideFunc()

The thing with this is that it doesn't really shorten my larger function. So is it possible to get the effect of the above code with insideFunc defined somewhere that is not inside of main?
Reply With Quote Quick reply to this message  
Join Date: Dec 2006
Posts: 999
Reputation: woooee is a jewel in the rough woooee is a jewel in the rough woooee is a jewel in the rough 
Solved Threads: 283
woooee woooee is offline Offline
Posting Shark

Re: calling a function without changing scope

 
0
  #2
Feb 20th, 2008
You can use a class to do that in the following way. You could also use a list or dictionary as a container for the 10 variables and pass one list/dictionary instead of 10 variables. IMHO using the class method is preferred.
  1. class test_class:
  2. def __init__(self):
  3. self.a="dog"
  4. self.b="cat"
  5. self.c=1
  6. print "__init__, a, b, c =", self.a, self.b, self.c
  7. self.first_func()
  8. self.second_func("abc")
  9. def first_func(self):
  10. self.c += 1
  11. print "first_func, a, b, c =", self.a, self.b, self.c
  12. def second_func(self, d):
  13. self.c += 1
  14. print "second_func a, b, c =", self.a, self.b, self.c
  15. print "d =", d
  16.  
  17. if __name__ == "__main__":
  18. TC=test_class()
  19. print "\n now calling the functions from outside the class"
  20. TC.first_func()
  21. TC.second_func("xyz")
Last edited by woooee; Feb 20th, 2008 at 4:18 pm.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC