Newbie questions on import & cmd line run

Dave Angel d at davea.name
Thu May 17 04:53:24 EDT 2012


On 05/17/2012 12:54 AM, alex23 wrote:
> On May 17, 11:45 am, gwhite <gwh... at ti.com> wrote:
> <SNIP>

> I don't think that only-one-import is true for scripts that are run
> from the command line, though. They can exist as both '__main__' and
> their actual name in the module table. (Someone please correct me if
> this understanding is wrong...)

You're basically right, and this is the source of many bugs.  Importing
the file that was the original script can cause many subtle bugs, much
worse than the general "circular imports" problem, because it's not
obvious that there are two complete instances of the code and data.

There have been many lengthy threads triggered by such a bug, and the
cure is always to eliminate the circle.  If you find you need to
reference back to the original script's objects by module namespace,
then it ought to be refactored.  The script would then consist of
something as simple as

import  realcode
if __name__ == "__main__":
    realcode.main()

else:
    print "Don't import this file, it's not a module"


At this point, other modules could also import realcode, and use its functions and global data.


-- 

DaveA




More information about the Python-list mailing list