Skip to content

If we create our custom module and there are somt lines that must not be executed during imports in another py file we should put this code in:

if __name__ == "__main__":
    print("some code")

Name of python file that you DIRECTLY execute is __main__

Good imports styling:

"""
Illustration of good import statement styling.

Note that the imports come after the docstring.
"""

# Standard library imports
import datetime
import os

# Third-party imports
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy

# Local application imports
from mod1 import Foo
from mod2 import Bar

Naming guard if __name__ == "__main__" :

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")

import #module #hiding

import math, sys

pi = 32342
print(pi)
print(math.pi)

importing-that-affects-namespace #hiding

from math import sin, pi

print(sin(pi / 2))


pi = 3.14
def sin(x):
    if 2 * x == pi:
        return 0.99999999
    else:
        return None


print(sin(pi / 2))

aggressive import (everything)

from math import *

alias

import math as m

print(m.sin(m.pi/2))
from math import pi as PI, sin as sinus
print(sinus(PI/2))