Search code examples
pythonglobal-variablespython-modulepython-interactivepythoninterpreter

python __name__ global variable gives different output than expected


I am trying to get a hands-on in python modules.

my code is,

#filename:module.py
def printname():
    print __name__

printname()

when I am executing the code with interpreter

python module.py

It gives output(i.e. module name as)

main

and when I import the module into another file and calling the module there it gives output as module name(expected).

module

according to docs, It should give module name as output. Why is the variation in output??


Solution

  • The main script is always called __main__. This is entirely correct behaviour.

    From the very same page you linked to, in the preceding Executing modules as scripts section, you'll find:

    When you run a Python module with

    python fibo.py <arguments>
    

    the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__".

    For everything you import, __name__ will reflect the module name under which it was first available.

    Also see the Interface options documentation:

    <script>

    [...]

    If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.

    and the __main__ Top-level script environment documentation:

    This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt.