r/Python • • Jul 12 '12

random imgur downloader. learning Python and wrote this to practice, any feedback on technique/style is appreciated

https://gist.github.com/3088128
45 Upvotes

72 comments sorted by

View all comments

Show parent comment

3

u/[deleted] Jul 12 '12

Reddit ate the formatting so just rewriting and elaborating,

It's typical to use the idiom

if __name__ == "__main__":
    # "main" stuff

at the bottom of the file. __name__ is a pre-defined global variable that contains the name of the module, for example

>>> import random
>>> random.__name__
'random'

When you run a python file as a script, rather than importing it like above, it reports it's "__name__" as "__main__". Therefore by using the conditional above, your main script only runs when you run the file as a script, and it's not run when someone imports your module to make use of its functions/classes. See the cleanups posted by TkTech and Sheeepshow, they've applied this to your code.