For some reason this code produces error:
import os
def main():
print(os.path.isfile('/bin/cat'))
import os
if __name__ == '__main__':
main()
Result:
Traceback (most recent call last):
File "test.py", line 10, in <module>
main()
File "test.py", line 5, in main
print(os.path.isfile('/bin/cat'))
UnboundLocalError: local variable 'os' referenced before assignment
Why it happens? Note that at beginning of both cases there is import os
. Somehow additional import in the end of the body of a function affects whole scope of this function.
If you remove import inside the function, everything is fine (which is not surprising).
import os
def main():
print(os.path.isfile('/bin/cat'))
# import os
if __name__ == '__main__':
main()
Result:
True
About possible duplicates: There are some similar questions, but regarding global variables, not imports.