importing part of a module without executing the rest

Discussion in 'Python' started by krishna.000.k, Jun 13, 2008.

  1. 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

    file2.py is used in a context where 'from abc import *' statement
    doesn't make sense but it can make sense of (and requires) 'a'.
    But it seems we can't import just a part of the module and expect the
    rest to not be executed.
    Executing python file2.py executes the 'from abc ...' and the print
    statement following it in file1.py.

    Can't I just import 'a' into this name scope without touching the rest
    of the statements in the module (file1 in this case). If so, what the
    rationale behind such logic in the module 'import' mechanism of
    python?
    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)

    Don't I have any solution other than packaging those parts in file1.py
    (a = 20 and the rest of the statements) into different modules?
     
    krishna.000.k, Jun 13, 2008
    #1
    1. Advertisements

  2. 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
     
    George Sakkis, Jun 14, 2008
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.