Search code examples
pythonfunctionparameter-passingnested-function

Python - Proper way to call nested functions?


Lets say you have the following code

def set_args():
    #Set Arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("-test", help = 'test')
    return parser

def run_code():
    def fileCommand():
        print("the file type is\n")
        os.system("file " + filename).read().strip()

def main():
    parser = set_args()
    args = parser.parse_args()
    

what is best way to call that fileCommand() function from def main():?

I have the following code which of course doesn't work:

def main():
    parser = set_args()
    args = parser.parse_args()
    
    #If -test, 
    if args.test:
        filename=args.test
        fileCommand()

So if you were to run python test.py -test test.txt it should run the file command on it to get the file type

I know if I keep messing around I'll get it one way or another, but I typically start to over complicated things so its harder down the line later. So what is the proper way to call nested functions?

Thanks in advance!


Solution

  • Python inner functions (or nested functions) have many use cases but in non of them, accessing through the nested function from outside is an option. A nested function is created to have access to the parent function variables and calling it from outside of the parent function is in conflict with principle.

    You can call the function from the parent function or make it a decorator:

    Calling the nested function from the parent would be:

    def run_code(filename):
        def fileCommand():
            print("the file type is\n")
            os.system("file " + filename).read().strip()
        fileCommand()
    

    If you describe more about your use case and the reason why you want to run the code like this, I can give more details about how you can implement your code.