python module importing

import module’s name

  1. Basic form

    1
    2
    import mymath
    print mymath.area(5)
  2. from module’s name import wanted object

    • taking the wanted object from the module
    • original object is lost if the name is using
    • it can be used without the module’s name
      1
      2
      from mymath import area, mypi
      print area(5)
  3. from module’s name import *

    • taking everything from the module without objects starting __
      1
      2
      from mymath import *
      print area(5)
  4. import module’s name as another module name

    • another name is used for calling the module
    • It is recommended when the original name is too long or already used
      1
      2
      3
      4
      import string as chstr
      print chstr
      print
      print chstr.punctuation
  5. from module’s name import original name as another name[, name2 as another name2]

    • another name is used for calling the module
      1
      2
      3
      4
      5
      6
      from string import replace as substitute[, upper as up]
      print substitute
      print substitute('ham chicken spam', 'chicke', 'egg')

      print up
      print up('abc')
  • import can be used anywhere(including in a function)

Compile and Load time

  • import mymath works like this

    1. Finding mymath.pyc
    2. If that doesn’t exist, Finding mymath.py and creating mymath.pyc
    3. Loading mymath.pyc into memory and executing
  • .pyc file

    1. Byte code file

      • Kind of Object code not depending on machines or platform(OS)
      • Python takes both executing ways of compile language and interpreter language
    2. Deciding about creating new .pycfile

      • When modificatin time of .py is more recently than modification time of .pyc
    3. Without .pyfile, import is available with .pyc
      • It can be use as the way to hide the original code

Using the same name again

  • Though the name’s target is changed, the module remains in memory, if we import the module, that takes the module existing in memory. So, we can use the thing we defined additionally in the module at the code

Executing module and test code

  • __name__

    • It is usually used for knowing if this module is used as the root module or in other module by import
    • Being used as the root module -> __main__
    • Being used in other module -> that module’s name

      1
      2
      3
      4
      print __name__ # __main__ print

      import prname
      print prname.__name__ # prname print
    • How to use

      1
      2
      3
      4
      5
      6
      7
      8
      9
      def add(a, b):
      return a + b

      def f():
      print "Python is becoming popular."

      if __name__ == "__main__":
      print add(1, 10)
      f()
      • Direct executing runs if statement
      • Being used in other module ignores if statement
Comments