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

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

Tags:

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)) {
   main()
}

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

options(run.main=FALSE)
source('main.R')

By the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. Hope it helps!

Great success!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

4 thoughts on “An R equivalent for Python’s if __name__ == ‘__main__’”

  1. Tremendous things here. I’m very satisfied to look your post.
    Thank you a lot and I’m taking a look forward to touch you.
    Will you please drop me a e-mail?

Leave a Reply

Your email address will not be published. Required fields are marked *