Python Quick Start
2/5 (Fri)
2/19 (Fri)
Introduction
print "Hello World"
Introduction
Introduction
Jey大的30分鐘系列
Introduction
#755 (Jey Tsai)
Outline
-
Introduction
-
Python Basic
-
Python Advanced
-
Test in Python
-
Modules & Tool introduction
-
Q & A
Resources
Resources
Resources
David Beazley youtube channel
Resources
Resources
Resources
Python Basic
Python Basic
-
Python Coding Style (PEP8)
-
Documents
-
Builtin funtions
-
Loop
-
Exception
-
Python tooler
Python Coding Style (PEP8)
# class
CamleCase
# function
all_lower_underscore
# global
ALL_UPPER_UNDERSCORE
Python Coding Style (PEP8)
# public (variable, module, package)
all_lower_underscore
# protect
_var_
# private
__var
Python Coding Style (PEP8)
# avoid reserve variables
file_
# module internal used
_var
# not important(throwable var)
_
# python reserve
__var__
Documents
def show_me_the_money(me, action):
payroll_slip = ricky.sendmail()
if payroll_slip.money < ACCEPT_VAL:
me.do_B(action)
else:
me.do_G(action)
Documents
# function action?
wear_slipper_everyday()
wear_short_pants()
snitch_to_labor_affair()
# object action?
class BadAction(object):
def wear_slipper_everyday(self):
...
def wear_short_pants(self):
...
def snitch_to_labor_affair(self):
...
Documents
-
help()
-
dir()
-
repr()
-
str()
-
__doc__
Docstring Conventions
Demo Time
Builtin Functions
Builtin Functions
# attribute related
hasattr
getattr
setattr
# import related
__import__
# container, loop
iter
next
...
Loop - iteration
i = 0
while i < len(foo_list):
v = my_list[i]
print v
i += 1
for i in range(len(foo_list)):
print foo_list[i]
for _it in foo_list:
print _it
Loop - get idx and val
>>> foo = [1,2,3,4,5]
>>> for _idx in range(len(foo)):
... print _idx, foo[_idx]
...
0 1
1 2
2 3
3 4
4 5
>>> for _idx, _val in enumerate(foo):
... print _idx, _val
...
0 1
1 2
2 3
3 4
4 5
Loop - iteration
# Get dictionary value
>>> a = {"foo": "hello", "bar": "world"}
>>> for key in a:
... print a[key]
...
hello
world
>>> for _v in a.itervalues(): print _v
...
hello
world
Loop - iteration
>>> for _k,_v in a.items(): print _k,_v
...
foo hello
bar world
Loop - iteration:zip
>>> a = [1,2,3,4,5]
>>> b = [1,2,3]
>>> for _ in zip(a,b):
... print _
...
(1, 1)
(2, 2)
(3, 3)
>>> c = [5,5,6,6]
>>> zip(a,b,c)
[(1, 1, 5), (2, 2, 5), (3, 3, 6)]
Loop - iteration
>>> a = [1,2,3,4,5]
>>> b = [_ for _ in a if _ > 2]
>>> b
[3, 4, 5]
>>> c = [_ if _ > 3 else None for _ in a]
>>> c
[None, None, None, 4, 5]
>>> d = {str(_): _ for _ in a}
>>> d
{'1': 1, '3': 3, '2': 2, '5': 5, '4': 4}
Loop - iteration:map
>>> def fib(n):
... return 1 if n <=2 else fib(n-1)+fib(n-2)
...
>>> fib(10)
55
>>> map(fib, a)
[1, 1, 2, 3, 5]
>>> [fib(_) for _ in a]
[1, 1, 2, 3, 5]
>>> map(spam, [(1,2),(3,4)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: spam() takes exactly 2 arguments (1 given)
Loop - for ... else
>>> for _ in spam:
... if _ > 3:
... print "break"
... break
... else:
... print "loop finish"
break
>>> for _ in spam:
... pass
... else:
... print "loop finish"
loop finish
try... exception ... else
>>> try:
... 1/0
... except ZeroDivisionError:
... raise
... else:
... print "No exception"
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
integer division or modulo by zero
>>> try:
... 1/2
... except ZeroDivisionError:
... raise
... else:
... print "No exception"
No exception
Python Tooler
-
Decorator
-
Iterator
-
Generator
-
Context manager
-
Descriptor
@Decorator
-
Function Patch
-
Class Patch?
Iterator
>>> a = [5,5,6,6,]
>>> b = iter(a)
>>> b.next()
5
>>> b.next()
5
>>> b.next()
6
>>> b.next()
6
>>> b.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
Iterator?
>>> for _ in a: print _,
9 5 2 7
>>> for _ in a.__iter__(): print _,
9 5 2 7
>>> for _ in iter(a): print _,
9 5 2 7
Interpreter translate iterable object -> Iterator
Generator
yield
Generator
-
Generate a sequence
-
Generator can implement scheduler
-
Python3 enhance generator
-
Python3 add "generator deletate"
-
Python3 implement Coroutine via Generator
Context Manager
with
Context Manager
-
Resource Manager
-
with scope
-
__enter__(self)
-
__exit__(self, exc_ty, exc_val, tb)
-
contextlib
Descriptor
Protocol
-
__get__
-
__set__
-
__delete__
object attribute with “binding behavior”
Descriptor
object attribute with “binding behavior”
@property
Other useful protocols
-
__getitem__(self, key)
-
__setitem__(self, key, val)
-
__iter__(self)
-
__contains__(self, value)
-
__getattribute__(self, key)
-
__getattr__(self, key)
Python Advanced
-
os.path, os, sys, shutil, subprocess
-
File Operation
-
threading
-
multiprocessing
-
socket
os.path
os.path.abspath
os.path.basename
os.path.dirname
os.path.join
os.path.exists
os.path.isfile
os.path.isdir
os.path.islink
os.path.realpath
os.path.walk
OS
os.mkdir
os.chdir
os.geteuid
os.seteuid
os.getgid
os.getpid
os.fork
os.dup2
os.open
os.read
os.write
os.lseek
os.fstat
os.uname
os.popen(not recommand used)
File Operations
-
open
-
close
-
read & write
-
json
-
PyYAML
-
ConfigureParser
-
tarfile
-
zipfile
threading
Fake Thread
threading
threading
Multiprocessing
multiprocessing.Pool Fail?! Python Bugs??
>>> for _ in range(2):
... task = multiprocessing.Process(target=fib, args=(30,))
... tasks.append(task)
>>> tasks
[<Process(Process-15, initial)>, <Process(Process-16, initial)>]
>>> for _ in range(2):
... task = tasks[_]
... task.start()
... for _ in range(2):
... task = tasks[_]
... task.join()
Demo Time
Mutliprocessing
VS
threading
CPU bound
VS
IO bound
Socket
-
TCP
-
UDP
-
Domain Socket
-
socket + threading
-
socket +select
Demo Time
Test In Python
PyCon 2014
doctest
Test Your Documents are right
Unit Test?
PyUnit
PyUnit
-
Ref JUnit
-
Python 2.1 include
-
Python stdardard library: unittest
-
Python3 include "Mock" in unittest
unittest:glossary
-
Test Fixture: setUp & tearDown
-
Test Case: smallest unit of testing
-
Test Suite: collection of Tests
-
Test Runner: run & report
Definition: Python Document
unittest == PyUnit
-
Basic unittest
-
setUp & tearDown hierarchy
-
skip test
-
combine test
Mocking
@mock.patch(real, fake)
Demo Time
ctypes
ctypes
>>> from ctypes import *
>>> sdk = CDLL('libsynosdk.so.6')
>>> sdk.SLIBServiceIsEnabled('atalk')
1
Pros | Cons |
---|---|
Pure Python code | struct need rewrite |
C++ need C wrapper | |
Need to learn |
Standard Library
Modules & Tool introduction
3rd party
Modules & Tool introduction
Modules & Tool introduction
Modules & Tool introduction
Modules & Tool introduction
Modules & Tool introduction
-
ipython - Better Python shell
-
bpython - Better Python shell
-
ptpython - Great Python shell
-
ipython-notebooks - Past your code
Q & A
Python
By chang-ning tsai
Python
- 474