question on "import __main__"

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • wen

    #1

    question on "import __main__"

    i have written some code in test.py as below:
    import __main__
    if __name__!='__ma in__':
    print 1

    print 2

    when i run test.py, i got
    2
    on the screen.

    now, i have some question about the code, 1. since no __main__ module at
    all, why it's legal to write "import __main__"?

    2. since if running a script independently, the __name__ should be
    '__main__', why it's not in the above code?


    thank you in advance.

    with my kind regards,
    Wen


  • Robert Kern

    #2
    Re: question on "import __main__"

    wen wrote:[color=blue]
    > i have written some code in test.py as below:
    > import __main__
    > if __name__!='__ma in__':
    > print 1
    >
    > print 2
    >
    > when i run test.py, i got
    > 2
    > on the screen.
    >
    > now, i have some question about the code, 1. since no __main__ module at
    > all, why it's legal to write "import __main__"?[/color]

    Because a module object is created for the running script. It is placed
    in sys.modules with the name "__main__". When you "import __main__", the
    import mechanism looks in sys.modules first for a module with the name
    "__main__" and uses that if it's there.
    [color=blue]
    > 2. since if running a script independently, the __name__ should be
    > '__main__', why it's not in the above code?[/color]

    It is. However, you wrote "!=" instead of "==".

    --
    Robert Kern
    rkern@ucsd.edu

    "In the fields of hell where the grass grows high
    Are the graves of dreams allowed to die."
    -- Richard Harter

    Comment

    • infidel

      #3
      Re: question on "import __main__"

      > import __main__[color=blue]
      > if __name__!='__ma in__':
      > print 1
      >
      > print 2
      >
      > when i run test.py, i got
      > 2
      > on the screen.
      >
      > now, i have some question about the code, 1. since no __main__ module at
      > all, why it's legal to write "import __main__"?[/color]

      __main__ is the module that the interpreter starts executing. So
      "import __main__" is legal, though I'm guessing it doesn't really do
      anything because the module is already loaded (since it's running).
      [color=blue]
      > 2. since if running a script independently, the __name__ should be
      > '__main__', why it's not in the above code?[/color]

      But it is.

      Comment

      Working...