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.
if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
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.
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__ .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With