12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

% python myclient.py13 346As for the rest of this one, mymod’s functions are accessible (that is, importable)from the top level of myclient, since from simply assigns to names in theimporter (it works almost as though mymod’s defs appeared in myclient). Forexample, another file can say this:import myclientmyclient.countLines(...)from myclient import countCharscountChars(...)If myclient used import instead of from, you’d need to use a path to get to thefunctions in mymod through myclient:import myclientmyclient.mymod.countLines(...)from myclient import mymodmymod.countChars(...)In general, you can define collector modules that import all the names from othermodules so they’re available in a single convenience module. Using the followingcode, you wind up with three different copies of the name somename (mod1.somename,collector.somename, and _ _main_ _.somename); all three share the same integerobject initially, and only the name somename exists at the interactive prompt as is:# File: mod1.pysomename = 42# File: collector.pyfrom mod1 import *from mod2 import *from mod3 import *# Collect lots of names here# from assigns to my names>>> from collector import somename5. Package imports. For this, I put the mymod.py solution file listed for exercise 3into a directory package. The following is what I did to set up the directory andits required _ _init_ _.py file in a Windows console interface; you’ll need to interpolatefor other platforms (e.g., use mv and vi instead of move and edit). Thisworks in any directory (I just happened to run my commands in <strong>Python</strong>’s installdirectory), and you can do some of this from a file explorer GUI, too.When I was done, I had a mypkg subdirectory that contained the files _ _init_ _.pyand mymod.py. You need an _ _init_ _.py in the mypkg directory, but not in itsparent; mypkg is located in the home directory component of the module searchpath. Notice how a print statement coded in the directory’s initialization filefires only the first time it is imported, not the second:C:\python25> mkdir mypkgC:\<strong>Python</strong>25> move mymod.py mypkg\mymod.pyC:\<strong>Python</strong>25> edit mypkg\_ _init_ _.py...coded a print statement...Part V, Modules | 663

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!