Creating a Module in Python

Creating a Module in Python

  • Module have the __name__ variable  set to the module name.
  • When a python is called as a script, the __name__ is set to "__main__". This lets you create modules that can also be executed as scripts using the following:
def add(x,y):
     return x+y
if __name__ = "__main__"
     print(add(1,2))

Importing Modules

  • To make use of the functions in a module, you'll need to import the module with an import statement. 
  • An import statement is made up of the import keyword along with the name of the module
  • In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.

Various possibilties of import: 

  • import modulename 
  • import module1,module2,module3 
  • import module1 as m 
  • import module1 as m1,module2 as m2,module3 
  • from module import member 
  • from module import member1,member2,memebr3 
  • from module import memeber1 as x 
  • from module import * 




Comments