Putting If Name Equals Main Inside Functions

Ok, so I haven’t done much blogging in a while (I’ve been busy focusing on learning things, I swear!!), but I just discovered a cool thing while writing a Bencoder:

YOU CAN PUT if __name__ == ‘__main__’: statements inside of functions, and they will run in their place in the program & not disrupt the normal flow of the program, either when you run it as main, or import it.


def ben_str(text):
print ‘Bencoding ‘ + text
length = str(len(text))
data = str(length + “:” + text)
print “Becoded: ” + data + “\n”
if __name__ == ‘__main__’:
print “test”
return data

if name == ‘__main__’:


Bencoding “text”
Bencoded: 4:text


Would I Ever Do This??

Hopefully not, but it’s cool to know that you can!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s