Saturday, 5 December 2015

Python: Executable statements in module

A module can contain executable statements. These statements are executed; only the first time the module name is encountered in an import statement.

arithmetic.py

print("Simple api to perform arithmetic operations")
def sum(a, b):
  return a+b

def subtract(a, b):
  return a-b
  
def mul(a,b):
  return a*b
  
def div(a, b):
  return a/b


>>> import arithmetic
Simple api to perform arithmetic operations
>>> 
>>> arithmetic.sum(10, 20)
30
>>> import arithmetic
>>> 
>>> arithmetic.div(10, 20)
0.5

Observe above snippet, print statement executed only for first import of the module, not for the second import.



Previous                                                 Next                                                 Home

No comments:

Post a Comment