pythonscopeglobalprogram-entry-pointdefined

python - the scope of variables inside "main" function


This is my first post here, so please give me some constructive criticism (not too much).

My initial intent was to receive inputs from the user, and save them into variables to later user in other functions (in other modules).

This is a simplified version of what i am trying to do: i tried both with and without the "global inputfile" line, unsuccessfully. I also tried sending the variable as an argument to a function outside, it didnt work. I also tried importing the main module to the other module, it didnt work.

The code:

def main(argv):
    inputfile = "a"

if __name__ == "__main__":
    global inputfile
    print(inputfile)

gives me the following error:

NameError: name 'inputfile' is not defined

Thank you for your time.


Solution

  • You need to call the function in order to acces the function value.

    def main():
        global inputfile
    
        inputfile = "a"
    
    if __name__ == "__main__":
        main()
        print(inputfile)
    

    Gives #

    a