calling a function without changing scope

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • trihaitran
    New Member
    • Feb 2008
    • 7

    calling a function without changing scope

    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:

    [code=python]
    def main():
    a = 'man'
    b = 'dog'

    def insideFunc():
    print 'used local variable %s' % a
    print 'used local variable %s' % b

    insideFunc()
    [/code]

    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?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by trihaitran
    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:

    [code=python]
    def main():
    a = 'man'
    b = 'dog'

    def insideFunc():
    print 'used local variable %s' % a
    print 'used local variable %s' % b

    insideFunc()
    [/code]

    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?
    Functions defined in the same module share the same global namespace. Use the global statement to access a variable in one function that is defined in another. I discourage the use of global variables and design my code to pass objects back and forth. Have you considered encapsulating your functions in a class object? It probably is a good idea to bust up large blocks of code into smaller ones.

    Comment

    Working...