0

Assume these 3 files:

charNames.py

  a = 'Susan'
  b = 'Charlie'
  c = 'Jiji'

threenames.py

a = 'dead'
b = 'parrot'
c = 'sketch'
print a,b,c

storytime.py

#!/usr/bin/env python
import charNames
import threenames

print charNames.a
threenames

I run storytime.py (which is also chmod +x) by using ./storytime.py from Terminal, this is the output that I get:

$ ./storytime.py 
dead parrot sketch
Susan
$ 

Why does the result execute print a,b,c from threenames.py before it runs print charNames.a?

From my understanding, Python is a top down programming language, like bash. So should it print "Susan" first, then "dead parrot sketch"?

This is run on OSX, with Python 2.7.5

Danijel-James W
  • 1,356
  • 2
  • 17
  • 34

2 Answers2

4

In Python when you import a file it is executed. That is why you are seeing the output from threenames.py first, because it is executed right after it is imported.

If you want a way to only run code in a file if it is the main file and not an import, you can use this code in threenames.py:

if __name__ == '__main__':
    print a, b, c

If you run threenames.py, you will see a,b, and c printed because it is the main file, but when it is imported, it is module, so the print function and any other function calls inside that conditional will not be executed

samrap
  • 5,595
  • 5
  • 31
  • 56
3

When you import a file, that file is actually executed. So when you import threenames that file is executed, hence you getting output from within that (the print a,b,c) before you think you called output from it.

You need to avoid printing things out in external modules, instead printing the attributes within like you have with charnames.a.

You should instead use a main() function-like structure:

if __name__ == '__main__':
    print a, b, c
anon582847382
  • 19,907
  • 5
  • 54
  • 57