-1

I have a script test.py and I want it to execute another script this_other_script.py which will return a list object. test.py looks like:

if __name__ == '__main__':
    someValue = this_other_script

    print(len(someValue))

this_other_script.py looks like:

if __name__ == '__main__':
    data = [a,b,c,d]
    return(data)

When I run test.py I receive an error of SyntaxError: 'return' outside function.

If this is due to program scope I would have thought it would be OK for the calling program to be given a return value from a program it is calling. I wouldn't expect for this_other_script to access a value of a variable not given to it by test.py so I'm not sure why this error is displayed.

uncle-junky
  • 723
  • 1
  • 8
  • 33
  • The error message tells you everything you need to know: you have a `return` statement that is not inside a function. What are you not understanding? – Daniel Roseman Jun 09 '19 at 18:00

2 Answers2

1

in test.py:

if __name__ == '__main__':
    import this_other_script
    someValue = this_other_script.get_data()

    print(len(someValue))

in this_other_script.py:

def get_data():
    data = [1,2,3,4]
    return(data)
  • Does `this_other_script.py` need the `if __name__ == '__main__':` or not? E.g. `if __name__ == '__main__':get_data()` where `def get_data():` function has been declared at the top? – uncle-junky Jun 09 '19 at 18:07
  • If I included the `if __name__ == "__main__"` in this_other_script.py, it would not work. This is because, as you said, you are executing test.py with python. I found this explanation helpful (https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – time_is_a_drug Jun 09 '19 at 18:14
  • I think I misunderstood your comment, I will add an additional answer with what you said. – time_is_a_drug Jun 09 '19 at 18:26
0

alternative answer:

in test.py

if __name__ == '__main__':
    import this_other_script
    someValue = this_other_script.get_data()

    print(len(someValue))

in this_other_script.py:

def get_data():
    data = [1,2,3,4]
    return(data)


if __name__ == '__main__':
    get_data()