6626070
2997924

PL03, Syntax and semantics

Back to the previous pagepage managementContentsofficial python docspython tutorialsLecture
List of posts to read before reading this article


Contents


Basis of python programming, Data structure

URL

Number

Integer

int

type(10)

int

type(10 * 5)

int




floating point number

float

type(10.0)

float

type(0.1)

float

type(10.0 * 5)

float

type(10 / 5)

float

type(123e2)    # 12300.0

float

type(123e-2)   # 1.23

float

type(123.456e-3)   # 0.123456

float



floating point error

0.1

0.1

# method1
%precision 55   
0.1

0.1000000000000000055511151231257827021181583404541015625

back to origin
%precision %r
0.1

0.1



# method2
'%.55f'%0.1

0.1000000000000000055511151231257827021181583404541015625



comparsion of floating point numbers

0.1 + 0.2 == 0.3

False

CAUTION
0.1 + 0.2

0.30000000000000004

0.3

0.3



round(0.1 + 0.2, 5) == round(0.3, 5)

True




Cast

float->int

int(1.0)

1

int(3.14)

3

int(3.9)

3

int(-3.9)

-3


int->float

float(1) 

1.0




NaN and inf

float("NaN")

nan

float("Inf")

inf

float("-Inf")

-inf


String





List





Tuple





Dictionary

set

numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))

empty = dict()
print('empty =', empty)
print(type(empty))
numbers = {'y': 0, 'x': 5}
<class 'dict'>
empty = {}
<class 'dict'>




get

a = {1:'korea',2:'USA',3:'china'}

print(a.get(1), a)
print(a[1], a)
print(a.pop(1), a)
OUTPUT
korea {1: 'korea', 2: 'USA', 3: 'china'}
korea {1: 'korea', 2: 'USA', 3: 'china'}
korea {2: 'USA', 3: 'china'}

a = {1:'korea',2:'USA',3:'china'}

print(a.popitem(), a)
print(a.popitem(), a)
print(a.popitem(), a)
OUTPUT
(3, 'china') {1: 'korea', 2: 'USA'}
(2, 'USA') {1: 'korea'}
(1, 'korea') {}




change type to list

a = {1:'korea',2:'USA',3:'china'}

print(list(a))
print(list(a.keys()))
print(list(a.values()))
print(list(a.items()))
OUTPUT
[1, 2, 3]
[1, 2, 3]
['korea', 'USA', 'china']
[(1, 'korea'), (2, 'USA'), (3, 'china')]




iteration

dict = {}
dict['name'] = 'ailever'
dict['age'] = 19

for i, j in dict.items():
     print(i, j)
name ailever
age 19    





Set

s = {1, 2, 3}
s |= {4}
s

{1, 2, 3, 4}

Equivalent code
s = set([1, 2, 3])
s.add(4)
s

{1, 2, 3, 4}



s = {1, 2, 3}
s |= {4,5,6}
s

{1, 2, 3, 4, 5, 6}

Equivalent code
s = set([1, 2, 3])
s.update([4, 5, 6])
s

{1, 2, 3, 4, 5, 6}



s = {1, 2, 3}
s.remove(2)
s

{1, 3}

Equivalent code
s = set([1, 2, 3])
s.remove(2)
s

{1, 3}



s = {1,2,3}
q = {3,4,5}

print(s & q)  # {3}, s.intersection(q) 
print(s | q)  # {1,2,3,4,5}, s.union(q)
print(s - q)  # {1,2}, s.difference(q)
{3}
{1,2,3,4,5}
{1,2}





Bool





Variable





Build the structure of the program! Control statement

URL

if

is, ==

is reference
== value
a = 1

print(a is 1)
print(a == 1)
print(id(a))
print(id(1))
True
True
1531412592
1531412592
a = 257

print(a is 257)
print(a == 257)
print(id(a))
print(id(257))
False
True
2396517385200
2396517385616




comprehension

a = 10
b = {a > 0 : 1,
     a == 0 : 0}.get(True, -1)
b
a = 10

if a > 0:
    b = 1
elif a == 0:
    b = 0
else:
    b = -1
    
b
a = 10
b = 1 if a > 0 else ( 0 if a==0 else -1)
b

while





for

comprehension

for

for i in range(10) : print(i)





try/except

URL img-9-4 image

try:
    raise ZeroDivisionError()
except ZeroDivisionError:
    print('error')
error





How to do the input and output of the program

URL

Function

position arguments

def hello(a,b,c):
    print(a)
    print(b)
    print(c)

x = [1,2,3]
y = (1,2,3)
hello(*x)   # hello(*[1,2,3])
hello(*y)   # hello(*(1,2,3))
OUTPUT
1
2
3
1
2
3

def hello(*args):
    print(args)

x = [1,2,3]
y = (1,2,3)
hello(*x)   # hello(*[1,2,3])
hello(*y)   # hello(*(1,2,3))
OUTPUT
1
2
3
1
2
3




keyword arguments

def hello(name,age,address):
    print('name',name)
    print('age',age)
    print('address',address)

x = {'name':'ailever', 'age':27, 'address':312321}
hello(*x)
hello(**x)
OUTPUT
name name
age age
address address
name ailever
age 27
address 312321

def hello(**kwargs):
    print(kwargs)
    
x = {'name':'ailever', 'age':27, 'address':312321}
hello(**x)
OUTPUT
name ailever
age 27
address 312321





Input/Ouput





Read/Write





Advanced python

URL

Class(1) : basic

Declare Class

class Person:
    pass

p1 = Person()
p2 = Person()
OUTPUT
print(type(p1))
print(type(p2))
<class '__main__.Person'>
<class '__main__.Person'>




Access instance

class Person:
   def lee(self, x):
            print(x)
            
m = Person()
m.lee(10)              # instance name space = bound
Person.lee(m, 10)      # class name sapce = unbound




Class Constructor

class Person:
    def __init__(self):
        self.name = ""
        self.age = 0

p1 = Person()
p1.name = 'bob'
p1.age = 21

p2 = Person()
p2.name = 'cathy'
p2.age = 25
OUTPUT
print(p1)
print(p1.name)
print(p1.age)

print(p2)
print(p2.name)
print(p2.age)
<__main__.Person object at 0x000001C35285EDD8>
bob
21

<__main__.Person object at 0x000001C35285ED30>
cathy
25




Setter, getter method

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person('bob', 21)
p1.name
p1.age

p2 = Person('cathy', 25)
p2.name
p2.age
OUTPUT
print(p1)
print(p1.name)
print(p1.age)

print(p2)
print(p2.name)
print(p2.age)
<__main__.Person object at 0x000001C352867978>
bob
21

<__main__.Person object at 0x000001C352867358>
cathy
25




class Person:
    def __init__(self):
        self.__age = 0
 
    @property
    def age(self):           # getter
        return self.__age
 
    @age.setter
    def age(self, value):    # setter
        self.__age = value
 
james = Person()
james.age = 20      # 인스턴스.속성 형식으로 접근하여 값 저장
print(james.age)    # 인스턴스.속성 형식으로 값을 가져옴

20


hasattr(object, name)

object - object whose named attribute is to be checked
name - name of the attribute to be searched
return

True, if object has the given named attribute
False, if object has no given named attribute

class Person:
    age = 23
    name = 'Adam'

person = Person()

print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))
Person has age?: True
Person has salary?: False




static method

class CLASS:
    @staticmethod
    def func(*args, **kwargs):
        pass

CLASS.func()




magic method

corikachu URL
schoolofweb URL

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return 'x={}, y={}'.format(self.x, self.y)

    def __len__(self):
        return int(self.x**2 + self.y**2)

    def __abs__(self):
        return math.sqrt(self.x**2 + self.y**2)

    def __getitem__(self, index):
        if index == 0:
            return self.x
        elif index == 1:
            return self.y
        else:
            return -1

    def __add__(self, point):
        new_x = self.x + point.x
        new_y = self.y + point.y
        return (new_x, new_y)

    def __sub__(self, point):
        new_x = self.x - point.x
        new_y = self.y - point.y
        return (new_x, new_y)

    def __mul__(self, point):
        if type(point) == int:
            return Point(point*self.x, point*self.y)
        elif type(point) == Point:
            return self.x*point.x + self.y*point.y

    def __eq__(self, point):
        return self.x == point.x and self.y == point.y

    def __ne__(self, point):
        return not (self.x == point.x and self.y == point.y)


p1 = Point(1.1,2.2)
p2 = Point(4.4,5.5)

print('__str__ : ',p1, p2)
print('__len__ : ',len(p1),len(p2))
print('__getitem__ :', p1[0],p1[1],p1[2])
print('__add__ : ',p1 + p2)
print('__sub__ : ',p1 - p2)
print('__mul__ : ',p1 * 3)
print('__mul__ : ',p1 * p2)
print('__eq__ : ',p1 == p1, p1 == p2)
print('__ne__ : ',p1 != p1, p1 != p2)
print('__abs__: ', abs(p1))
__init__(self) : p = Point()



__str__(self) : object = CLASS()



__del__(self) : del object



__repr__(self) :



__len__(self) : len(object)



__abs__(self) : abs(object)



__add__(self) : object1 + object2



__sub__(self) : object1 - object2



__mul__(self) : object1 * object2







Class(2) : Inheritance

Class Inheritance and Inclusion

Inheritance

class Person:
    def greeting(self):
        print('hello')

class Student(Person):
    def study(self):
        print('study')

james = Student()
james.greeting()
james.study()

hello
study

class Person:
    def __init__(self):
        print('Person')
        self.hello = 'hello'
    
class Student(Person):
    def __init__(self):
        print('Student')
        super().__init__()
        self.school = 'school'
        
james = Student()
print(james.school)
print(james.hello)

Student
Person
school
hello


Error
class Person:
    def __init__(self):
        print('Person')
        self.hello = 'hello'
    
class Student(Person):
    def __init__(self):
        print('Student')
        self.school = 'school'
        
james = Student()
print(james.school)
print(james.hello)

---> 13 print(james.hello)
AttributeError: 'Student' object has no attribute 'hello'


Caution
class Person:
    def __init__(self):
        print('Person')
        self.hello = 'hello'
    
class Student(Person):
    pass        

james = Student()
print(james.hello)

Person
hello





Multiple Inheritance

class A:
    def greeting(self):
        print('hello, A')
        
class B(A):
    def greeting(self):
        print('hello, B')
        
class C(A):
    def greeting(self):
        print('hello, C')
        
class D(B,C):    # left side has a priority
    pass
        
x = D()
x.greeting()

hello, B


MRO:Method Resolution Order
D.mro()

[__main__.D, __main__.B, __main__.C, __main__.A, object]





Inclusion

class Person:
    def greeting(self):
        print('hello')

class PersonList():
    def __init__(self):
        self.person_list = []
        
    def append_person(self, person):
        self.person_list.append(person)

recode = PersonList()
james = Person()
recode.append_person(james)
recode.person_list

[<__main__.Person at 0x7f2158a17e48>]




Overiding Class

class Person:
    def greeting(self):
        print('hello, Person')

class Student(Person):
    def greeting(self):
        print('hello, Student')

james = Student()
james.greeting()

hello, Student

class Person:
    def greeting(self):
        print('hello, Person')

class Student(Person):
    def greeting(self):
        super().greeting()
        print('hello, Student')

james = Student()
james.greeting()

hello, Person
hello, Student




Abstract Class

from abc import *   # abc : abstract base class

class StudentBase(metaclass=ABCMeta):
    @abstractmethod
    def study(self):
        pass
    
    @abstractmethod
    def go_to_school(self):
        pass
    
class Student(StudentBase):
    def study(self):
        print('study')

    def go_to_school(self):
        print('go to school')
        
james = Student()
james.study()
james.go_to_school()

study
go to school


Error
from abc import *   # abc : abstract base class

class StudentBase(metaclass=ABCMeta):
    @abstractmethod
    def study(self):
        pass
    
    @abstractmethod
    def go_to_school(self):
        pass
    
class Student(StudentBase):
    def study(self):
        print('study')

james = Student()

---> 16 james = Student()
TypeError: Can't instantiate abstract class Student with abstract methods go_to_school





Meta Class

Method 1

# class = type('name_of_class', (base_class), {property:method})

Hello = type('Hello',(),{})
h = Hello()
h

<__main__.Hello at 0x7f21589b5080>

def replace(self, old, new):
    while old in self:
        self[self.index(old)] = new

AdvancedList = type('AdvancedList', (list,), {'desc':'improved list', 'replace':replace})

x = AdvancedList([1,2,3,1,2,3,1,2,3])
x.replace(1,100)
print(x)
print(x.desc)

[100, 2, 3, 100, 2, 3, 100, 2, 3]
improved list




Method 2

class MakeCalc(type):
    def __new__(metacls, name, bases, namespace):
        namespace['desc'] = 'calc class'
        namespace['add'] = lambda self, a, b : a + b
        return type.__new__(metacls, name, bases, namespace)
    
Calc = MakeCalc('Calc', (), {})
c = Calc()
print(c.desc)
print(c.add(1,2))

calc class
3

# Singleton

class Singleton(type):
    __instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls.__instances:
            cls.__instances[cls] = super().__call__(*args, **kwargs)
        return cls.__instances[cls]
    
class Hello(metaclass=Singleton):
    pass

a = Hello()
b = Hello()
print(a is b)

True





Object

attribute

class A:
    pass

a = A()

None;                     print(f'* a', vars(a))
setattr(a, 'x', 1);       print(f'* setattr : ', vars(a))
hasattr(a, 'x');          print(f'* hasattr : {hasattr(a, "x")}')
getattr(a, 'x');          print(f'* getattr : {getattr(a, "x")}')
delattr(a, 'x');          print(f'* delattr : ', vars(a))                       
* a {}
* setattr :  {'x': 1}
* hasattr : True
* getattr : 1
* delattr :  {}





Module

module import

import

parent path

import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))




if __name__ == "__main__":
    pass




help(object)





Package





Exception handling

raise

URL img-9-4

class DoorException(Exception):
    pass

class DoorOpenedException(DoorException):
    pass

class DoorClosedException(DoorException):
    pass


class Door:
    def __init__(self):
        self.is_opened = True
    
    def state(self):
        raise DoorException('being preparing')

    def open(self):
        if self.is_opened:
            raise DoorOpenedException('already opened')
        else:
            print('open')
            self.is_opened = True

    def close(self):
        if not self.is_opened:
            raise DoorClosedException('already closed')
        else:
            print('close')
            self.is_opened = False
            
door = Door()
door.close()
door.open()
door.state()
close
open
---------------------------------------------------------------------------
DoorException                             Traceback (most recent call last)
<ipython-input-797-ad6705ac378e> in <module>
     33 door.close()
     34 door.open()
---> 35 door.state()

<ipython-input-797-ad6705ac378e> in state(self)
     14 
     15     def state(self):
---> 16         raise DoorException('being preparing')
     17 
     18     def open(self):

DoorException: being preparing

try/except/else/finally

try:
    x = int(input('enter number : '))
    y = 10 / x 
except ZeroDivisionError:    # if exception is occured
    print('cannot divide')
else:                        # if exception is not occured
    print(y)
finally:                     # always
    print('end')

enter number : 2
5.0
end




Python error hierarchy

URL image





Built-in function

abs

abs(3)
3


abs(-3)
3


abs(-1.2)
1.2


all

all([1, 2, 3])
True


all([1, 2, 3, 0])
False


any

any([1, 2, 3, 0])
True


any([0, ""])
False


chr

chr(97)
'a'
chr(48)
'0'


dir

dir([1, 2, 3])
['append', 'count', 'extend', 'index', 'insert', 'pop',...]


dir({'1':'a'})
['clear', 'copy', 'get', 'has_key', 'items', 'keys',...]


divmod

divmod(7, 3)
(2, 1)


7 // 3, 7 % 3
(2, 1)


enumerate

for i, name in enumerate(['body', 'foo', 'bar']):
    print(i, name)
0 body
1 foo
2 bar


eval

eval('1+2')
3


eval("'hi' + 'a'")
'hia'


eval('divmod(4, 3)')
(1, 1)


filter




hex

hex(234)
'0xea'


hex(3)
'0x3'


id

>>> a = 3
>>> id(3)
135072304


id(a)
135072304


b = a
id(b)
135072304


input

>>> a = input()
hi
>>> a
'hi'

>>> b = input("Enter: ")
Enter: hi
>>> b
'hi'


int

int('3')
3


int(3.4)
3


isinstance

class Person: pass

a = Person()
isinstance(a, Person)
True


b = 3
isinstance(b, Person)
False


len

len("python")
6


len([1,2,3])
3


len((1, 'a'))
2


list

list("python")
['p', 'y', 't', 'h', 'o', 'n']


list((1,2,3))
[1, 2, 3]


map

# two_times.py
def two_times(numberList):
    result = [ ]
    for number in numberList:
        result.append(number*2)
    return result

result = two_times([1, 2, 3, 4])
print(result)
[2, 4, 6, 8]


def two_times(x): 
    return x*2

list(map(two_times, [1, 2, 3, 4]))
[2, 4, 6, 8]

max

max([1, 2, 3])
3


max("python")
'y'


min

min([1, 2, 3])
1


min("python")
'h'


oct

oct(34)
'0o42'


oct(12345)
'0o30071'


open
r, b, a, +

mode description method
w write  
r read seek,read,readline,readlines
a append  
b binary  
+ overwrite a part of doc  
f = open("binary_file", "rb")
f.close()

with open("binary_file","rb") as f:
    pass
fread = open("read_mode.txt", 'r')
fread2 = open("read_mode.txt")
fappend = open("append_mode.txt", 'a')


ord

ord('a')
97


ord('0')
48


pow

pow(2, 4)
16


pow(3, 3)
27


range

list(range(5))
[0, 1, 2, 3, 4]


list(range(5, 10))
[5, 6, 7, 8, 9]


list(range(1, 10, 2))
[1, 3, 5, 7, 9]


list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]


round

round(4.6)
5


round(4.2)
4


round(5.678, 2)
5.68


sorted

sorted([3, 1, 2])
[1, 2, 3]


sorted(['a', 'c', 'b'])
['a', 'b', 'c']


sorted("zero")
['e', 'o', 'r', 'z']


sorted((3, 2, 1))
[1, 2, 3]


str

str(3)
'3'


str('hi')
'hi'


str('hi'.upper())
'HI'


sum

sum([1,2,3])
6


sum((4,5,6))
15


tuple

tuple("abc")
('a', 'b', 'c')


tuple([1, 2, 3])
(1, 2, 3)


tuple((1, 2, 3))
(1, 2, 3)


type

type("abc")
<class 'str'>


type([ ])
<class 'list'>


type(open("test", 'w'))
<class '_io.TextIOWrapper'>


zip

list(zip([1, 2, 3], [4, 5, 6]))
[(1, 4), (2, 5), (3, 6)]


list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]


list(zip("abc", "def"))
[('a', 'd'), ('b', 'e'), ('c', 'f')]





External function

sys

import sys
print(sys.argv)
C:/doit/Mymod>python argv_test.py you need python
['argv_test.py', 'you', 'need', 'python']


import sys

print('hello1')
sys.exit()
print('hello2')
C:/doit/Mymod>python argv_test.py you need python
hello1
['argv_test.py', 'you', 'need', 'python']


import sys

print(sys.path)
['', 'C:\\Windows\\SYSTEM32\\python37.zip', 'c:\\Python37\\DLLs', 
'c:\\Python37\\lib', 'c:\\Python37', 'c:\\Python37\\lib\\site-packages']


import sys

sys.path.append('C:/doit/mymod')
print(sys.path)
['', 'C:\\Windows\\SYSTEM32\\python37.zip', 'c:\\Python37\\DLLs', 
'c:\\Python37\\lib', 'c:\\Python37', 'c:\\Python37\\lib\\site-packages', 'C:/doit/mymod']


argparse

URL

import argparse

parser = argparse.ArgumentParser(description="set your environment")
parser.add_argument('--env1', required=False, help="env 1")
parser.add_argument('--env2', required=False, help="env 2")
args = parser.parse_args()

print(args.env1)
print(args.env2)
import argparse

def option():
    parser = argparse.ArgumentParser(description="set your environment")   
    parser.add_argument('--env1', type=str, required=False, help="env 1")
    parser.add_argument('--env2', type=str, required=False, help="env 2")
    args = parser.parse_args()
    return args

def main(opt):
    print(opt.env1)
    print(opt.env2)

if __name__ == "__main__":
    opt = option()
    main(opt)


pickle

Save

import pickle

f = open("test.txt", 'wb')
data = {1: 'python', 2: 'you need'}
pickle.dump(data, f)
f.close()


Load

import pickle

f = open("test.txt", 'rb')
data = pickle.load(f)
print(data)
{2:'you need', 1:'python'}


os

method description
os.chdir(‘path’) change directory
os.getcwd()
os.path.dirname(__file__)
get current working directory
os.listdir(‘path’) list of files on directory
import os

os.environ
environ({'PROGRAMFILES': 'C:\\Program Files', 'APPDATA': … 생략 …})


import os

os.chdir("C:\WINDOWS")


import os

os.getcwd()
'C:\WINDOWS'
another way
import os

current_path = os.path.abspath(os.path.dirname(__file__))
print(__file__)
print(current_path)
1341.py
s:\workspace\2020-02-04


shutil


glob


tempfile


time


ctypes

import ctypes

ctypes.windll.user32.MessageBoxW(0, "It's done!", "Title", 1)


calendar


random


webbrowser





Object copy

immutable

  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin 1 1 1 1
simple(b=100) 1 100 1 1
shallow(c=100) 1 1 100 1
deep(d=100) 1 1 1 100
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d))
    print()    

a = 1
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)
a value: 1 : original(a) ,
 a id: 10914496
b value: 1 : simple(b = a) ,
 b id: 10914496
c value: 1 : shallow(c = copy.copy(a))  ,
 c id: 10914496
d value: 1 : deep(d = copy.deepcopy(d)) ,
 d id: 10914496
simple
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d))
    print()    

a = 1
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

b = 100
description(a,b,c,d)
a value: 1 : original(a) ,
 a id: 10914496
b value: 1 : simple(b = a) ,
 b id: 10914496
c value: 1 : shallow(c = copy.copy(a))  ,
 c id: 10914496
d value: 1 : deep(d = copy.deepcopy(d)) ,
 d id: 10914496

a value: 1 : original(a) ,
 a id: 10914496
b value: 100 : simple(b = a) ,
 b id: 10917664
c value: 1 : shallow(c = copy.copy(a))  ,
 c id: 10914496
d value: 1 : deep(d = copy.deepcopy(d)) ,
 d id: 10914496

shallow
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d))
    print()    

a = 1
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

c = 100
description(a,b,c,d)
a value: 1 : original(a) ,
 a id: 10914496
b value: 1 : simple(b = a) ,
 b id: 10914496
c value: 1 : shallow(c = copy.copy(a))  ,
 c id: 10914496
d value: 1 : deep(d = copy.deepcopy(d)) ,
 d id: 10914496

a value: 1 : original(a) ,
 a id: 10914496
b value: 1 : simple(b = a) ,
 b id: 10914496
c value: 100 : shallow(c = copy.copy(a))  ,
 c id: 10917664
d value: 1 : deep(d = copy.deepcopy(d)) ,
 d id: 10914496

deep
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d))
    print()    

a = 1
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

d = 100
description(a,b,c,d)
a value: 1 : original(a) ,
 a id: 10914496
b value: 1 : simple(b = a) ,
 b id: 10914496
c value: 1 : shallow(c = copy.copy(a))  ,
 c id: 10914496
d value: 1 : deep(d = copy.deepcopy(d)) ,
 d id: 10914496

a value: 1 : original(a) ,
 a id: 10914496
b value: 1 : simple(b = a) ,
 b id: 10914496
c value: 1 : shallow(c = copy.copy(a))  ,
 c id: 10914496
d value: 100 : deep(d = copy.deepcopy(d)) ,
 d id: 10917664


mutable

  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1] [1] [1] [1]
simple(b[0]=100) [100] [100] [1] [1]
simple(b=[100]) [1] [100] [1] [1]
shallow(c[0]=100) [1] [1] [100] [1]
shallow(c=[100]) [1] [1] [100] [1]
deep(d[0]=100) [1] [1] [1] [100]
deep(d=[100]) [1] [1] [1] [100]
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]))
    print()
    
a = [1]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)
a value: [1] : original(a) ,
 a id: 140282058829128 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282058829128 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282056137608 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055629320 , d[0] id: 10914496
simple
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]))
    print()
    
a = [1]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

b[0] = 100
description(a,b,c,d)
a value: [1] : original(a) ,
 a id: 140282055757896 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282055757896 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282055759112 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055758152 , d[0] id: 10914496

a value: [100] : original(a) ,
 a id: 140282055757896 , a[0] id: 10917664
b value: [100] : simple(b = a) ,
 b id: 140282055757896 , b[0] id: 10917664
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282055759112 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055758152 , d[0] id: 10914496




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]))
    print()
    
a = [1]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

b = [100]
description(a,b,c,d)
a value: [1] : original(a) ,
 a id: 140282054944712 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282054944712 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282055640840 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055757896 , d[0] id: 10914496

a value: [1] : original(a) ,
 a id: 140282054944712 , a[0] id: 10914496
b value: [100] : simple(b = a) ,
 b id: 140282055758152 , b[0] id: 10917664
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282055640840 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055757896 , d[0] id: 10914496

shallow
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]))
    print()
    
a = [1]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

c[0] = 100
description(a,b,c,d)
a value: [1] : original(a) ,
 a id: 140282057630472 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282057630472 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282054944712 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055758152 , d[0] id: 10914496

a value: [1] : original(a) ,
 a id: 140282057630472 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282057630472 , b[0] id: 10914496
c value: [100] : shallow(c = copy.copy(a))  ,
 c id: 140282054944712 , c[0] id: 10917664
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055758152 , d[0] id: 10914496




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]))
    print()
    
a = [1]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

c = [100]
description(a,b,c,d)
a value: [1] : original(a) ,
 a id: 140282054999432 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282054999432 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282057631304 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057630472 , d[0] id: 10914496

a value: [1] : original(a) ,
 a id: 140282054999432 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282054999432 , b[0] id: 10914496
c value: [100] : shallow(c = copy.copy(a))  ,
 c id: 140282055758152 , c[0] id: 10917664
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057630472 , d[0] id: 10914496

deep
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]))
    print()
    
a = [1]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

d[0] = 100
description(a,b,c,d)
a value: [1] : original(a) ,
 a id: 140282055758152 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282055758152 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282054946120 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057631304 , d[0] id: 10914496

a value: [1] : original(a) ,
 a id: 140282055758152 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282055758152 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282054946120 , c[0] id: 10914496
d value: [100] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057631304 , d[0] id: 10917664




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]))
    print()
    
a = [1]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

d = [100]
description(a,b,c,d)
a value: [1] : original(a) ,
 a id: 140282055726216 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282055726216 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282055640840 , c[0] id: 10914496
d value: [1] : deep(d = copy.deepcopy(d)) ,
 d id: 140282055758152 , d[0] id: 10914496

a value: [1] : original(a) ,
 a id: 140282055726216 , a[0] id: 10914496
b value: [1] : simple(b = a) ,
 b id: 140282055726216 , b[0] id: 10914496
c value: [1] : shallow(c = copy.copy(a))  ,
 c id: 140282055640840 , c[0] id: 10914496
d value: [100] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057631304 , d[0] id: 10917664




simple copy

  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1,[2]] [1,[2]] [1,[2]] [1,[2]]
simple(b[0]=2) [2,[2]] [2,[2]] [1,[2]] [1,[2]]
simple(b[1]=[3]) [1,[3]] [1,[3]] [1,[2]] [1,[2]]
simple(b[1][0]=3) [1,[3]] [1,[3]] [1,[3]] [1,[2]]
simple(b[1].append(4)) [1,[2,4]] [1,[2,4]] [1,[2,4]] [1,[2]]
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()
    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

b[0] = 2
description(a,b,c,d)

b[1] = [3]
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282049351496 , a[0] id: 10914496 , a[1] id: 140282049578824
b value: [1, [2]] : simple(b = a) ,
 b id: 140282049351496 , b[0] id: 10914496 , b[1] id: 140282049578824
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282049351560 , c[0] id: 10914496 , c[1] id: 140282049578824
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057881608 , d[0] id: 10914496 , d[1] id: 140282049410312

a value: [2, [2]] : original(a) ,
 a id: 140282049351496 , a[0] id: 10914528 , a[1] id: 140282049578824
b value: [2, [2]] : simple(b = a) ,
 b id: 140282049351496 , b[0] id: 10914528 , b[1] id: 140282049578824
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282049351560 , c[0] id: 10914496 , c[1] id: 140282049578824
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057881608 , d[0] id: 10914496 , d[1] id: 140282049410312

a value: [2, [3]] : original(a) ,
 a id: 140282049351496 , a[0] id: 10914528 , a[1] id: 140282060263624
b value: [2, [3]] : simple(b = a) ,
 b id: 140282049351496 , b[0] id: 10914528 , b[1] id: 140282060263624
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282049351560 , c[0] id: 10914496 , c[1] id: 140282049578824
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057881608 , d[0] id: 10914496 , d[1] id: 140282049410312




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    

    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

b[0] = 2
description(a,b,c,d)

b[1][0] = 3
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282054943752 , a[0] id: 10914496 , a[1] id: 140282054945928
b value: [1, [2]] : simple(b = a) ,
 b id: 140282054943752 , b[0] id: 10914496 , b[1] id: 140282054945928
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282054944328 , c[0] id: 10914496 , c[1] id: 140282054945928
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054944072 , d[0] id: 10914496 , d[1] id: 140282054943048

a value: [2, [2]] : original(a) ,
 a id: 140282054943752 , a[0] id: 10914528 , a[1] id: 140282054945928
b value: [2, [2]] : simple(b = a) ,
 b id: 140282054943752 , b[0] id: 10914528 , b[1] id: 140282054945928
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282054944328 , c[0] id: 10914496 , c[1] id: 140282054945928
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054944072 , d[0] id: 10914496 , d[1] id: 140282054943048

a value: [2, [3]] : original(a) ,
 a id: 140282054943752 , a[0] id: 10914528 , a[1] id: 140282054945928
b value: [2, [3]] : simple(b = a) ,
 b id: 140282054943752 , b[0] id: 10914528 , b[1] id: 140282054945928
c value: [1, [3]] : shallow(c = copy.copy(a))  ,
 c id: 140282054944328 , c[0] id: 10914496 , c[1] id: 140282054945928
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054944072 , d[0] id: 10914496 , d[1] id: 140282054943048




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    

    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

b[0] = 2
description(a,b,c,d)

b[1].append(4)
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282049958344 , a[0] id: 10914496 , a[1] id: 140282055016520
b value: [1, [2]] : simple(b = a) ,
 b id: 140282049958344 , b[0] id: 10914496 , b[1] id: 140282055016520
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282049923464 , c[0] id: 10914496 , c[1] id: 140282055016520
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282049958024 , d[0] id: 10914496 , d[1] id: 140282049959432

a value: [2, [2]] : original(a) ,
 a id: 140282049958344 , a[0] id: 10914528 , a[1] id: 140282055016520
b value: [2, [2]] : simple(b = a) ,
 b id: 140282049958344 , b[0] id: 10914528 , b[1] id: 140282055016520
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282049923464 , c[0] id: 10914496 , c[1] id: 140282055016520
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282049958024 , d[0] id: 10914496 , d[1] id: 140282049959432

a value: [2, [2, 4]] : original(a) ,
 a id: 140282049958344 , a[0] id: 10914528 , a[1] id: 140282055016520
b value: [2, [2, 4]] : simple(b = a) ,
 b id: 140282049958344 , b[0] id: 10914528 , b[1] id: 140282055016520
c value: [1, [2, 4]] : shallow(c = copy.copy(a))  ,
 c id: 140282049923464 , c[0] id: 10914496 , c[1] id: 140282055016520
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282049958024 , d[0] id: 10914496 , d[1] id: 140282049959432




Sallow copy

  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1,[2]] [1,[2]] [1,[2]] [1,[2]]
shallow(c[0]=2) [1,[2]] [1,[2]] [2,[2]] [1,[2]]
shallow(c[1]=[3]) [1,[2]] [1,[2]] [1,[3]] [1,[2]]
shallow(c[1][0]=3) [1,[3]] [1,[3]] [1,[3]] [1,[2]]
shallow(c[1].append(4)) [1,[2,4]] [1,[2,4]] [1,[2,4]] [1,[2]]
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    
    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

c[0] = 2
description(a,b,c,d)

c[1] = [3]
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282054999560 , a[0] id: 10914496 , a[1] id: 140282054999752
b value: [1, [2]] : simple(b = a) ,
 b id: 140282054999560 , b[0] id: 10914496 , b[1] id: 140282054999752
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282054848712 , c[0] id: 10914496 , c[1] id: 140282054999752
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054999688 , d[0] id: 10914496 , d[1] id: 140282054848776

a value: [1, [2]] : original(a) ,
 a id: 140282054999560 , a[0] id: 10914496 , a[1] id: 140282054999752
b value: [1, [2]] : simple(b = a) ,
 b id: 140282054999560 , b[0] id: 10914496 , b[1] id: 140282054999752
c value: [2, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282054848712 , c[0] id: 10914528 , c[1] id: 140282054999752
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054999688 , d[0] id: 10914496 , d[1] id: 140282054848776

a value: [1, [2]] : original(a) ,
 a id: 140282054999560 , a[0] id: 10914496 , a[1] id: 140282054999752
b value: [1, [2]] : simple(b = a) ,
 b id: 140282054999560 , b[0] id: 10914496 , b[1] id: 140282054999752
c value: [2, [3]] : shallow(c = copy.copy(a))  ,
 c id: 140282054848712 , c[0] id: 10914528 , c[1] id: 140282054848648
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054999688 , d[0] id: 10914496 , d[1] id: 140282054848776




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    

    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

c[0] = 2
description(a,b,c,d)

c[1][0] = 3
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282054945672 , a[0] id: 10914496 , a[1] id: 140282054944136
b value: [1, [2]] : simple(b = a) ,
 b id: 140282054945672 , b[0] id: 10914496 , b[1] id: 140282054944136
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282054944904 , c[0] id: 10914496 , c[1] id: 140282054944136
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054943752 , d[0] id: 10914496 , d[1] id: 140282054945928

a value: [1, [2]] : original(a) ,
 a id: 140282054945672 , a[0] id: 10914496 , a[1] id: 140282054944136
b value: [1, [2]] : simple(b = a) ,
 b id: 140282054945672 , b[0] id: 10914496 , b[1] id: 140282054944136
c value: [2, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282054944904 , c[0] id: 10914528 , c[1] id: 140282054944136
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054943752 , d[0] id: 10914496 , d[1] id: 140282054945928

a value: [1, [3]] : original(a) ,
 a id: 140282054945672 , a[0] id: 10914496 , a[1] id: 140282054944136
b value: [1, [3]] : simple(b = a) ,
 b id: 140282054945672 , b[0] id: 10914496 , b[1] id: 140282054944136
c value: [2, [3]] : shallow(c = copy.copy(a))  ,
 c id: 140282054944904 , c[0] id: 10914528 , c[1] id: 140282054944136
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054943752 , d[0] id: 10914496 , d[1] id: 140282054945928




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    

    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

c[0] = 2
description(a,b,c,d)

c[1].append(4)
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282055726856 , a[0] id: 10914496 , a[1] id: 140282054999048
b value: [1, [2]] : simple(b = a) ,
 b id: 140282055726856 , b[0] id: 10914496 , b[1] id: 140282054999048
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282055728712 , c[0] id: 10914496 , c[1] id: 140282054999048
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054991560 , d[0] id: 10914496 , d[1] id: 140282050117832

a value: [1, [2, 4]] : original(a) ,
 a id: 140282055726856 , a[0] id: 10914496 , a[1] id: 140282054999048
b value: [1, [2, 4]] : simple(b = a) ,
 b id: 140282055726856 , b[0] id: 10914496 , b[1] id: 140282054999048
c value: [1, [2, 4]] : shallow(c = copy.copy(a))  ,
 c id: 140282055728712 , c[0] id: 10914496 , c[1] id: 140282054999048
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054991560 , d[0] id: 10914496 , d[1] id: 140282050117832




deep copy

  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1,[2]] [1,[2]] [1,[2]] [1,[2]]
deep(d[0]=2) [1,[2]] [1,[2]] [1,[2]] [2,[2]]
deep(d[1]=[3]) [1,[2]] [1,[2]] [1,[2]] [1,[3]]
deep(d[1][0]=3) [1,[2]] [1,[2]] [1,[2]] [1,[3]]
deep(d[1].append(4)) [1,[2]] [1,[2]] [1,[2]] [1,[2,4]]
import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    
    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

d[0] = 2
description(a,b,c,d)

d[1] = [3]
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282055725768 , a[0] id: 10914496 , a[1] id: 140282055726920
b value: [1, [2]] : simple(b = a) ,
 b id: 140282055725768 , b[0] id: 10914496 , b[1] id: 140282055726920
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282055725640 , c[0] id: 10914496 , c[1] id: 140282055726920
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054999560 , d[0] id: 10914496 , d[1] id: 140282054848648

a value: [1, [2]] : original(a) ,
 a id: 140282055725768 , a[0] id: 10914496 , a[1] id: 140282055726920
b value: [1, [2]] : simple(b = a) ,
 b id: 140282055725768 , b[0] id: 10914496 , b[1] id: 140282055726920
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282055725640 , c[0] id: 10914496 , c[1] id: 140282055726920
d value: [2, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054999560 , d[0] id: 10914528 , d[1] id: 140282054848648

a value: [1, [2]] : original(a) ,
 a id: 140282055725768 , a[0] id: 10914496 , a[1] id: 140282055726920
b value: [1, [2]] : simple(b = a) ,
 b id: 140282055725768 , b[0] id: 10914496 , b[1] id: 140282055726920
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282055725640 , c[0] id: 10914496 , c[1] id: 140282055726920
d value: [2, [3]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054999560 , d[0] id: 10914528 , d[1] id: 140282054999688




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    

    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

d[0] = 2
description(a,b,c,d)

d[1][0] = 3
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282057630280 , a[0] id: 10914496 , a[1] id: 140282054944712
b value: [1, [2]] : simple(b = a) ,
 b id: 140282057630280 , b[0] id: 10914496 , b[1] id: 140282054944712
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282057630856 , c[0] id: 10914496 , c[1] id: 140282054944712
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057630728 , d[0] id: 10914496 , d[1] id: 140282057630472

a value: [1, [2]] : original(a) ,
 a id: 140282057630280 , a[0] id: 10914496 , a[1] id: 140282054944712
b value: [1, [2]] : simple(b = a) ,
 b id: 140282057630280 , b[0] id: 10914496 , b[1] id: 140282054944712
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282057630856 , c[0] id: 10914496 , c[1] id: 140282054944712
d value: [2, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057630728 , d[0] id: 10914528 , d[1] id: 140282057630472

a value: [1, [2]] : original(a) ,
 a id: 140282057630280 , a[0] id: 10914496 , a[1] id: 140282054944712
b value: [1, [2]] : simple(b = a) ,
 b id: 140282057630280 , b[0] id: 10914496 , b[1] id: 140282054944712
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282057630856 , c[0] id: 10914496 , c[1] id: 140282054944712
d value: [2, [3]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282057630728 , d[0] id: 10914528 , d[1] id: 140282057630472




import copy

def description(a,b,c,d):
    print('a value:',a,': original(a)',
          ',\n a id:',id(a),', a[0] id:',id(a[0]),', a[1] id:',id(a[1]))
    print('b value:',b,': simple(b = a)',
          ',\n b id:',id(b),', b[0] id:',id(b[0]),', b[1] id:',id(b[1]))
    print('c value:',c,': shallow(c = copy.copy(a)) ',
          ',\n c id:',id(c),', c[0] id:',id(c[0]),', c[1] id:',id(c[1]))
    print('d value:',d,': deep(d = copy.deepcopy(d))',
          ',\n d id:',id(d),', d[0] id:',id(d[0]),', d[1] id:',id(d[1]))
    print()    

    
a = [1, [2]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
description(a,b,c,d)

d[0] = 2
description(a,b,c,d)

d[1].append(4)
description(a,b,c,d)
a value: [1, [2]] : original(a) ,
 a id: 140282057630728 , a[0] id: 10914496 , a[1] id: 140282057630472
b value: [1, [2]] : simple(b = a) ,
 b id: 140282057630728 , b[0] id: 10914496 , b[1] id: 140282057630472
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282057631304 , c[0] id: 10914496 , c[1] id: 140282057630472
d value: [1, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054944840 , d[0] id: 10914496 , d[1] id: 140282055630280

a value: [1, [2]] : original(a) ,
 a id: 140282057630728 , a[0] id: 10914496 , a[1] id: 140282057630472
b value: [1, [2]] : simple(b = a) ,
 b id: 140282057630728 , b[0] id: 10914496 , b[1] id: 140282057630472
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282057631304 , c[0] id: 10914496 , c[1] id: 140282057630472
d value: [2, [2]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054944840 , d[0] id: 10914528 , d[1] id: 140282055630280

a value: [1, [2]] : original(a) ,
 a id: 140282057630728 , a[0] id: 10914496 , a[1] id: 140282057630472
b value: [1, [2]] : simple(b = a) ,
 b id: 140282057630728 , b[0] id: 10914496 , b[1] id: 140282057630472
c value: [1, [2]] : shallow(c = copy.copy(a))  ,
 c id: 140282057631304 , c[0] id: 10914496 , c[1] id: 140282057630472
d value: [2, [2, 4]] : deep(d = copy.deepcopy(d)) ,
 d id: 140282054944840 , d[0] id: 10914528 , d[1] id: 140282055630280




summary

  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin 1 1 1 1
b=100 1 100 1 1
c=100 1 1 100 1
d=100 1 1 1 100
  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1] [1] [1] [1]
b[0]=100 [100] [100] [1] [1]
b=[100] [1] [100] [1] [1]
c[0]=100 [1] [1] [100] [1]
c=[100] [1] [1] [100] [1]
d[0]=100 [1] [1] [1] [100]
d=[100] [1] [1] [1] [100]
  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1,[2]] [1,[2]] [1,[2]] [1,[2]]
b[0]=2 [2,[2]] [2,[2]] [1,[2]] [1,[2]]
b[1]=[3] [1,[3]] [1,[3]] [1,[2]] [1,[2]]
b[1][0]=3 [1,[3]] [1,[3]] [1,[3]] [1,[2]]
b[1].append(4) [1,[2,4]] [1,[2,4]] [1,[2,4]] [1,[2]]
  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1,[2]] [1,[2]] [1,[2]] [1,[2]]
c[0]=2 [1,[2]] [1,[2]] [2,[2]] [1,[2]]
c[1]=[3] [1,[2]] [1,[2]] [1,[3]] [1,[2]]
c[1][0]=3 [1,[3]] [1,[3]] [1,[3]] [1,[2]]
c[1].append(4) [1,[2,4]] [1,[2,4]] [1,[2,4]] [1,[2]]
  a b=a c=copy.copy(a) d=copy.deepcopy(a)
origin [1,[2]] [1,[2]] [1,[2]] [1,[2]]
d[0]=2 [1,[2]] [1,[2]] [1,[2]] [2,[2]]
d[1]=[3] [1,[2]] [1,[2]] [1,[2]] [1,[3]]
d[1][0]=3 [1,[2]] [1,[2]] [1,[2]] [1,[3]]
d[1].append(4) [1,[2]] [1,[2]] [1,[2]] [1,[2,4]]





Closure : func of func

global vs nonlocal

a = 3
def calc():
    a = 1
    b = 5
    total = 0
    def mul_add(x):
        global a
        nonlocal total
        total = total + a*x + b
        print(total)
    return mul_add

c = calc()
print(c(1))
8




lambda closure

def calc():
    a = 3
    b = 5
    return lambda x : a*x + b

c = calc()
print(c(1))
8




decorator

function decorator

def trace(func):
    def wrapper():
        return func()
    return wrapper

@trace
def function():
    pass

function()
def trace(func):
    def wrapper(*agrs,**kwagrs):
        return func(*agrs,**kwagrs)
    return wrapper

@trace
def function(*args, **kwargs):
    pass

function()
def trace(x):
    def decorator(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    return decorator

@trace(x=3)
def function(*args, **kwargs):
    pass

print(function())




class decorator

class trace:
    def __init__(self, func):
        self.func = func

    def __call__(self):
        return self.func()

@trace
def function():
    pass

function()
class trace:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

@trace
def function(*args, **kwargs):
    pass

function()





Decorator

Function Decorator

def hello():
    print('hello start')
    print('hello')
    print('hello end')

def world():
    print('world start')
    print('world')
    print('world end')
    
hello()
world()

hello start
hello
hello end
world start
world
world end




def trace(func):
    def wrapper():
        print(func.__name__, 'start')
        func()
        print(func.__name__, 'end')
    return wrapper

def hello():
    print('hello')

def world():
    print('world')

trace_hello = trace(hello)
trace_hello()
trace_world = trace(world)
trace_world()

hello start
hello
hello end
world start
world
world end




def trace(func):
    def wrapper():
        print(func.__name__, 'start')
        func()
        print(func.__name__, 'end')
    return wrapper

@trace
def hello():
    print('hello')

@trace
def world():
    print('world')

hello()
world()

hello start
hello
hello end
world start
world
world end




Decorator with arguments

def trace(func):
    def wrapper(*args, **kwargs):
        r = func(*args, **kwargs)
        print('{0}(args={1}, kwargs={2}) -> {3}'.format(func.__name__, args, kwargs, r))
        return r
    return wrapper

@trace
def get_max(*args):
    return max(args)

@trace
def get_min(**kwargs):
    return min(kwargs.values())

print(get_max(10,20))
print(get_min(x=10, y=20, z=30))

get_max(args=(10, 20), kwargs={}) -> 20
20
get_min(args=(), kwargs={'x': 10, 'y': 20, 'z': 30}) -> 10
10

Example
def trace(x):
    def decorator(func):
        def wrapper(a,b):
            r = func(a,b)
            if r % x == 0:
                print('returned value of {0} is multiple of {1}'.format(func.__name__, x))
            else:
                print('returned value of {0} is not multiple of {1}'.format(func.__name__, x))
            return r
        return wrapper
    return decorator

@trace(3)
def add(a,b):
    return a + b

print(add(10,20))
print(add(2,5))

returned value of add is multiple of 3
30
returned value of add is not multiple of 3
7





Class Decorator

class trace:
    def __init__(self, func):
        self.func = func
    
    def __call__(self):
        print(self.func.__name__, 'start')
        self.func()
        print(self.func.__name__, 'end')

def hello():
    print('hello')

@trace
def world():
    print('world')

trace_hello = trace(hello)
trace_hello()
world()

hello start
hello
hello end
world start
world
world end




Decorator with arguments

class trace:
    def __init__(self, func):
        self.func = func
    
    def __call__(self, *args, **kwargs):
        r = self.func(*args, **kwargs)
        print('{0}(args={1}, kwargs={2}) -> {3}'.format(self.func.__name__, args, kwargs, r))
        return r
        
@trace
def add(a, b):
    return a + b

print(add(10,20))
print(add(a=10, b=20))

add(args=(10, 20), kwargs={}) -> 30
30
add(args=(), kwargs={'a': 10, 'b': 20}) -> 30
30

Example
class trace:
    def __init__(self, x):
        self.x = x
    
    def __call__(self, func):
        def wrapper(a,b):
            r = func(a,b)
            if r % self.x == 0:
                print('returned value of {0} is mutiple of {1}'.format(func.__name__, self.x))
            else:
                print('returned value of {0} is not mutiple of {1}'.format(func.__name__, self.x))
            return r
        return wrapper
    
@trace(3)
def add(a, b):
    return a + b

print(add(10,20))
print(add(2, 5))

returned value of add is mutiple of 3
30
returned value of add is not mutiple of 3
7






Iterator : next!

image

class Counter:
    def __init__(self, stop):
        self.current = 0
        self.stop = stop
        
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current < self.stop:
            r = self.current
            self.current += 1
            return r
        else:
            raise StopIteration

for i in Counter(3): print(i)
0
1
2




class Counter:
    def __init__(self, stop):
        self.stop = stop
    
    def __getitem__(self, index):
        if index < self.stop :
            return index
        else:
            raise IndexError
    
#print(Counter(3)[0],Counter(3)[1],Counter(3)[2])

for i in Counter(3): print(i)
0
1
2




iter(iterable_object)

a = iter(range(3))
next(a)
next(a)
next(a)
2




iter(callable_object, sentinel)

import random

for i in iter(lambda : random.randint(0,5), 2):
    print(i)
3
1
4
4
3
5
3
3
1
5
4




next(iterable_object, default_value)

a = iter(range(3))
next(a,10)
next(a,10)
next(a,10)
next(a,10)
10





Generator : yield!

Yield

# 'yield(co)' is different 'return(sub)'
def number_generator():
    yield 0
    yield 1
    yield 2
    
for i in number_generator():
    print(i)

0
1
2

g = number_generator()
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())

0
1
2
3 print(g.__next__())
4 print(g.__next__())
----> 5 print(g.__next__())

StopIteration:




def number_generator(stop):
    n = 0
    while n < stop :
        yield n
        n += 1
        
for i in number_generator(3):
    print(i)

for i in range(3):
    print(i)

0
1
2
0
1
2

g = number_generator(3)
print(next(g))
print(next(g))
print(next(g))

0
1
2




def upper_generator(x):
    for i in x:
        yield i.upper()

fruits = ['apple', 'pear', 'grape']

for i in upper_generator(fruits):
    print(i)
    
    
for i in fruits:
    print(i.upper())

0
1
2




Yield from

def number_generator1():
    x = [1,2,3]
    for i in x:
        yield i

for i in number_generator1():
    print(i)
    
    
def number_generator2():
    x = [1,2,3]
    yield from x
    
for i in number_generator2():
    print(i)

0
1
2
0
1
2




def number_generator(stop):
    n = 0
    while n < stop:
        yield n
        n += 1
        
def three_generator():
    yield from number_generator(3)
    
for i in three_generator():
    print(i)

0
1
2




generator expression

for list

import time

def sleep_func(x):
    print("sleep...")
    time.sleep(1)
    return x

start = time.time()
l = [sleep_func(x) for x in range(5)]
for j,i in enumerate(l):print('step = %d, '%j,i)
end = time.time()
end-start
sleep...
sleep...
sleep...
sleep...
sleep...
step = 0,  0
step = 1,  1
step = 2,  2
step = 3,  3
step = 4,  4

5.009469032287598

for generator

import time

def sleep_func(x):
    print("sleep...")
    time.sleep(1)
    return x

start = time.time()
g = (sleep_func(x) for x in range(5))
for j,i in enumerate(g): print('step = %d, '%j,i)
end = time.time()
end-start
sleep...
step = 0,  0
sleep...
step = 1,  1
sleep...
step = 2,  2
sleep...
step = 3,  3
sleep...
step = 4,  4

5.008758068084717

memory size

import sys

# for list
print(sys.getsizeof( [i for i in range(100) if i % 2]),'   for list, iter_num:100')  
print(sys.getsizeof( [i for i in range(1000) if i % 2]),'   for list, iter_num:1000')

# for generator
print(sys.getsizeof( (i for i in range(100) if i % 2)),'   for generator, iter_num:100')
print(sys.getsizeof( (i for i in range(1000) if i % 2)),'   for generator, iter_num:1000')
528    for list, iter_num:100
4272    for list, iter_num:1000
88    for generator, iter_num:100
88    for generator, iter_num:1000





Coroutine : send!

Main routine and Sub routine

def sub_add(a,b):
    c = a + b
    print(c)
    print('sub add func')
def main_calc():
    sub_add(1,2)
    print('main calc func')
    
main_calc()
3
sub add func
main calc func




put signal

(yield)

def number_coroutine():
    while True:
        x = (yield)
        print(x)
co = number_coroutine()
next(co)
co.send(1)
co.send(2)
co.send(3)
1
2
3




get signal

(yield + variable)

def sum_coroutine():
    total = 0
    while True:
        x = (yield total)
        total += x
co = sum_coroutine()
print(next(co))
print(co.send(1))
print(co.send(2))
print(co.send(3))
0
1
3
6




exit

close

def number_coroutine():
    while True:
        x = (yield)
        print(x, end=' ')

co = number_coroutine()
next(co)

for i in range(20):
    co.send(i)

co.close()
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19




error handling

close

def number_coroutine():
    try:
        while True:
            x = (yield)
            print(x, end=' ')
    except GeneratorExit:
        print()
        print('coroutine exit')

co = number_coroutine()
next(co)

for i in range(20):
    co.send(i)

co.close()
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
coroutine exit




throw

def sum_coroutine():
    try:
        total = 0
        while True:
            x = (yield)
            total += x
    except RuntimeError as e:
        print(e)
        yield total

co = sum_coroutine()
next(co)

for i in range(20):
    co.send(i)

print(co.throw(RuntimeError,'exit through error'))
exit through error
190




get return

def accumulate():
    total = 0
    while True:
        x = (yield)
        if x is None:
            return total
        total += x

def sum_coroutine():
    while True:
        total = yield from accumulate()
        print(total)

co = sum_coroutine()
next(co)

for i in range(1,11):
    co.send(i)
co.send(None)

for i in range(1,101):
    co.send(i)
co.send(None)
55
5050




StopIteration

python - V : 3.6

def accumulate():
    total = 0
    while True:
        x = (yield)
        if x is None:
            raise StopIteration(total)
        total += x

def sum_coroutine():
    while True:
        total = yield from accumulate()
        print(total)

co = sum_coroutine()
next(co)

for i in range(1,11):
    co.send(i)
co.send(None)

for i in range(1,101):
    co.send(i)
co.send(None)
55
5050

python - V : 3.7

def accumulate():
    total = 0
    while True:
        x = (yield)
        if x is None:
            return total
        total += x

def sum_coroutine():
    while True:
        total = yield from accumulate()
        print(total)

co = sum_coroutine()
next(co)

for i in range(1,11):
    co.send(i)
co.send(None)

for i in range(1,101):
    co.send(i)
co.send(None)
55
5050





Collections

Example

ChainMap

from collections import ChainMap
from pprint import pprint

# dict > chainmap
Parent = {'music':'bach', 'art':'rembrandt'}
Me = {'art':'van gogh', 'opera':'carmen'}
cm = ChainMap(Me, Parent)

# chainmap > chainmap
chainmap_parent_generation = cm.parents
chainmap_me_generation = cm
chainmap_me_generation['me'] = 'ME'
chainmap_me_generation['sibling1'] = 'SIBLING1'
chainmap_me_generation['sibling2'] = 'SIBLING2'
del chainmap_me_generation['sibling2']
chainmap_child_generation = cm.new_child()

# chainmap viewer
chainmap_family_viewer = chainmap_child_generation.items()

# chainmap > list
chainmap_family_list = chainmap_child_generation.maps
OUTPUT

image image image image


# [common keys] : chainmap > list
chainmapkey_family = list(chainmap_child_generation)

# [items of the common keys] : chainmap > dict
chainmapdict_family = dict(chainmap_child_generation)
OUTPUT

image image image






Counter

from collections import Counter

l = ['red', 'blue', 'red', 'green', 'blue', 'blue']
cnt = Counter(l)

# count
cnt

# elements
sorted(cnt)
OUTPUT

image image






deque





defaultdict





Regular expression

URL

Explore regular expressions

re module

Raw string

print(r'abcd/n')
abcd/n




Search method

import re

re.search(r'abc','abcdef')
<_sre.SRE_Match object; span=(0, 3), match='abc'>
SUPPLEMENT
m = re.search(r'abc','abcdef')
print(m.start())
print(m.end())
print(m.group())
0
3
abc




Examples

import re

re.search(r'\d\d\d\w','efw2342efwefwef')
<_sre.SRE_Match object; span=(3, 7), match='2342'>
re.search(r'..\w\w','efw@#$23$@')
<_sre.SRE_Match object; span=(4, 8), match='#$23'>




Metacharacter

Meta(1) Expr
[abck] a,b,c,k
[abc.^] a,b,c,.,^
[a-d] range
[0-9] range
[a-z] range
[A-Z] range
[a-zA-Z0-9] range
[^0-9] not
. all of things
import re

re.search(r'[cbm]at','cat')
<_sre.SRE_Match object; span=(0, 3), match='cat'>
re.search(r'[0-9]haha','1hahah')
<_sre.SRE_Match object; span=(0, 5), match='1haha'>
re.search(r'[abc.^]aron','caron')
<_sre.SRE_Match object; span=(0, 5), match='caron'>
re.search(r'[^abc]aron','#aron')
<_sre.SRE_Match object; span=(0, 5), match='#aron'>
re.search(r'p.g','pig')
<_sre.SRE_Match object; span=(0, 3), match='pig'>




Meta(2) Expr
\d [0-9]
\D [^0-9]
\s space word
\S non-space word
\w [0-9a-zA-Z]
\W [^0-9a-zA-Z]
import re

re.search(r'\sand','apple and banana')
<_sre.SRE_Match object; span=(5, 9), match=' and'>
re.search(r'\Sand','apple and banana')

re.search(r'.and','pand')
<_sre.SRE_Match object; span=(0, 4), match='pand'>
re.search(r'\.and','.and')
<_sre.SRE_Match object; span=(0, 4), match='.and'>




Recurrence pattern

+ more than 1
* more than 0
{n} n
? regardless
import re

re.search(r'a[bcd]*b','abcbcbcbccb')
<_sre.SRE_Match object; span=(0, 11), match='abcbcbcbccb'>
re.search(r'b\w+a','banana')
<_sre.SRE_Match object; span=(0, 6), match='banana'>
re.search(r'i+','piigiii')
<_sre.SRE_Match object; span=(1, 3), match='ii'>
re.search(r'pi+g','pig')
<_sre.SRE_Match object; span=(0, 3), match='pig'>
re.search(r'pi*g','pig')
<_sre.SRE_Match object; span=(0, 3), match='pig'>
re.search(r'pi+g','pg')

re.search(r'pi*g','pg')
<_sre.SRE_Match object; span=(0, 2), match='pg'>
re.search(r'pi{3}g','piiig')
<_sre.SRE_Match object; span=(0, 5), match='piiig'>
re.search(r'pi{3,5}g','piiiig')
<_sre.SRE_Match object; span=(0, 6), match='piiiig'>
re.search(r'pi{3,5}g','piiiiiig')

re.search(r'httpf?','https://www.naver.com')
<_sre.SRE_Match object; span=(0, 4), match='http'>




Condition

^ start
$ end
import re

re.search(r'b\w+a','cabana')
<_sre.SRE_Match object; span=(2, 6), match='bana'>
re.search(r'^b\w+a','cabana')

re.search(r'^b\w+a','babana')
<_sre.SRE_Match object; span=(0, 6), match='babana'>
re.search(r'b\w+a$','cabana')
<_sre.SRE_Match object; span=(2, 6), match='bana'>
re.search(r'b\w+a$','cabanap')




Grouping

import re

m = re.search(r'(\w+)@(.+)','test@gmail.com')
print(m.group(1))
print(m.group(2))
print(m.group(0))
test
gmail.com
test@gmail.com





Get started with regular expressions





Into a world of powerful regular expression





Debugging

unittest

workspace

class Calculator:
    def add(self, a, b):
        return a + b

    def mul(self, a, b):
        return a * b

def Matmul(a, b):
    return a * b

unittest

import unittest, time
from workspace import Calculator, Matmul

class test_class(unittest.TestCase):
    def test_module_add(self):
        self.calculator = Calculator()
        self.assertEqual(self.calculator.add(3, 4), 7)

    def test_module_mul(self):
        time.sleep(1)
        self.fail()

class test_function(unittest.TestCase):
    def test_module_matmul(self):
        time.sleep(1)
        self.assertEqual(Matmul(3,5), 15)

unittest.main()





List of posts followed by this article


Reference


OUTPUT