10

Checking to see if __name__ == '__main__' is a common idiom to run some code when the file is being called directly, rather than through a module.

In the process of writing a custom command for Django's manage.py, I found myself needing to use code.InteractiveConsole, which gives the effect to the user of a standard python shell. In some test code I was doing, I found that in the script I'm trying to execute, I get that __name__ is __console__, which caused my code (dependent on __main__) to not run.

I'm fairly certain that I have some things in my original implementation to change, but it got me wondering as to what different things __name__ could be. I couldn't find any documentation on the possible values, nor what they mean, so that's how I ended up here.

2 Answers 2

9

from the document of class code.InteractiveInterpreter([locals]):
The optional locals argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key '__name__' set to '__console__' and key '__doc__' set to None. maybe u can turnning the locals argument, set __name__ with __main__, or change the test clause from

if __name__ == '__main__'
to  
if __name__ in set(["__main__", "__console__"])

Hope it helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Probably don't need the set() or list, could use a single tuple of strings.
@GringoSuave agree,:)
6

__name__ is usually the module name, but it's changed to '__main__' when the module in question is executed directly instead of being imported by another one.

I understand that other values can only be set directly by the code you're running.

1 Comment

See docs.python.org/reference/toplevel_components.html for additional information. __name__ IS the module name. __main__ is a special module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.