15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

import import2<br />

And here are the contents of import2.py:<br />

# import2.py<br />

print 'loaded import2'<br />

Here is the output when we import import1 from <strong>Python</strong>:<br />

>>> import import1<br />

loaded import1<br />

loaded import2<br />

>>><br />

Following our suggested workaround of checking the value of __name__, we can change the code in<br />

import1.py and import2.py so that this behavior does not occur.<br />

Here is the modified version of import1.py:<br />

# import1.py<br />

import import2<br />

if __name__ == '__main__':<br />

print 'loaded import1'<br />

The following is the code for import2.py, changed in the same manner:<br />

# import2.py<br />

if __name__ == '__main__'<br />

print 'loaded import2'<br />

We no longer get any output when we import import1 from <strong>Python</strong>:<br />

>>>import import1<br />

>>><br />

Now it does not necessarily mean that this is the behavior you should code for all situations. There may<br />

be cases where you want to display output to confirm a module import. It all depends on your situation.<br />

Our goal is to provide pragmatic programming examples to prevent unintended side effects.<br />

14.4.2. execfile()<br />

It should seem apparent that importing a module is not the preferred method of executing a <strong>Python</strong><br />

script from within another <strong>Python</strong> script; that is not what the importing process is. One side effect of<br />

importing a module is the execution of the top-level code.

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

Saved successfully!

Ooh no, something went wrong!