Equivalent to Perl Modulino for Ruby, Python?
Asked Answered
P

3

3

I know Perl has a design pattern known as a modulino, in which a library module file can act as both a library and a script. Is there any equivalent to this in Ruby / Python?

I think this design pattern would be very useful for me; I'm writing workers that are fairly short, but also require a script to run them. I think it would be convenient to have this all run from the same place.

Popup answered 29/4, 2013 at 21:50 Comment(0)
E
7

Python has __name__:

class MyClass(object):
    pass

if __name__ == '__main__':
    print("This will only run if you run the script explicitly, not import it")

If you run python myscript.py, the print function will run. If you import MyClass from myscript, the print will not.

Evelinaeveline answered 29/4, 2013 at 21:55 Comment(1)
Thank you, this is exactly what I was looking for. Now to find the equivalent for Ruby...Popup
T
7

This is the Ruby version:

if __FILE__ == $PROGRAM_NAME #equivalent: if __FILE__ == $0
  puts "This is the main file running, it is not being required."
end
Treacy answered 29/4, 2013 at 22:38 Comment(0)
W
2

Perl 6 has this feature built in. You define a subroutine named MAIN that executes if you use the file as a script:

 sub MAIN { ... }

The signature for MAIN tells Perl 6 how to parse the command-line parameters. You can have multi-subs and Perl 6 will use the one whose signature matches. Here's the example from Synopsis 6:

multi MAIN (Int $i) {...}   # foo 1
multi MAIN (Rat $i) {...}   # foo 1/2
multi MAIN (Num $i) {...}   # foo 1e6
multi MAIN ($i) {...}       # foo bar
Whichever answered 24/11, 2016 at 4:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.