[Tutor] compiled Python Files ?? [print / .pyc and import]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 9 Dec 2001 14:25:21 -0800 (PST)

> I created three simple files to test with:
> *************************************************************
> F1.py file and all it contains is:
> print "Hello"
> *************************************************************
> Another file F2.py that contains:
> print "JSmith"
> *************************************************************
> I have one more FX.py file that contains:
> import F1.py
> import F2.py

Hmmm... did this work?  Your FX.py file might need:

import F1
import F2

instead: Python knows how to look for Python modules, as long as we give
it the name.  It knows that '.py' files hold Python modules, so we don't
need to put the extension here when we import modules.

> So, here are my questions. Although I didn't request it, Python did a
> line feed between Hello and JSmith, is this normal?

Yes.  The 'print' statement puts in a "line feed" for convenience, so that
people aren't surprised when they try something like this:

>>> def test():
...     print "Hello"
...     print  
...     print "world!"
>>> test()


This way, we can skip lines just by doing a


which many feel is nice.

However, perhaps we don't want 'print' to skip lines.  If we put a
trailing comma on a print statement, 'print' will put a space instead:

>>> def test2():
...     print "hello",
...     print "world!"
>>> test2()
hello world!

> After I ran this, I noticed that I had two new versions of F1 and F2;
> the directory showed "Compiled Python file" as a description and they
> had .pyc extensions. Why didn't I see this happening with my other
> tests? Is it because the other tests imported Tkinter?

It's because your FX.py program imported the other two 'modules' --- doing
an import has this effect.  Let's talk about this below.

> I understand I can run the .pyc files, instead of the .py files. Is
> this true?

Yes, it's true.  However, I wouldn't recommend deleting the .py files,
sine the .pyc files are very unreadable.  *grin*

> Why didn't I get a FX.pyc file also... ? The first two files compiled but 
> the third file that imported the other two didn't.

Ah!  But if we had a third program that did something like:

import FX

Python will make an FX.pyc file for us.

A 'pyc' file is Python's representation of our program.  Python needs to
chew our Python "source" into small bytecodes, because the underlying
Python engine can deal with these bites...er... bytes fairly easily.  In
many cases, these bytecodes are just kept in memory, and disappear after a
program is done.

However, If a module is imported, Python expects that it might be worth it
to save the bytecodes to disk, so that next time, if we ever import that
module again, Python can just slurp up the .pyc file instead of chewing.  
.pyc files are there to allow our programs to be loaded faster, but that's
about it.