Walter Bright:

On 4/30/2014 8:54 AM, bearophile wrote:
I'd also like some built-in way (or partially built-in) to use a module only as "main module" (to run its demos) or as module to be imported. This problem is
solved in Python with the "if __name__ == "__main__":" idiom.

    dmd foo.d -unittest -main

I think you are greatly missing the point. The unittests are mainly for the developer, while the demo is for the user of the demo. The unittests validate the code, while the demo shows how to use the module (and surely the demo is not meant to run in parallel with the other unittests). Sometimes the demo part is more than a demo, it contains usable and useful code, with a command-line interface, to allow stand alone usage of the module functionality. Currently this is how I do it:


module foobar;

// Here functions and
// classes with their unittests

version (foobar_main) {
    void main() {
        // foobar module demo code here.
    }
}


I can't use just "version(main)", because the module could import other modules with their own demo sections. So I need something to tell them apart from each other.

This could be simplified with a solution similar to the Python one:

version (__is_main) {
    void main() {
        // foobar module demo code here.
    }
}


Now if I have module A and B, where B imports A, and both have the demo main, I can use this to compile A stand-alone with its demo:

dmd A.d

And I can use this to not compile the demo of A and compile the demo section of B:

dmd A.d B.d

This is just the basic idea, and perhaps people suggested something better than this.

Bye,
bearophile

Reply via email to