# Modules can be imported anywhere in Python, there is no restriction
# but for readability they are imported at the beginning itself
# Eg. 'math' is built-in module, import it using the 'import' keyword
# the 'import' statement creates a module object in this namespace
# any module is only imported once in a program, re-importing has no effect
import math
# Accessing a function from 'math' object any functions/classes/variables
# of 'math' module now can be accessed using '.' operator
my_var = math.sqrt(8)
## Import any specifics from the module using 'from' keyword,
# here we're importing a function
from math import sqrt
# Note: Doing stared import (Eg. from math import *) is not usually recommended
# as it might add name collisions
my_var = sqrt(16)
## Make an import with different access name to avoid name collision
def math(num):
return pow(num, 2)
# Import a module with different name using 'as' followed by a new name
import math as maths
# So now accessing a function from 'math' module would be
print(maths.sqrt(4)) # 2.0
# And our 'math' function will be
print(math(2)) # 4
## Check the functions/classes/variables of a module using 'dir()'
print(dir(math))
a = 42
def my_fun():
print("This function was called")
## Check if this module is the executing module
if __name__ == "__main__":
# do something here
print("sample module was ran")
my_fun()
## Notice: Now importing 'sample' module will not call 'my_fun()'
# as it is only called if '__name__' equals '__main__',
# which is only when running from that module i.e running 'sample.py' script
import sample
print(dir(sample)) # ['__builtins__', '__name__',...]
print(sample.__name__) # sample
# access variable from 'sample' module
print(sample.a) # 42
# check '__name__' variable of current module
print(__name__) # __main__
## Now try doing otherwise, add 'import my_module' in 'sample.py' and
# check the if this print method is called, check what is printed
if __name__ == "__main__":
# add code here which you don't want to be invoked unless this script is ran
print("my_module was ran")