Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the `if __name__ == "__main__": ` like idioms have a name of design pattern?

Do these following idioms (to write a module which is also an executable/runnable) have a name of design pattern?

In Python, we can write a module as an executable too with if name == 'main': idiom:

if __name__ == "__main__":
    main()

Similar idiom can be found in Ruby:

if __FILE__ == $0
  main()
end

Also same effect can be achieved differently in Perl too:

main() unless caller;

In Tcl, you may write:

if {![info level] && [info script] eq $::argv0} {
    main
}

Although these are implemented in different ways, they share the same goal: make single script file both a module and an executable/runnable. It seems to me a design pattern. How do you call them? I personally have been called them as Executable Module or Runnable Module, but I want to know the more common name if it exists.

like image 344
hkoba Avatar asked Jul 04 '18 03:07

hkoba


People also ask

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.

Is if name == Main necessary?

The Reason Behind if __name__ == '__main__' in Python You might have seen this one before: the syntax which often gets ignored because it doesn't seem to hinder the execution of your code. It may not seem necessary, but that's only if you're working with a single Python file.

What is if __ name __ in Python?

When a Python interpreter reads a Python file, it first sets a few special variables. Then it executes the code from the file. One of those variables is called __name__ .

What does __ main __ mean in Python?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.


1 Answers

In Perl, this pattern is known as a modulino. I believe the term was coined by brian d foy in his book Mastering Perl. I don't often see the name applied for languages other than Perl, but it does happen.

Edit to add: the name goes back earlier than that. Here's an article from 2004 that uses the term.

like image 53
mob Avatar answered Oct 22 '22 06:10

mob