Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like Python's `if __name__ == "__main__":` stuff in Common Lisp

I wrote two functions in two separated files, assumed to be file A.lisp and B.lisp, where both files have some main program code for test and A.lisp would call the function in B.lisp. This means using the load method directly in A.lisp would execute the main code in B.lisp, which is not supposed to happen. And these files are, in my opinion, too small to be considered using something like package.

Is there anything like Python's if __name__ == "__main__": stuff in Common Lisp? Top-level code that's wrapped inside this condition will only be executed if the current file is the main module, i.e. the running program, but not if it's imported as a library.

like image 256
lastland Avatar asked Dec 12 '22 06:12

lastland


2 Answers

Packages are only namespaces for symbols. They don't say anything about loading or compiling code.

Common Lisp does not have the idea of a library, module or even something like a 'main' module/routine in its ANSI Common Lisp standard. The standard defines two routines PROVIDEand REQUIRE. But those are not very well specified.

Most applications and libraries use a 'system' tool to structure, specify, compile and load code.

There is a 'free' one called ASDF. 'Another System Definition Facility'. For most types of applications a tool like ASDF is useful. For primitive applications you can write your own tools using standard functions like COMPILE-FILEand LOAD.

Nick Levine wrote a tutorial for ASDF (part of his abandoned Lisp book project): Systems.

Several Lisp implementations have more extensive facilities to create applications (for example Mac OS X applications written with Clozure Common Lisp).

like image 151
Rainer Joswig Avatar answered May 26 '23 21:05

Rainer Joswig


The if __name__ == "__main__": idiom is very specific to Python, and even some people in the Python community consider using it for test code bad style.

With Common Lisp's high emphasis on interactive development in the REPL, it would actually be a disadvantage to have to reload the whole file each time you want to run the tests. Just put the tests into a function definition instead of the top level, it works and is more convenient.

like image 27
Rörd Avatar answered May 26 '23 22:05

Rörd