Home » An R equivalent for Python’s if __name__ == ‘__main__’

An R equivalent for Python’s if __name__ == ‘__main__’

  • by
Want to do a random act of kindness? Share this post.

In this blog post, I describe to ways to deal with code you do not want to run when it is sourced from an external file in R.

When Python sources code it does a particular thing, it assigns the string ‘__main__’ to the __name__ variable in that code. However, if Python sources code from a module it will assign the filename of the code to the __name__ variable and strip the ‘.py’ from it. This makes it easy for you if you want to run code within a file, but don’t want it to run when your code is sourced from another file.

In this example, foo() will only run when the code isn’t sourced from an external file (e.g. with import foo).

if __name__ == '__main__':
    ...your code...

This is extremely useful if your script is a library, and running the script an sich is only for doing unit tests or for tinkering.It’s somewhat of a pitty that this doesn’t exist in R. However, there are some workarounds that offer similar functionality.

This chunk of code will check if the source code is actually the environment (or frame) with level 0 — e.g. the .GlobalEnv. If this is new to you, that’s fine, since this is some hard-core under the hood level stuff. If you want to know more: Hadley Wickham has written an in-depth guide to environments.

if (sys.nframe() == 0) {
    ...your code...

Another way you could approach this, is by using options. This way, you could set an option in an external script, source your code and only run certain chunks when the options meets the criteria. This should be in your main.R file.

main <- function() {
    ...your code...

if (getOption('run.main', default=TRUE)) {

And this should be in the file where you’re calling main.R from, if you don’t want …your code… to run.


Great success!

Want to do a random act of kindness? Share this post.