Wednesday, 13 March 2019

【toturial】import function of python

There are many ways to import modules or packages.
  1. regular imports
  2. from __ import __
  3. relative imports
  4. optional imports
  5. local imports

regular imports

import single module or package
import sys
import sys as system

import multi-modules or packages
import os, sys, time

import sub module or package
import urllib.error

from __ import __

from is used when you only want to import one part of a module and package
from functools import lru_cache
from os import path, walk, unlink
from os import uname, remove

from os import (path, walk, unlink, uname, 
                remove, rename)
from os import path, walk, unlink, uname, \
                remove, rename
from is used when you want to import all of a module and package
from os import *

relative imports

Case 1: 
Given a file structure like this
we want to import subpackage 1 and subpackage 2 in the top __init__.py
from . import subpackage1
from . import subpackage2

But it will occur a problem like 
The reason is that this subpackage is not initialized. 
The solution to this problem is to add two commands before using "from . import subpackage1"
import subpackage1
import subpackage2

from . import subpackage1
from . import subpackage2
Then in both subpackage1 and subpackage2, there generates a file directory named __pycache__ for each other. 
Once generating this file, next time you can directly use 
from . import subpackage1
from . import subpackage2

You may notice the file in the directory __pycache__ is __init__.... 
what does that mean?
let's go on and look back later
If we want to import module_x and module_y in __init__.py under subpackage1 
from . import module_x
from . import module_y
the same problem will occur
Then we use the method described above, as
import module_x
import module_y

from . import module_x
from . import module_y

Then you will find
__init__.cpython-37.pyc
module_x.cpython-37.pyc
module_y.cpython-37.pyc

So that looks like a registration, once appearing in this directory, then you can use them.

Case 2: 
If we want to use my_package as well as its packages and modules inside.
For example, we create a testpackage, test.py
So the way of import my_package is:
import sys
sys.path.append('C:/Users/acw393/Dropbox/SecondYearResearch')
import my_package

from my_package import module_a
Attention, the path should be the upper directory of  my_package

This case is very useful when you use local modules!!

Here is an example to use local modules! (attention: this case is that target module and current runfile are not in the same file directory)
the location of the target module
__init__.py is the initial function of the whole module. if you import seglearn, the __init__ will automatically run.

But I want to use this module named seglearn in a file,

What we should do is to:
1) add a sys path of current target module into system environment:
__init__.py :
import sys
sys.path.append('C:/Users/Bang/Dropbox/SecondYearResearch/Seglearn-revised')
import seglearn

2) add the same thing at any runfile where you directly use seglearn.
import sys
sys.path.append('C:/Users/Bang/Dropbox/SecondYearResearch/Seglearn-revised')
import seglearn

Here, we can know, if we create a module (which should have __init__.py to initially run all sub-modules), we only need to add following code in the  __init__.py of that module.
import sys
sys.path.append(path): path means the file directory where the defined module is. 
import name_definedmodule

then add the same code in the file you want to import.

Optional imports

It is used when you wish to use a certain module by priority or use a backup when the target module doesn't exist. 
try:
    # For Python 3
    from http.client import responses
except ImportError:  # For Python 2.5-2.7
    try:
        from httplib import responses  # NOQA
    except ImportError:  # For Python 2.4
        from BaseHTTPServer import BaseHTTPRequestHandler as _BHRH
        responses = dict([(k, v[0]) for k, v in _BHRH.responses.items()])


try:
    from urlparse import urljoin
    from urllib2 import urlopen
except ImportError:
    # Python 3
    from urllib.parse import urljoin
    from urllib.request import urlopen


Local imports

import sys  # global scope

def square_root(a):
    # This import is into the square_root functions local scope
    import math
    return math.sqrt(a)

def my_pow(base_num, power):
    return math.pow(base_num, power)

if __name__ == '__main__':
    print(square_root(49))
    print(my_pow(2, 3))


circular imports

# a.py
import b

def a_test():
    print("in a_test")
    b.b_test()

a_test()


import a

def b_test():
    print('In test_b"')
    a.a_test()

b_test()


Shadowed imports

import math

def square_root(number):
    return math.sqrt(number)

square_root(72)


Tips for establishing your own module and package
1. import all you need in __init__.py. This is a good habit for a programmer.

No comments:

Post a Comment

[Research] Recurrent Neural Network (RNN)

1. Introduction As we all know, forward neural networks (FNN) have no connection between neurons in the same layer or in cross layers. Th...