Can someone explain this behavior to me?

Discussion in 'Python' started by Jesse Aldridge, Feb 26, 2009.

  1. I have one module called
    class Foo:
    foo = None

    def get_foo():

    if __name__ == "__main__":
    import bar = "foo"
    Jesse Aldridge, Feb 26, 2009
    1. Advertisements

  2. Jesse Aldridge

    Chris Rebert Guest

    Not sure, but circular imports are *evil* anyway, so I'd suggest you
    just rewrite the code to avoid doing any circular imports in the first

    Chris Rebert, Feb 26, 2009
    1. Advertisements

  3. Jesse Aldridge

    John Machin Guest

    AFAICT from that convoluted mess, because there are two rabbit holes, and, and you poked "foo" down the wrong
    one. In any case the other one is not the right one -- as you have
    already been advised, circular imports are evil.
    John Machin, Feb 26, 2009
  4. AFAICT you have 2 different "foo" modules here. The first foo is when is called as a script, but it's not called "foo" it's called
    "__main__" because it's called as a script. When "bar" is imported, it
    imports "foo", but this is different. Technically this is the first time
    you are *importing* foo. It's actually loaded a second time with the
    name "foo".

    A more simplified version of it is this:

    $ cat
    cat = 6
    import bar
    print '%s: = %s' % (__file__, __name__, cat)

    $ cat
    import foo = 7
    print '%s: = %s' % (__file__, foo.__name__,

    $ python
    /home/marduk/test/ = 6
    /home/marduk/test/ = 7 = 6

    $ python -c "import foo" = 7 = 7

    But, as others have said, this is confusing and should be avoided.

    Albert Hopkins, Feb 26, 2009
  5. Jesse Aldridge

    Steve Holden Guest

    There are actually two get_foo()s, since is run (giving it the
    name "__main__") and imported (giving it the name "foo"). You will
    probably find that __main__.get_foo() == "foo".

    Steve Holden, Feb 27, 2009
  6. Ah, I get it.
    Thanks for clearing that up, guys.
    Jesse Aldridge, Feb 27, 2009
    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.