importing part of a module without executing the rest

George Sakkis george.sakkis at gmail.com
Sat Jun 14 01:02:26 CEST 2008


On Jun 13, 5:52 pm, krishna.00... at gmail.com wrote:
> file1.py
> ----------
> a = 20
> from abc import *
> print "Should this be printed when 'a'  is alone imported from this
> module"
>
> file2.py
> ----------
> from file1 import a
> print a
>
> (snipped)
>
> Of course, the option of using if __name__ == '__main__' in file1.py
> for statements following 'a = 20' is not useful in my case as I need
> all statements in file1 to be exectued when imported by someone else
> (say file3.py)

That's a bad code smell. In general, modules intended to be imported
should not have any side effects at global scope before the "if
__name__ == '__main__':" part. Put the "print ..." and all other
statements with side effects in one or more functions and let the
importing module call them explicitly if necessary.

George



More information about the Python-list mailing list