Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the different possible values for __name__ in a Python script, and what do they mean?

Tags:

python

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.

like image 429
Xiong Chiamiov Avatar asked Jul 10 '09 21:07

Xiong Chiamiov


People also ask

What does __ name __ in Python mean?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.

What does _ and __ mean in Python?

The use of double underscore ( __ ) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python mangles these names and it is used to avoid name clashes with names defined by subclasses.

What is meaning of if __ name __ == '__ Main__?

if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.

What will be the value of __ name __ attribute of the imported module?

The value of __name__ attribute is set to “__main__” when module is run as main program. Otherwise, the value of __name__ is set to contain the name of the module. We use if __name__ == “__main__” block to prevent (certain) code from being run when the module is imported.


1 Answers

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.

like image 151
sunqiang Avatar answered Sep 18 '22 05:09

sunqiang