Python Path [Chapter 8]: Python Modules

Keywords: Python Pycharm less Programming

Reading catalogue

Modules and packages

The concept of module:

In the process of developing computer programs, as the program code is written more and more, the code in a file becomes longer and longer, and it is more and more difficult to maintain.

In order to write maintainable code, we group many functions into different files, so that each file contains relatively less code. Many programming languages use this way of organizing code. In Python, A. py file is called a module.

What are the benefits of using modules?

1. The greatest advantage is that the maintainability of the code is greatly improved.
2. Writing code does not have to start from scratch. When a module is written, it can be called elsewhere. When we write programs, we often drink other modules, including Python built-in modules and modules from third parties.

There are three modules:

1. python standard library
2. Third Party Module
3. Application custom module

Be careful:

Using modules can also avoid conflicts between function names and variable names. Functions and variables with the same name can exist in different modules, so when we write our own modules, we don't need to consider that names conflict with other modules. But be careful not to conflict with the name of the built-in function.

2. Importing Method of Module

1. import statement

import module1,[module2[,...moduleN]]

When we use the import statement, how does the Python interpreter find the corresponding file? The answer is that the interpreter has its own search path, which exists in sys.path.

import sys
print(sys.path)

//The results are as follows:
['G:\\python_s3\\day21', 'G:\\python_s3', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages', 'D:\\Program Files (x64)\\pycharm Software installation\\config\\PyCharm 2018.3\\helpers\\pycharm_matplotlib_backend']

So if a file with the same name as the module to be introduced exists in the current directory like me, the module to be introduced will not be shielded.

2. from...import... statement

from modname import name1[,name2[, ... nameN]]

This declaration does not import the entire modulename module into the current namespace, but simply refers to the global symbol table of the module that executes the declaration, independently of name1 or name2 in it.  

3. from...import * statement

from modname import *

4. Essence of operation

1,import test
2,from test import add

Whether 1 or 2, first find test.py through sys.path, and then execute the test script. The difference is that 1 loads the variable name test into the namespace, while 2 only loads the variable name add.

3. Achieving Knowledge Reserve of Decorators

Decorator = higher-order function + function nesting + closure

4. Higher Order Functions

Definition of higher-order functions:
1. The parameter received by a function is a function name.
2. The return value of a function is a function name.
3. Any of the above conditions can be called higher order functions.

 

 

5. Function nesting

def father(name):
    print('from father %s' %name)
    def son():
        print('from the son')
        def grandson():
            print('from the grandson')
        grandson()
    son()

father('Zhu Rui')

Six, closure

1, closure

def father(name):
    print('from father %s' %name)
    def son():
        print('from the son')
        def grandson():
            print('from the grandson')
        grandson()
    son()

father('Zhu Rui')

'''
//closure
'''

def father(name):
    def son():
        # name='simon1'
        print('My father is%s' %name)
        def grandson():
            print('My grandfather is%s' %name)
        grandson()
    son()
father('simon')

2. Basic Realization of Functional Closed Packaging Ornaments

import time
def timmer(func):
    def wrapper():
        # print(func)
        start_time=time.time()
        func() #It's running test()
        stop_time=time.time()
        print('The running time is%s' %(stop_time-start_time))
    return wrapper
@timmer #Grammar sugar, that's the point.

def test():
    time.sleep(3)
    print('test Function finished running')

# res=timmer(test) #Returns the address of wrapper
# res() #wrapper()

# test=timmer(test) #Returns the address of wrapper
# test() #wrapper()

test()
'''
//Grammatical sugar
'''
# @timmer #It's equivalent to test=timmer(test)

3. Function closure plus return value

#No return value added
import time
def timmer(func):
    def wrapper():
        # print(func)
        start_time=time.time()
        func() #It's running test()
        stop_time=time.time()
        print('The running time is%s' %(stop_time-start_time))
        return 123
    return wrapper
@timmer #Grammatical sugar

def test():
    time.sleep(3)
    print('test Function finished running')
    return 'This is test Return value'
res=test() #It's running wrapper.
print(res)

//The results are as follows:
C:\Python35\python3.exe G:/python_s3/day20/Add the return value.py
test Function finished running
//Running time is 3.000171661376953
123
#Add the return value
import time
def timmer(func):
    def wrapper():
        # print(func)
        start_time=time.time()
        res=func() #It's running. test()     ##Major modifications here 1
        stop_time=time.time()
        print('The running time is%s' %(stop_time-start_time))
        return res     ##Modify here 2
    return wrapper
@timmer #Grammatical sugar

def test():
    time.sleep(3)
    print('test Function finished running')
    return 'This is test Return value'
res=test() #It's running wrapper.
print(res)

//The results are as follows:
C:\Python35\python3.exe G:/python_s3/day20/Add the return value.py
test Function finished running
//Running time is 3.000171661376953
//This is the return value of test.

4. Function closures plus parameters

import time
def timmer(func):
    def wrapper(name,age):   #Add parameters, name,age
        # print(func)
        start_time=time.time()
        res=func(name,age) ##Add parameters, name,age
        stop_time=time.time()
        print('The running time is%s' %(stop_time-start_time))
        return res
    return wrapper
@timmer #Grammatical sugar

def test(name,age): #Add parameters, name,age
    time.sleep(3)
    print('test Function finished running,The name is%s],Age is.%s]' % (name,age))
    return 'This is test Return value'
res=test('simon',18) #It's running wrapper.
print(res)

Using variable length parameter code is as follows: the effect is flexible reference.

import time
def timmer(func):
    def wrapper(*args,**kwargs): #test('simon',18)  args=('simon') kwargs={'age':18}
        # print(func)
        start_time=time.time()
        res=func(*args,**kwargs) #It's running test () func (*('simon'), **{age': 18})
        stop_time=time.time()
        print('The running time is%s' %(stop_time-start_time))
        return res
    return wrapper
@timmer #Grammatical sugar

def test(name,age):
    time.sleep(3)
    print('test Function finished running,The name is%s],Age is.%s]' % (name,age))
    return 'This is test Return value'
def test1(name,age,gender):
    time.sleep(1)
    print('test Function finished running,The name is%s],Age is.%s],Gender is.%s]' % (name,age,gender))
res=test('simon',18) #It's running wrapper.
print(res)

test1('simon',18,'male')

 

5. Use of Decorators

#Non-ginseng ornaments
import time
def timmer(func):
    def wrapper(*args,**kwargs):
        start_time=time.time()
        res=func(*args,**kwargs)
        stop_time=time.time()
        print('run time is %s' %(stop_time-start_time))
        return res
    return wrapper

@timmer
def foo():
    time.sleep(3)
    print('from foo')
foo()
#Ginseng Decorator
def auth(driver='file'):
    def auth2(func):
        def wrapper(*args,**kwargs):
            name=input("user: ")
            pwd=input("pwd: ")

            if driver == 'file':
                if name == 'simon' and pwd == '123':
                    print('login successful')
                    res=func(*args,**kwargs)
                    return res
            elif driver == 'ldap':
                print('ldap')
        return wrapper
    return auth2

@auth(driver='file')
def foo(name):
    print(name)

foo('simon')

# Verification Functional Decorator

#Verification Functional Decorator
user_list=[
    {'name':'simon','passwd':'123'},
    {'name':'zhurui','passwd':'123'},
    {'name':'william','passwd':'123'},
    {'name':'zhurui1','passwd':'123'},
]
current_dic={'username':None,'login':False}


def auth_func(func):
    def wrapper(*args,**kwargs):
        if current_dic['username'] and current_dic['login']:
            res=func(*args,**kwargs)
            return res
        username=input('User name:').strip()
        passwd=input('Password:').strip()
        for user_dic in user_list:
            if username == user_dic['name'] and passwd == user_dic['passwd']:
                current_dic['username']=username
                current_dic['login']=True
                res=func(*args,**kwargs)
                return res
        else:
            print('Error in username or password')

        # if username == 'simon' and passwd == '123':
        #     user_dic['username']=username
        #     user_dic['login']=True
        #     res=func(*args,**kwargs)
        #     return res
        # else:
        #     print('user name or password error')
    return wrapper

@auth_func
def index():
    print('Welcome to the homepage of a treasure')
@auth_func
def home(name):
    print('Welcome home%s' %name)
@auth_func
def shopping_car(name):
    print('%s There are some in the shopping cart.[%s,%s,%s]' %(name,'tableware','Sofa','Electric vehicle'))

print('before----->',current_dic)
index()
print('after---->',current_dic)
home('simon')
# shopping_car('simon')

# Decorator with Parameter Verification Function

#Decorator with Parameter Verification Function
user_list=[
    {'name':'simon','passwd':'123'},
    {'name':'zhurui','passwd':'123'},
    {'name':'william','passwd':'123'},
    {'name':'zhurui1','passwd':'123'},
]
current_dic={'username':None,'login':False}

def auth(auth_type='filedb'):
    def auth_func(func):
        def wrapper(*args,**kwargs):
            print('The authentication type is',auth_type)
            if auth_type == 'filedb':
                if current_dic['username'] and current_dic['login']:
                    res = func(*args, **kwargs)
                    return res
                username=input('User name:').strip()
                passwd=input('Password:').strip()
                for user_dic in user_list:
                    if username == user_dic['name'] and passwd == user_dic['passwd']:
                        current_dic['username']=username
                        current_dic['login']=True
                        res = func(*args, **kwargs)
                        return res
                else:
                    print('Error in username or password')
            elif auth_type == 'ldap':
                print('It's not done. I don't know how to play it.')
                res = func(*args, **kwargs)
                return res
            else:
                print('The ghost knows what authentication method you use.')
                res = func(*args, **kwargs)
                return res

        return wrapper
    return auth_func

@auth(auth_type='filedb') #Auth_func = auth (auth_type='filedb') - >@auth_func adds an auth_type - - > index = auth_func (index)
def index():
    print('Welcome to the homepage of a treasure')

@auth(auth_type='ldap')
def home(name):
    print('Welcome home%s' %name)
#
@auth(auth_type='sssssss')
def shopping_car(name):
    print('%s There are some in the shopping cart.[%s,%s,%s]' %(name,'Tea with milk','Younger sister','A doll'))

# print('before-->',current_dic)
# index()
# print('after--->',current_dic)
# home('simon')
shopping_car('simon')

Posted by sciencebear on Mon, 22 Apr 2019 09:09:33 -0700